Repository: zajo/leaf Branch: master Commit: 50fe0ed3d44d Files: 185 Total size: 1012.5 KB Directory structure: gitextract_sux2q_ly/ ├── .drone/ │ └── drone.sh ├── .drone.star ├── .gitattributes ├── .github/ │ └── workflows/ │ ├── ci.yml │ └── gh-pages.yml ├── .gitignore ├── .travis.yml ├── .vscode/ │ ├── launch.json │ └── tasks.json ├── CMakeLists.txt ├── LICENSE_1_0.txt ├── README.md ├── appveyor.yml ├── benchmark/ │ ├── b.bat │ ├── b.sh │ ├── benchmark.md │ ├── deep_stack_leaf.cpp │ └── deep_stack_other.cpp ├── conanfile.py ├── doc/ │ ├── Jamfile │ ├── docinfo.html │ ├── leaf-theme.yml │ ├── leaf.adoc │ ├── rouge-github.css │ ├── whitepaper.md │ ├── zajo-dark.css │ └── zajo-light.css ├── example/ │ ├── asio_beast_leaf_rpc.cpp │ ├── capture_in_exception.cpp │ ├── capture_in_result.cpp │ ├── error_log.cpp │ ├── error_trace.cpp │ ├── exception_to_result.cpp │ ├── lua_callback_eh.cpp │ ├── lua_callback_result.cpp │ ├── print_file/ │ │ ├── print_file_eh.cpp │ │ ├── print_file_outcome_result.cpp │ │ ├── print_file_result.cpp │ │ └── readme.md │ ├── print_half.cpp │ └── readme.md ├── gen/ │ └── generate_single_header.py ├── include/ │ └── boost/ │ ├── leaf/ │ │ ├── capture.hpp │ │ ├── common.hpp │ │ ├── config/ │ │ │ ├── tls.hpp │ │ │ ├── tls_array.hpp │ │ │ ├── tls_cpp11.hpp │ │ │ ├── tls_freertos.hpp │ │ │ └── tls_globals.hpp │ │ ├── config.hpp │ │ ├── context.hpp │ │ ├── detail/ │ │ │ ├── all.hpp │ │ │ ├── demangle.hpp │ │ │ ├── function_traits.hpp │ │ │ ├── mp11.hpp │ │ │ ├── optional.hpp │ │ │ └── print.hpp │ │ ├── error.hpp │ │ ├── exception.hpp │ │ ├── handle_errors.hpp │ │ ├── on_error.hpp │ │ ├── pred.hpp │ │ ├── result.hpp │ │ └── to_variant.hpp │ └── leaf.hpp ├── index.html ├── meson.build ├── meson_options.txt ├── meta/ │ └── libraries.json ├── subprojects/ │ ├── lua.wrap │ └── tl_expected.wrap ├── test/ │ ├── BOOST_LEAF_ASSIGN_test.cpp │ ├── BOOST_LEAF_AUTO_test.cpp │ ├── BOOST_LEAF_CHECK_test.cpp │ ├── Jamfile.v2 │ ├── _compile-fail-BOOST_LEAF_ASSIGN.cpp │ ├── _compile-fail-BOOST_LEAF_AUTO.cpp │ ├── _compile-fail-arg_boost_error_info_1.cpp │ ├── _compile-fail-arg_boost_error_info_2.cpp │ ├── _compile-fail-arg_catch_1.cpp │ ├── _compile-fail-arg_catch_2.cpp │ ├── _compile-fail-arg_match_1.cpp │ ├── _compile-fail-arg_match_2.cpp │ ├── _compile-fail-arg_rvalue_ref.cpp │ ├── _compile-fail-diagnostic_info.cpp │ ├── _compile-fail-error_info.cpp │ ├── _compile-fail-exception_1.cpp │ ├── _compile-fail-exception_2.cpp │ ├── _compile-fail-new_error.cpp │ ├── _compile-fail-result_1.cpp │ ├── _compile-fail-result_2.cpp │ ├── _compile-fail-result_3.cpp │ ├── _compile-fail-result_4.cpp │ ├── _compile-fail-verbose_diagnostic_info.cpp │ ├── _hpp_capture_test.cpp │ ├── _hpp_common_test.cpp │ ├── _hpp_config_test.cpp │ ├── _hpp_context_test.cpp │ ├── _hpp_error_test.cpp │ ├── _hpp_exception_test.cpp │ ├── _hpp_handle_errors_test.cpp │ ├── _hpp_leaf_test.cpp │ ├── _hpp_on_error_test.cpp │ ├── _hpp_pred_test.cpp │ ├── _hpp_result_test.cpp │ ├── _hpp_to_variant_test.cpp │ ├── _test_ec.hpp │ ├── _test_res.hpp │ ├── accumulate_basic_test.cpp │ ├── accumulate_nested_error_exception_test.cpp │ ├── accumulate_nested_error_result_test.cpp │ ├── accumulate_nested_new_error_exception_test.cpp │ ├── accumulate_nested_new_error_result_test.cpp │ ├── accumulate_nested_success_exception_test.cpp │ ├── accumulate_nested_success_result_test.cpp │ ├── boost/ │ │ └── core/ │ │ ├── current_function.hpp │ │ └── lightweight_test.hpp │ ├── boost_exception_test.cpp │ ├── capture_exception_async_test.cpp │ ├── capture_exception_result_async_test.cpp │ ├── capture_exception_state_test.cpp │ ├── capture_exception_unload_test.cpp │ ├── capture_result_async_test.cpp │ ├── capture_result_state_test.cpp │ ├── capture_result_unload_test.cpp │ ├── context_activator_test.cpp │ ├── context_deduction_test.cpp │ ├── ctx_handle_all_test.cpp │ ├── ctx_handle_some_test.cpp │ ├── ctx_remote_handle_all_test.cpp │ ├── ctx_remote_handle_some_test.cpp │ ├── defer_basic_test.cpp │ ├── defer_nested_error_exception_test.cpp │ ├── defer_nested_error_result_test.cpp │ ├── defer_nested_new_error_exception_test.cpp │ ├── defer_nested_new_error_result_test.cpp │ ├── defer_nested_success_exception_test.cpp │ ├── defer_nested_success_result_test.cpp │ ├── diagnostic_info_test.cpp │ ├── diagnostic_info_test2.cpp │ ├── e_LastError_test.cpp │ ├── e_errno_test.cpp │ ├── error_code_test.cpp │ ├── error_id_test.cpp │ ├── exception_test.cpp │ ├── exception_to_result_test.cpp │ ├── function_traits_test.cpp │ ├── handle_all_other_result_test.cpp │ ├── handle_all_test.cpp │ ├── handle_basic_test.cpp │ ├── handle_some_other_result_test.cpp │ ├── handle_some_test.cpp │ ├── lightweight_test.hpp │ ├── match_member_test.cpp │ ├── match_test.cpp │ ├── match_value_test.cpp │ ├── multiple_errors_test.cpp │ ├── optional_test.cpp │ ├── preload_basic_test.cpp │ ├── preload_exception_test.cpp │ ├── preload_nested_error_exception_test.cpp │ ├── preload_nested_error_result_test.cpp │ ├── preload_nested_new_error_exception_test.cpp │ ├── preload_nested_new_error_result_test.cpp │ ├── preload_nested_success_exception_test.cpp │ ├── preload_nested_success_result_test.cpp │ ├── print_test.cpp │ ├── result_bad_result_test.cpp │ ├── result_implicit_conversion_test.cpp │ ├── result_load_test.cpp │ ├── result_ref_test.cpp │ ├── result_state_test.cpp │ ├── tls_array_alloc_test1.cpp │ ├── tls_array_alloc_test2.cpp │ ├── tls_array_alloc_test3.cpp │ ├── tls_array_test.cpp │ ├── to_variant_test.cpp │ ├── try_catch_error_id_test.cpp │ ├── try_catch_system_error_test.cpp │ ├── try_catch_test.cpp │ ├── try_exception_and_result_test.cpp │ ├── visibility_test.cpp │ ├── visibility_test_lib.cpp │ └── visibility_test_lib.hpp └── wasm.txt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .drone/drone.sh ================================================ #!/bin/bash # Copyright 2020 Rene Rivera, Sam Darwin # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE.txt or copy at http://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 if [ "$DRONE_JOB_BUILDTYPE" == "boost" ]; then echo '==================================> 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 echo '==================================> 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} fi ================================================ FILE: .drone.star ================================================ # 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") ================================================ FILE: .gitattributes ================================================ * text=auto !eol svneol=native#text/plain *.gitattributes text svneol=native#text/plain # Scriptish formats *.bat text svneol=native#text/plain *.bsh text svneol=native#text/x-beanshell *.cgi text svneol=native#text/plain *.cmd text svneol=native#text/plain *.js text svneol=native#text/javascript *.php text svneol=native#text/x-php *.pl text svneol=native#text/x-perl *.pm text svneol=native#text/x-perl *.py text svneol=native#text/x-python *.sh eol=lf svneol=LF#text/x-sh configure eol=lf svneol=LF#text/x-sh # Image formats *.bmp binary svneol=unset#image/bmp *.gif binary svneol=unset#image/gif *.ico binary svneol=unset#image/ico *.jpeg binary svneol=unset#image/jpeg *.jpg binary svneol=unset#image/jpeg *.png binary svneol=unset#image/png *.tif binary svneol=unset#image/tiff *.tiff binary svneol=unset#image/tiff *.svg text svneol=native#image/svg%2Bxml # Data formats *.pdf binary svneol=unset#application/pdf *.avi binary svneol=unset#video/avi *.doc binary svneol=unset#application/msword *.dsp text svneol=crlf#text/plain *.dsw text svneol=crlf#text/plain *.eps binary svneol=unset#application/postscript *.gz binary svneol=unset#application/gzip *.mov binary svneol=unset#video/quicktime *.mp3 binary svneol=unset#audio/mpeg *.ppt binary svneol=unset#application/vnd.ms-powerpoint *.ps binary svneol=unset#application/postscript *.psd binary svneol=unset#application/photoshop *.rdf binary svneol=unset#text/rdf *.rss text svneol=unset#text/xml *.rtf binary svneol=unset#text/rtf *.sln text svneol=native#text/plain *.swf binary svneol=unset#application/x-shockwave-flash *.tgz binary svneol=unset#application/gzip *.vcproj text svneol=native#text/xml *.vcxproj text svneol=native#text/xml *.vsprops text svneol=native#text/xml *.wav binary svneol=unset#audio/wav *.xls binary svneol=unset#application/vnd.ms-excel *.zip binary svneol=unset#application/zip # Text formats .htaccess text svneol=native#text/plain *.bbk text svneol=native#text/xml *.cmake text svneol=native#text/plain *.css text svneol=native#text/css *.dtd text svneol=native#text/xml *.htm text svneol=native#text/html *.html text svneol=native#text/html *.ini text svneol=native#text/plain *.log text svneol=native#text/plain *.mak text svneol=native#text/plain *.qbk text svneol=native#text/plain *.rst text svneol=native#text/plain *.sql text svneol=native#text/x-sql *.txt text svneol=native#text/plain *.xhtml text svneol=native#text/xhtml%2Bxml *.xml text svneol=native#text/xml *.xsd text svneol=native#text/xml *.xsl text svneol=native#text/xml *.xslt text svneol=native#text/xml *.xul text svneol=native#text/xul *.yml text svneol=native#text/plain boost-no-inspect text svneol=native#text/plain CHANGES text svneol=native#text/plain COPYING text svneol=native#text/plain INSTALL text svneol=native#text/plain Jamfile text svneol=native#text/plain Jamroot text svneol=native#text/plain Jamfile.v2 text svneol=native#text/plain Jamrules text svneol=native#text/plain Makefile* text svneol=native#text/plain README text svneol=native#text/plain TODO text svneol=native#text/plain # Code formats *.c text svneol=native#text/plain *.cpp text svneol=native#text/plain *.h text svneol=native#text/plain *.hpp text svneol=native#text/plain *.ipp text svneol=native#text/plain *.tpp text svneol=native#text/plain *.jam text svneol=native#text/plain *.java text svneol=native#text/plain ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: pull_request: push: branches: - master - develop - feature/** env: UBSAN_OPTIONS: print_stacktrace=1 jobs: posix: strategy: 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 install: g++-5 - toolset: gcc-6 cxxstd: "11,14,1z" os: ubuntu-18.04 install: g++-6 - toolset: gcc-7 cxxstd: "11,14" os: ubuntu-18.04 - toolset: gcc-8 cxxstd: "11,14,17,2a" os: ubuntu-18.04 install: g++-8 - toolset: gcc-9 cxxstd: "11,14,17,2a" os: ubuntu-20.04 - toolset: gcc-10 cxxstd: "11,14,17,2a" os: ubuntu-20.04 install: g++-10 - toolset: gcc-11 cxxstd: "11,14,17,2a" os: ubuntu-20.04 install: g++-11 - toolset: clang compiler: clang++-3.9 cxxstd: "11,14" os: ubuntu-18.04 install: clang-3.9 - toolset: clang compiler: clang++-4.0 cxxstd: "11,14" os: ubuntu-18.04 install: clang-4.0 - toolset: clang compiler: clang++-5.0 cxxstd: "11,14,1z" os: ubuntu-18.04 install: clang-5.0 - toolset: clang compiler: clang++-6.0 cxxstd: "11,14,17" os: ubuntu-18.04 install: clang-6.0 - toolset: clang compiler: clang++-7 cxxstd: "11,14,17" os: ubuntu-18.04 install: clang-7 - toolset: clang compiler: clang++-8 cxxstd: "11,14,17" os: ubuntu-20.04 install: clang-8 - toolset: clang compiler: clang++-9 cxxstd: "11,14,17,2a" 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" os: ubuntu-20.04 install: clang-12 - toolset: clang cxxstd: "11,14,17,2a" os: macos-10.15 runs-on: ${{matrix.os}} steps: - uses: actions/checkout@v2 - name: Install packages if: matrix.install run: sudo apt install ${{matrix.install}} - name: Setup Boost run: | REF=${GITHUB_BASE_REF:-$GITHUB_REF} BOOST_BRANCH=develop && [ "$REF" == "master" ] && BOOST_BRANCH=master || true 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 git submodule update --init tools/boostdep python tools/boostdep/depinst/depinst.py --git_args "--jobs 3" leaf ./bootstrap.sh ./b2 -d0 headers - name: Create user-config.jam if: matrix.compiler run: | echo "using ${{matrix.toolset}} : : ${{matrix.compiler}} ;" > ~/user-config.jam - name: Generate headers run: | cd ../boost-root/libs/leaf python gen/generate_single_header.py -i include/boost/leaf/detail/all.hpp -p include -o test/leaf.hpp boost/leaf - 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_capture0,leaf_release_capture0,leaf_debug_diag0,leaf_release_diag0,leaf_debug_embedded,leaf_release_embedded,leaf_debug_leaf_hpp,leaf_release_leaf_hpp windows: strategy: fail-fast: false matrix: include: - toolset: msvc-14.2 cxxstd: "14,17,latest" addrmd: 32,64 os: windows-2019 - toolset: gcc cxxstd: "11,14,17,2a" addrmd: 64 os: windows-2019 runs-on: ${{matrix.os}} steps: - uses: actions/checkout@v2 - name: Setup Boost shell: cmd run: | if "%GITHUB_BASE_REF%" == "" set GITHUB_BASE_REF=%GITHUB_REF% set BOOST_BRANCH=develop if "%GITHUB_BASE_REF%" == "master" set BOOST_BRANCH=master 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\ git submodule update --init tools/boostdep python tools/boostdep/depinst/depinst.py --git_args "--jobs 3" leaf 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 - 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_capture0,leaf_release_capture0,leaf_debug_diag0,leaf_release_diag0,leaf_debug_embedded,leaf_release_embedded,leaf_debug_leaf_hpp,leaf_release_leaf_hpp ================================================ FILE: .github/workflows/gh-pages.yml ================================================ name: documentation on: push: branches: - master jobs: publish: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install packages run: | sudo gem install asciidoctor asciidoctor-pdf rouge - name: Setup Boost run: | REF=${GITHUB_BASE_REF:-$GITHUB_REF} BOOST_BRANCH=develop && [ "$REF" == "master" ] && BOOST_BRANCH=master || true 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 git submodule update --init tools/build git submodule update --init libs/config ./bootstrap.sh - name: Create user-config.jam run: | echo "using asciidoctor ;" > ~/user-config.jam - name: Build documentation run: | cd ../boost-root/libs/leaf/doc ../../../b2 - name: Generate single header run: | REF=$(git show-ref $GITHUB_REF --hash) cd ../boost-root/libs/leaf 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 with: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} BRANCH: gh-pages FOLDER: ../boost-root/libs/leaf/doc/html ================================================ FILE: .gitignore ================================================ .DS_Store .Trashes *.suo *.user *.log *.sdf *.opensdf *.db *.opendb bld/* doc/html/* snippets/* subprojects/*/ .vscode/ipch/* .vscode/settings.json .vscode/c_cpp_properties.json benchmark/tl/* test/leaf.hpp doc/leaf.html ================================================ FILE: .travis.yml ================================================ # 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 ================================================ FILE: .vscode/launch.json ================================================ { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "(lldb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/bld/debug/capture_exception_async_test", "args": [ ], "cwd": "${workspaceFolder}", "stopAtEntry": false, "externalConsole": false, "MIMode": "lldb" } ] } ================================================ FILE: .vscode/tasks.json ================================================ { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "Configure 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", "problemMatcher": [] }, { "label": "Configure Meson build directories (no Boost)", "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", "problemMatcher": [] }, { "label": "Generate leaf.hpp", "type": "shell", "command": "cd ${workspaceRoot} && python gen/generate_single_header.py -i include/boost/leaf/detail/all.hpp -p ${workspaceRoot}/include -o ${workspaceRoot}/test/leaf.hpp boost/leaf", "problemMatcher": [] }, { "group": { "kind": "build", "isDefault": true }, "label": "Build all unit tests and examples (debug)", "type": "shell", "command": "cd ${workspaceRoot}/bld/debug && ninja", "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", "${workspaceRoot}/bld/debug" ] } }, { "group": "test", "label": "Run all unit tests (debug)", "type": "shell", "dependsOn": [ "Generate leaf.hpp" ], "command": "cd ${workspaceRoot}/bld/debug_leaf_hpp && ninja && meson test && cd ${workspaceRoot}/bld/debug && ninja && meson test", "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", "${workspaceRoot}/bld/debug" ] } }, { "group": "test", "label": "Run all unit tests (release)", "type": "shell", "dependsOn": [ "Generate leaf.hpp" ], "command": "cd ${workspaceRoot}/bld/release && ninja && meson test && cd ${workspaceRoot}/bld/release_leaf_hpp && ninja && meson test", "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", "${workspaceRoot}/bld/release" ] } }, { "group": "test", "label": "Run all unit tests (b2, all configurations)", "type": "shell", "dependsOn": [ "Generate leaf.hpp" ], "command": "../../b2 test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_leaf_hpp,leaf_release_leaf_hpp exception-handling=on,off cxxstd=11,14,1z,17 && ../../b2 test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_leaf_hpp,leaf_release_leaf_hpp,leaf_debug_embedded,leaf_release_embedded exception-handling=off rtti=off cxxstd=11,14,1z,17", "windows": { "command": "..\\..\\b2 test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_leaf_hpp,leaf_release_leaf_hpp exception-handling=on,off cxxstd=14,17,latest && ..\\..\\b2 test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_leaf_hpp,leaf_release_leaf_hpp,leaf_debug_embedded,leaf_release_embedded exception-handling=off rtti=off cxxstd=14,17,latest", }, "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", "${workspaceRoot}/bld/release" ] } }, { "group": { "kind": "test", "isDefault": true }, "label": "Test current editor file", "type": "shell", "command": "cd ${workspaceRoot}/bld/debug && ninja && { meson test ${fileBasenameNoExtension} || cat ./meson-logs/testlog.txt }", "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", "${workspaceRoot}/bld/debug" ] } } ] } ================================================ FILE: CMakeLists.txt ================================================ # Generated by `boostdep --cmake leaf` # Copyright 2020 Peter Dimov # Distributed under the Boost Software License, Version 1.0. # https://www.boost.org/LICENSE_1_0.txt cmake_minimum_required(VERSION 3.5...3.16) project(boost_leaf VERSION "${BOOST_SUPERPROJECT_VERSION}" LANGUAGES CXX) add_library(boost_leaf INTERFACE) add_library(Boost::leaf ALIAS boost_leaf) target_include_directories(boost_leaf INTERFACE include) if(BUILD_TESTING AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test/CMakeLists.txt") add_subdirectory(test) endif() ================================================ FILE: LICENSE_1_0.txt ================================================ Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # LEAF > A lightweight error handling library for C++11. ## Documentation https://boostorg.github.io/leaf/ ## Features * Portable single-header format, no dependencies. * Tiny code size when configured 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. * Can be used with or without exception handling. ## Support * [cpplang on Slack](https://Cpplang.slack.com) (use the `#boost` channel) * [Boost Users Mailing List](https://lists.boost.org/mailman/listinfo.cgi/boost-users) * [Boost Developers Mailing List](https://lists.boost.org/mailman/listinfo.cgi/boost) ## Distribution 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). 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]. ================================================ FILE: appveyor.yml ================================================ # 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% ================================================ FILE: benchmark/b.bat ================================================ ninja del benchmark.csv deep_stack_leaf deep_stack_tl deep_stack_result deep_stack_outcome ================================================ FILE: benchmark/b.sh ================================================ ninja rm benchmark.csv ./deep_stack_leaf ./deep_stack_tl ./deep_stack_result ./deep_stack_outcome ================================================ FILE: benchmark/benchmark.md ================================================ # 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 ================================================ FILE: benchmark/deep_stack_leaf.cpp ================================================ // 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 { [[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; [[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; } ================================================ FILE: benchmark/deep_stack_other.cpp ================================================ // 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; } ================================================ FILE: conanfile.py ================================================ 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 = [] ================================================ FILE: doc/Jamfile ================================================ # Copyright 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://www.boost.org/LICENSE_1_0.txt) project doc/leaf ; import 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 ; pdf leaf.pdf : leaf.adoc : book pdf-themesdir=. pdf-theme=leaf ; install pdf_ : leaf.pdf : html ; alias boostdoc ; explicit boostdoc ; alias boostrelease : html_ ; explicit boostrelease ; ================================================ FILE: doc/docinfo.html ================================================ ================================================ FILE: doc/leaf-theme.yml ================================================ extends: default base: font: color: #404040 literal: font: family: Courier color: #000000 admonition: icon: note: stroke-color: #000000 tip: stroke-color: #000000 warning: stroke-color: #FF5100 important: stroke-color: #FF5100 caution: stroke-color: #FF5100 conum: font: glyphs: circled color: #000000 link: text-decoration: underline text-decoration-width: 0.5 font-color: #000000 ================================================ FILE: doc/leaf.adoc ================================================ :last-update-label!: :icons: font :prewrap!: :docinfo: shared :stylesheet: zajo-dark.css :source-highlighter: rouge ifdef::backend-pdf[] = LEAF endif::[] ifndef::backend-pdf[] = LEAFpass:[
] endif::[] Lightweight Error Augmentation Framework written in {CPP}11 | Emil Dotchevski ifndef::backend-pdf[] :toc: left :toclevels: 3 :toc-title: [.text-right] https://github.com/boostorg/leaf[GitHub] | https://boostorg.github.io/leaf/leaf.pdf[PDF] endif::[] [abstract] == Abstract 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. * 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. * Can be used with or without exception handling. ==== 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: <> \| <> \| <> \| <> \| <> |==== 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]] == Distribution LEAF is distributed under the http://www.boost.org/LICENSE_1_0.txt[Boost Software License, Version 1.0]. 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). NOTE: LEAF does not depend on Boost or other libraries. [[tutorial]] == Tutorial What is a failure? It is simply the inability of a function to return a valid result, instead producing an error object describing the reason for the failure. 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. Therefore what would have been a `result` becomes `result`, which stores the discriminant and (optionally) a `T`, while the `E` is communicated directly to the error handling scope where it is needed. The benefit of this decomposition is that `result` becomes extremely lightweight, as it is not coupled with error types; further, error objects are communicated in constant time (independent of the call stack depth). Even very large objects are handled efficiently without dynamic memory allocation. === Reporting Errors A function that reports an error is pretty straight-forward: [source,c++] ---- enum class err1 { e1, e2, e3 }; leaf::result f() { .... if( error_detected ) return leaf::new_error( err1::e1 ); // Pass an error object of any type // Produce and return a T. } ---- [.text-right] <> | <> ''' [[checking_for_errors]] === Checking for Errors Checking for errors communicated by a `leaf::result` works as expected: [source,c++] ---- leaf::result g() { leaf::result r = f(); if( !r ) return r.error(); T const & v = r.value(); // Use v to produce a valid U } ---- [.text-right] <> TIP: The the result of `r.error()` is compatible with any instance of the `leaf::result` template. In the example above, note that `g` returns a `leaf::result`, while `r` is of type `leaf::result`. The boilerplate `if` statement can be avoided using `BOOST_LEAF_AUTO`: [source,c++] ---- leaf::result g() { BOOST_LEAF_AUTO(v, f()); // Bail out on error // Use v to produce a valid U } ---- [.text-right] <> `BOOST_LEAF_AUTO` can not be used with `void` results; in that case, to avoid the boilerplate `if` statement, use `BOOST_LEAF_CHECK`: [source,c++] ---- leaf::result f(); leaf::result g() { BOOST_LEAF_CHECK(f()); // Bail out on error return 42; } ---- [.text-right] <> On implementations that define `pass:[__GNUC__]` (e.g. GCC/clang), the `BOOST_LEAF_CHECK` macro definition takes advantage of https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html[GNU C statement expressions]. In this case, in addition to its portable usage with `result`, `BOOST_LEAF_CHECK` can be used in expressions with non-`void` result types: [source,c++] ---- leaf::result f(); float g(int x); leaf::result t() { return g( BOOST_LEAF_CHECK(f()) ); } ---- The following is the portable alternative: [source,c++] ---- leaf::result t() { BOOST_LEAF_AUTO(x, f()); return g(x); } ---- ''' [[tutorial-error_handling]] === Error Handling Error handling scopes must use a special syntax to indicate that they need to access error objects. The following excerpt attempts several operations and handles errors of type `err1`: [source,c++] ---- leaf::result r = leaf::try_handle_some( []() -> leaf::result { BOOST_LEAF_AUTO(v1, f1()); BOOST_LEAF_AUTO(v2, f2()); return g(v1, v2); }, []( err1 e ) -> leaf::result { if( e == err1::e1 ) .... // Handle err1::e1 else .... // Handle any other err1 value } ); ---- [.text-right] <> | <> | <> The first lambda passed to `try_handle_some` is executed first; 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. It is possible for an error handler to specify that it can only deal with some values of a given error type: [source,c++] ---- leaf::result r = leaf::try_handle_some( []() -> leaf::result { BOOST_LEAF_AUTO(v1, f1()); BOOST_LEAF_AUTO(v2, f2()); return g(v1. v2); }, []( leaf::match ) -> leaf::result { // Handle err::e1 or err1::e3 }, []( err1 e ) -> leaf::result { // Handle any other err1 value } ); ---- [.text-right] <> | <> | <> | <> LEAF considers the provided error handlers in order, and calls the first one for which it can supply arguments, based on the error objects currently being communicated. Above: * 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`. * Otherwise the second error handler will be called if an error object of type `err1` is available, regardless of its value. * Otherwise `leaf::try_handle_some` fails. It is possible for an error handler to conditionally leave the current failure unhandled: [source,c++] ---- leaf::result r = leaf::try_handle_some( []() -> leaf::result { BOOST_LEAF_AUTO(v1, f1()); BOOST_LEAF_AUTO(v2, f2()); return g(v1. v2); }, []( err1 e, leaf::error_info const & ei ) -> leaf::result { if( <> ) return valid_U; else return ei.error(); } ); ---- [.text-right] <> | <> | <> | <> Any error handler can take an argument of type `leaf::error_info const &` to get access to generic information about the error being handled; in this case we use the `error` member function, which returns the unique <> of the current error; we use it to initialize the returned `leaf::result`, effectively propagating the current error out of `try_handle_some`. TIP: If we wanted to signal a new error (rather than propagating the current error), in the `return` statement we would invoke the `leaf::new_error` function. If we want to ensure that all possible failures are handled, we use `leaf::try_handle_all` instead of `leaf::try_handle_some`: [source,c++] ---- U r = leaf::try_handle_all( []() -> leaf::result { BOOST_LEAF_AUTO(v1, f1()); BOOST_LEAF_AUTO(v2, f2()); return g(v1. v2); }, []( leaf::match ) -> U { // Handle err::e1 }, []( err1 e ) -> U { // Handle any other err1 value }, []() -> U { // Handle any other failure } ); ---- [.text-right] <> The `leaf::try_handle_all` function enforces at compile time that at least one of the supplied error handlers takes no arguments (and therefore is able to handle any failure). In addition, all error handlers are forced to return a valid `U`, rather than a `leaf::result`, so that `leaf::try_handle_all` is guaranteed to succeed, always. ''' === Working with Different Error Types It is of course possible to provide different handlers for different error types: [source,c++] ---- enum class err1 { e1, e2, e3 }; enum class err2 { e1, e2 }; .... leaf::result r = leaf::try_handle_some( []() -> leaf::result { BOOST_LEAF_AUTO(v1, f1()); BOOST_LEAF_AUTO(v2, f2()); return g(v1, v2); }, []( err1 e ) -> leaf::result { // Handle errors of type `err1`. }, []( err2 e ) -> leaf::result { // Handle errors of type `err2`. } ); ---- [.text-right] <> | <> | <> Recall that 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; * otherwise, `leaf::try_handle_some` fails. ''' === Working with Multiple Error Objects The `leaf::new_error` function can be invoked with multiple error objects, for example to communicate an error code and the relevant file name: [source,c++] ---- enum class io_error { open_error, read_error, write_error }; struct e_file_name { std::string value; } leaf::result open_file( char const * name ) { .... if( open_failed ) return leaf::new_error(io_error::open_error, e_file_name {name}); .... } ---- [.text-right] <> | <> Similarly, error handlers may take multiple error objects as arguments: [source,c++] ---- leaf::result r = leaf::try_handle_some( []() -> leaf::result { BOOST_LEAF_AUTO(f, open_file(fn)); .... }, []( io_error ec, e_file_name fn ) -> leaf::result { // Handle I/O errors when a file name is available. }, []( io_error ec ) -> leaf::result { // Handle I/O errors when no file name is available. } ); ---- [.text-right] <> | <> | <> Once again, error handlers are considered in order: * The first error handler will be used if an error object of type `io_error` _and_ and error_object of type `e_file_name` are available; * otherwise, the second error handler will be used if an error object of type `io_error` is avaliable; * otherwise, `leaf_try_handle_some` fails. An alternative way to write the above is to provide a single error handler that takes the `e_file_name` argument as a pointer: [source,c++] ---- leaf::result r = leaf::try_handle_some( []() -> leaf::result { BOOST_LEAF_AUTO(f, open_file(fn)); .... }, []( io_error ec, e_file_name const * fn ) -> leaf::result { if( fn ) .... // Handle I/O errors when a file name is available. else .... // Handle I/O errors when no file name is available. } ); ---- [.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. TIP: Error handlers can take arguments by value, by (`const`) reference or as a (`const`) pointer. It the latter case, changes to the error object state will be propagated up the call stack if the failure is not handled. [[tutorial-augmenting_errors]] === Augmenting Errors Let's say we have a function `parse_line` which could fail due to an `io_error` or a `parse_error`: [source,c++] ---- enum class io_error { open_error, read_error, write_error }; enum class parse_error { bad_syntax, bad_range }; leaf::result parse_line( FILE * f ); ---- The `leaf::on_error` function can be used to automatically associate additional error objects with any failure that is "in flight": [source,c++] ---- struct e_line { int value; }; leaf::result process_file( FILE * f ) { for( int current_line = 1; current_line != 10; ++current_line ) { auto load = leaf::on_error( e_line {current_line} ); BOOST_LEAF_AUTO(v, parse_line(f)); // use v } } ---- [.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. Such failures can then be handled like so: [source,c++] ---- leaf::result r = leaf::try_handle_some( [&]() -> leaf::result { BOOST_LEAF_CHECK( process_file(f) ); }, []( parse_error e, e_line current_line ) { std::cerr << "Parse error at line " << current_line.value << std::endl; }, []( io_error e, e_line current_line ) { std::cerr << "I/O error at line " << current_line.value << std::endl; }, []( io_error e ) { std::cerr << "I/O error" << std::endl; } ); ---- [.text-right] <> | <> The following is equivalent, and perhaps simpler: [source,c++] ---- leaf::result r = leaf::try_handle_some( []() -> leaf::result { BOOST_LEAF_CHECK( process_file(f) ); }, []( parse_error e, e_line current_line ) { std::cerr << "Parse error at line " << current_line.value << std::endl; }, []( io_error e, e_line const * current_line ) { std::cerr << "Parse error"; if( current_line ) std::cerr << " at line " << current_line->value; std::cerr << std::endl; } ); ---- ''' [[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: [source,c++] ---- leaf::result r = leaf::try_handle_some( []() -> leaf::result { BOOST_LEAF_CHECK( process_file(f) ); }, []( std::bad_alloc const & ) { std::cerr << "Out of memory!" << std::endl; }, []( parse_error e, e_line l ) { std::cerr << "Parse error at line " << l.value << std::endl; }, []( io_error e, e_line const * l ) { std::cerr << "Parse error"; if( l ) std::cerr << " at line " << l.value; std::cerr << std::endl; } ); ---- [.text-right] <> | <> | <> Above, we have simply added an error handler that takes a `std::bad_alloc`, and everything "just works" as expected: LEAF will dispatch error handlers correctly no matter if failures are communicated via `leaf::result` or by an exception. Of course, if we use exception handling exclusively, we do not need `leaf::result` at all. In this case we use `leaf::try_catch`: [source,c++] ---- leaf::try_catch( [] { process_file(f); }, []( std::bad_alloc const & ) { std::cerr << "Out of memory!" << std::endl; }, []( parse_error e, e_line l ) { std::cerr << "Parse error at line " << l.value << std::endl; }, []( io_error e, e_line const * l ) { std::cerr << "Parse error"; if( l ) std::cerr << " at line " << l.value; std::cerr << std::endl; } ); ---- [.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? 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: [source,c++] ---- enum class err1 { e1, e2, e3 }; enum class err2 { e1, e2 }; .... leaf::result f() { .... if( error_detected ) return leaf::new_error(err1::e1, err2::e2); // Produce and return a T. } ---- [.text-right] <> | <> When using exception handling this becomes: [source,c++] ---- enum class err1 { e1, e2, e3 }; enum class err2 { e1, e2 }; T f() { if( error_detected ) leaf::throw_exception(err1::e1, err2::e2); // Produce and return a T. } ---- [.text-right] <> 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 procedure. 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::throw_exception`: [source,c++] ---- 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`. 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 <>): [source,c++] ---- int parse_line( FILE * f ); // Throws struct e_line { int value; }; void process_file( FILE * f ) { for( int current_line = 1; current_line != 10; ++current_line ) { auto load = leaf::on_error( e_line {current_line} ); int v = parse_line(f); // use v } } ---- [.text-right] <> ''' === Using External `result` Types Static type checking creates difficulties in error handling interoperability in any non-trivial project. Using exception handling alleviates this problem somewhat because in that case error types are not burned into function signatures, so errors easily punch through multiple layers of APIs; but this doesn't help {CPP} in general because the community is fractured on the issue of exception handling. That debate notwithstanding, the reality is that {CPP} programs need to handle errors communicated through multiple layers of APIs via a plethora of error codes, `result` types and exceptions. LEAF enables application developers to shake error objects out of each individual library's `result` type and send them to error handling scopes verbatim. Here is an example: [source,c++] ---- lib1::result foo(); lib2::result bar(); int g( int a, int b ); leaf::result f() { auto a = foo(); if( !a ) return leaf::new_error( a.error() ); auto b = bar(); if( !b ) return leaf::new_error( b.error() ); return g( a.value(), b.value() ); } ---- [.text-right] <> | <> Later we simply call `leaf::try_handle_some` passing an error handler for each type: [source,c++] ---- leaf::result r = leaf::try_handle_some( []() -> leaf::result { return f(); }, []( lib1::error_code ec ) -> leaf::result { // Handle lib1::error_code }, []( lib2::error_code ec ) -> leaf::result { // Handle lib2::error_code } ); } ---- [.text-right] <> | <> A possible complication is that we might not have the option to return `leaf::result` from `f`: a third party API may impose a specific signature on it, forcing it to return a library-specific `result` type. This would be the case when `f` is intended to be used as a callback: [source,c++] ---- void register_callback( std::function()> const & callback ); ---- Can we use LEAF in this case? Actually we can, as long as `lib3::result` is able to communicate a `std::error_code`. We just have to let LEAF know, by specializing the `is_result_type` template: [source,c++] ---- namespace boost { namespace leaf { template struct is_result_type>: std::true_type; } } ---- [.text-right] <> With this in place, `f` works as before, even though `lib3::result` isn't capable of transporting `lib1` errors or `lib2` errors: [source,c++] ---- lib1::result foo(); lib2::result bar(); int g( int a, int b ); lib3::result f() { auto a = foo(); if( !a ) return leaf::new_error( a.error() ); auto b = bar(); if( !b ) return leaf::new_error( b.error() ); return g( a.value(), b.value() ); } ---- [.text-right] <> The object returned by `leaf::new_error` converts implicitly to `std::error_code`, using a LEAF-specific `error_category`, which makes `lib3::result` compatible with `leaf::try_handle_some` (and with `leaf::try_handle_all`): [source,c++] ---- lib3::result r = leaf::try_handle_some( []() -> lib3::result { return f(); }, []( lib1::error_code ec ) -> lib3::result { // Handle lib1::error_code }, []( lib2::error_code ec ) -> lib3::result { // Handle lib2::error_code } ); } ---- [.text-right] <> ''' [[tutorial-model]] === Error Communication Model ==== `noexcept` API The following figure illustrates how error objects are transported when using LEAF without exception handling: .LEAF noexcept Error Communication Model image::LEAF-1.png[] The arrows pointing down indicate the call stack order for the functions `f1` through `f5`: higher level functions calling lower level functions. Note the call to `on_error` in `f3`: it caches the passed error objects of types `E1` and `E3` in the returned object `load`, where they stay ready to be communicated in case any function downstream from `f3` reports an error. Presumably these objects are relevant to any such failure, but are conveniently accessible only in this scope. _Figure 1_ depicts the condition where `f5` has detected an error. It calls `leaf::new_error` to create a new, unique `error_id`. The passed error object of type `E2` is immediately loaded in the first active `context` object that provides static storage for it, found in any calling scope (in this case `f1`), and is associated with the newly-generated `error_id` (solid arrow); The `error_id` itself is returned to the immediate caller `f4`, usually stored in a `result` object `r`. That object takes the path shown by dashed arrows, as each error neutral function, unable to handle the failure, forwards it to its immediate caller in the returned value -- until an error handling scope is reached. When the destructor of the `load` object in `f3` executes, it detects that `new_error` was invoked after its initialization, loads the cached objects of types `E1` and `E3` in the first active `context` object that provides static storage for them, found in any calling scope (in this case `f1`), and associates them with the last generated `error_id` (solid arrow). When the error handling scope `f1` is reached, it probes `ctx` for any error objects associated with the `error_id` it received from `f2`, and processes a list of user-provided error handlers, in order, until it finds a handler with arguments that can be supplied using the available (in `ctx`) error objects. That handler is called to deal with the failure. ==== Exception Handling API The following figure illustrates the slightly different error communication model used when errors are reported by throwing exceptions: .LEAF Error Communication Model Using Exception Handling image::LEAF-2.png[] The main difference is that the call to `new_error` is implicit in the call to the function template `leaf::throw_exception`, which in this case takes an exception object of type `Ex`, and throws an exception object of unspecified type that derives publicly from `Ex`. [[tutorial-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. 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`. To support this tricky use case, LEAF provides the function <>, which returns the error ID returned by the most recent call (from this thread) to <>. One possible approach to solving the problem is to use the following logic (implemented by the <> type): . Before calling the uncooperative API, call <> and cache the returned value. . Call the API, then call `current_error` again: .. If this returns the same value as before, pass the error objects to `new_error` to associate them with a new `error_id`; .. else, associate the error objects with the `error_id` value returned by the second call to `current_error`. Note that if the above logic is nested (e.g. one function calling another), `new_error` will be called only by the inner-most function, because that call guarantees that all calling functions will hit the `else` branch. For a detailed tutorial see <>. TIP: To avoid ambiguities, whenever possible, use the <> function template to throw 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. 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 <>: [source,c++] ---- return leaf::new_error(ec, e_input_name{n1}, e_output_name{n2}); ---- Alternatively, error objects may be loaded using a `result` that is already communicating an error. This way they become associated with that error, rather than with a new error: [source,c++] ---- leaf::result f() noexcept; leaf::result g( char const * fn ) noexcept { if( leaf::result r = f() ) { <1> ....; return { }; } else { return r.load( e_file_name{fn} ); <2> } } ---- [.text-right] <> | <> <1> Success! Use `r.value()`. <2> `f()` has failed; here we associate an additional `e_file_name` with the error. However, this association occurs iff in the call stack leading to `g` there are error handlers that take an `e_file_name` argument. Otherwise, the object passed to `load` is discarded. In other words, the passed objects are loaded iff the program actually uses them to handle errors. 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: + [source,c++] ---- struct info { .... }; info compute_info() noexcept; leaf::result operation( char const * file_name ) noexcept { if( leaf::result r = try_something() ) { <1> .... return { }; } else { return r.load( <2> [&] { return compute_info(); } ); } } ---- [.text-right] <> | <> + <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. + * 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. + 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: + [source,c++] ---- struct e_relevant_file_names { std::vector value; }; leaf::result operation( char const * file_name ) noexcept { if( leaf::result r = try_something() ) { <1> .... return { }; } else { return r.load( <2> [&](e_relevant_file_names & e) { e.value.push_back(file_name); } ); } } ---- [.text-right] <> | <> + <1> Success! Use `r.value()`. <2> `try_something` has failed -- add `file_name` to the `e_relevant_file_names` object, associated with the `error_id` communicated in `r`. Note, however, that the passed function will only be called iff in the call stack there are error handlers that take an `e_relevant_file_names` object. ''' [[tutorial-on_error]] === Using `on_error` 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: [source,c++] ---- leaf::result parse_info( FILE * f ) noexcept; <1> leaf::result parse_file( char const * file_name ) noexcept { auto load = leaf::on_error(leaf::e_file_name{file_name}); <2> if( FILE * f = fopen(file_name,"r") ) { auto r = parse_info(f); fclose(f); return r; } else return leaf::new_error( error_enum::file_open_error ); } ---- [.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. TIP: `on_error` -- like `load` -- 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. 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: [source,c++] ---- void read_file(FILE * f) { auto load = leaf::on_error([]{ return e_errno{errno}; }); .... size_t nr1=fread(buf1,1,count1,f); if( ferror(f) ) leaf::throw_exception(); size_t nr2=fread(buf2,1,count2,f); if( ferror(f) ) leaf::throw_exception(); size_t nr3=fread(buf3,1,count3,f); if( ferror(f) ) leaf::throw_exception(); .... } ---- Above, if `throw_exception` is called, 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 <>. ''' [[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. Consider this error code enum: [source,c++] ---- enum class my_error { e1=1, e2, e3 }; ---- We could handle `my_error` errors like so: [source,c++] ---- return leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( my_error e ) { <1> switch(e) { case my_error::e1: ....; <2> break; case my_error::e2: case my_error::e3: ....; <3> break; default: ....; <4> 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. This can be rewritten using the <> predicate to organize the different cases in different error handlers. The following is equivalent: [source,c++] ---- return leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( 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. In particular, `match` works great with `std::error_code`. The following handler is designed to handle `ENOENT` errors: [source,c++] ---- []( leaf::match ) { } ---- 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: [source,c++] ---- []( leaf::match, std::errc::no_such_file_or_directory> ) { } ---- 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): [source,c++] ---- []( std::error_code, leaf::category> ) { } ---- TIP: See <> for more examples. 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. * <> 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 <>. NOTE: See also <>. ''' [[tutorial-binding_handlers]] === Binding Error Handlers in a `std::tuple` Consider this snippet: [source,c++] ---- leaf::try_handle_all( [&] { return f(); // returns leaf::result }, [](my_error_enum x) { ... }, [](read_file_error_enum y, e_file_name const & fn) { ... }, [] { ... }); ---- [.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`: [source,c++] ---- leaf::try_handle_all( [&] { return g(); // returns leaf::result }, [](my_error_enum x) { ... }, [](read_file_error_enum y, e_file_name const & fn) { ... }, [] { ... }); ---- That works, but it is better to bind our error handlers in a `std::tuple`: [source,c++] ---- auto error_handlers = std::make_tuple( [](my_error_enum x) { ... }, [](read_file_error_enum y, e_file_name const & fn) { ... }, [] { ... }); ---- The `error_handlers` tuple can later be used with any error handling function: [source,c++] ---- leaf::try_handle_all( [&] { // Operations which may fail <1> }, error_handlers ); leaf::try_handle_all( [&] { // Different operations which may fail <2> }, error_handlers ); <3> ---- [.text-right] <> | <> <1> One set of operations which may fail... <2> A different set of operations which may fail... <3> ... both using the same `error_handlers`. Error handling functions accept a `std::tuple` of error handlers in place of any error handler. The behavior is as if the tuple is unwrapped in-place. ''' [[tutorial-async]] === Transporting Error Objects Between Threads 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. LEAF offers two interfaces for this purpose, one using `result`, and another designed for programs that use exception handling. [[tutorial-async_result]] ==== Using `result` Let's assume we have a `task` that we want to launch asynchronously, which produces a `task_result` but could also fail: [source,c++] ---- 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: [source,c++] ---- std::future> launch_task() noexcept { return std::async( std::launch::async, [&] { std::shared_ptr ctx = leaf::make_shared_context(error_handlers); return leaf::capture(ctx, &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: [source,c++] ---- //std::future> fut; fut.wait(); return leaf::try_handle_some( [&]() -> leaf::result { BOOST_LEAF_AUTO(r, fut.get()); //Success! 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 .... return { }; }, [](E3 e3) { //Deal with E3 .... return { }; } ); ---- Launching the task looks the same as before, except that we don't use `result`: [source,c++] ---- 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); } ); } ---- [.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: [source,c++] ---- //std::future fut; fut.wait(); return leaf::try_catch( [&] { task_result r = fut.get(); // Throws on error //Success! }, error_handlers ); ---- [.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]. ''' [[tutorial-classification]] === Classification of Failures It is common for an interface to define an `enum` that lists all possible error codes that the API reports. The benefit of this approach is that the list is complete and usually well documented: [source,c++] ---- enum error_code { .... read_error, size_error, eof_error, .... }; ---- The disadvantage of such flat enums is that they do not support handling of a whole class of failures. Consider the following LEAF error handler: [source,c++] ---- .... [](leaf::match, leaf::e_file_name const & fn) { std::cerr << "Failed to access " << fn.value << std::endl; }, .... ---- [.text-right] <> | <> It will get called if the value of the `error_code` enum communicated with the failure is one of `size_error`, `read_error` or `eof_error`. In short, the idea is to handle any input error. 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: [source,c++] ---- struct input_error: std::exception { }; struct read_error: input_error { }; struct size_error: input_error { }; struct eof_error: input_error { }; ---- In terms of LEAF, our input error exception handler now looks like this: [source,c++] ---- [](input_error &, leaf::e_file_name const & fn) { std::cerr << "Failed to access " << fn.value << std::endl; }, ---- This is future-proof, but still not ideal, because it is not possible to refine the classification of the failure after the exception object has been thrown. LEAF supports a novel style of error handling where the classification of failures does not use error code values or exception type hierarchies. Instead of our `error_code` enum, we could define: [source,c++] ---- .... struct input_error { }; struct read_error { }; struct size_error { }; struct eof_error { }; .... ---- With this in place, we could define a function `file_read`: [source,c++] ---- leaf::result file_read( FILE & f, void * buf, int size ) { int n = fread(buf, 1, size, &f); if( ferror(&f) ) return leaf::new_error(input_error{}, read_error{}, leaf::e_errno{errno}); <1> if( n!=size ) return leaf::new_error(input_error{}, eof_error{}); <2> return { }; } ---- [.text-right] <> | <> | <> <1> This error is classified as `input_error` and `read_error`. <2> This error is classified as `input_error` and `eof_error`. Or, even better: [source,c++] ---- leaf::result file_read( FILE & f, void * buf, int size ) { auto load = leaf::on_error(input_error{}); <1> int n = fread(buf, 1, size, &f); if( ferror(&f) ) return leaf::new_error(read_error{}, leaf::e_errno{errno}); <2> if( n!=size ) return leaf::new_error(eof_error{}); <3> return { }; } ---- [.text-right] <> | <> | <> | <> <1> Any error escaping this scope will be classified as `input_error` <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::throw_exception` instead of `leaf::new_error`: [source,c++] ---- void file_read( FILE & f, void * buf, int size ) { auto load = leaf::on_error(input_error{}); int n = fread(buf, 1, size, &f); if( ferror(&f) ) leaf::throw_exception(read_error{}, leaf::e_errno{errno}); if( n!=size ) leaf::throw_exception(eof_error{}); } ---- [.text-right] <> | <> | <> 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 returns 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`: [source,c++] ---- .... [](input_error, leaf::e_file_name const & fn) { std::cerr << "Failed to access " << fn.value << std::endl; }, .... ---- Remarkably, because the classification of the failure does not depend on error codes or on exception types, this error handler can be used with `try_catch` if we use exception handling, or with `try_handle_some`/`try_handle_all` if we do not. ''' [[tutorial-exception_to_result]] === Converting Exceptions to `result` It is sometimes necessary to catch exceptions thrown by a lower-level library function, and report the error through different means, to a higher-level library which may not use exception handling. TIP: Error handlers that take arguments of types that derive from `std::exception` work correctly -- regardless of whether the error object itself is thrown as an exception, or <> into a <>. The technique described here is only needed when the exception must be communicated through functions which are not exception-safe, or are compiled with exception handling disabled. Suppose we have an exception type hierarchy and a function `compute_answer_throws`: [source,c++] ---- class error_base: public std::exception { }; class error_a: public error_base { }; class error_b: public error_base { }; class error_c: public error_base { }; int compute_answer_throws() { switch( rand()%4 ) { default: return 42; case 1: throw error_a(); case 2: throw error_b(); case 3: throw error_c(); } } ---- We can write a simple wrapper using `exception_to_result`, which calls `compute_answer_throws` and switches to `result` for error handling: [source,c++] ---- leaf::result compute_answer() noexcept { return leaf::exception_to_result( [] { return compute_answer_throws(); } ); } ---- [.text-right] <> | <> The `exception_to_result` template takes any number of exception types. All exception types thrown by the passed function are caught, and an attempt is made to convert the exception object to each of the specified types. Each successfully-converted slice of the caught exception object, as well as the return value of `std::current_exception`, are copied and <>, and in the end the exception is converted to a `<>` object. (In our example, `error_a` and `error_b` slices as communicated as error objects, but `error_c` exceptions will still be captured by `std::exception_ptr`). Here is a simple function which prints successfully computed answers, forwarding any error (originally reported by throwing an exception) to its caller: [source,c++] ---- leaf::result print_answer() noexcept { BOOST_LEAF_AUTO(answer, compute_answer()); std::cout << "Answer: " << answer << std::endl; return { }; } ---- [.text-right] <> | <> 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. [source,c++] ---- leaf::try_handle_all( []() -> leaf::result { BOOST_LEAF_CHECK(print_answer()); return { }; }, [](error_a const & e) { std::cerr << "Error A!" << std::endl; }, [](error_b const & e) { std::cerr << "Error B!" << std::endl; }, [] { std::cerr << "Unknown error!" << std::endl; } ); ---- [.text-right] <> | <> | <> NOTE: The complete program illustrating this technique is available https://github.com/boostorg/leaf/blob/master/example/exception_to_result.cpp?ts=4[here]. ''' [[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. LEAF makes this easy. As an example, we'll write a program that uses Lua and reports a failure from a {CPP} function registered as a C callback, called from a Lua program. The failure will be propagated from {CPP}, through the Lua interpreter (written in C), back to the {CPP} function which called it. C/{CPP} functions designed to be invoked from a Lua program must use the following signature: [source,c] ---- int do_work( lua_State * L ) ; ---- Arguments are passed on the Lua stack (which is accessible through `L`). Results too are pushed onto the Lua stack. First, let's initialize the Lua interpreter and register a function, `do_work`, as a C callback available for Lua programs to call: [source,c++] ---- std::shared_ptr init_lua_state() noexcept { std::shared_ptr L(lua_open(), &lua_close); //<1> lua_register(&*L, "do_work", &do_work); //<2> luaL_dostring(&*L, "\ //<3> \n function call_do_work()\ \n return do_work()\ \n end"); return L; } ---- <1> Create a new `lua_State`. We'll use `std::shared_ptr` for automatic cleanup. <2> Register the `do_work` {CPP} function as a C callback, under the global name `do_work`. With this, calls from Lua programs to `do_work` will land in the `do_work` {CPP} function. <3> Pass some Lua code as a `C` string literal to Lua. This creates a global Lua function called `call_do_work`, which we will later ask Lua to execute. Next, let's define our `enum` used to communicate `do_work` failures: [source,c++] ---- enum do_work_error_code { ec1=1, ec2 }; ---- We're now ready to define the `do_work` callback function: [source,c++] ---- int do_work( lua_State * L ) noexcept { bool success = rand() % 2; <1> if( success ) { lua_pushnumber(L, 42); <2> return 1; } else { (void) leaf::new_error(ec1); <3> return luaL_error(L, "do_work_error"); <4> } } ---- [.text-right] <> | <> <1> "Sometimes" `do_work` fails. <2> In case of success, push the result on the Lua stack, return back to Lua. <3> Generate a new `error_id` and associate a `do_work_error_code` with it. Normally, we'd return this in a `leaf::result`, but the `do_work` function signature (required by Lua) does not permit this. <4> Tell the Lua interpreter to abort the Lua program. Now we'll write the function that calls the Lua interpreter to execute the Lua function `call_do_work`, which in turn calls `do_work`. We'll return `<>`, so that our caller can get the answer in case of success, or an error: [source,c++] ---- leaf::result call_lua( lua_State * L ) { lua_getfield(L, LUA_GLOBALSINDEX, "call_do_work"); error_monitor cur_err; if( int err = lua_pcall(L, 0, 1, 0) ) <1> { auto load = leaf::on_error(e_lua_error_message{lua_tostring(L,1)}); <2> lua_pop(L,1); return cur_err.assigned_error_id().load(e_lua_pcall_error{err}); <3> } else { int answer = lua_tonumber(L, -1); <4> lua_pop(L, 1); return answer; } } ---- [.text-right] <> | <> | <> <1> Ask the Lua interpreter to call the global Lua function `call_do_work`. <2> `on_error` works as usual. <3> `load` will use the `error_id` generated in our Lua callback. This is the same `error_id` the `on_error` uses as well. <4> Success! Just return the `int` answer. Finally, here is the `main` function which exercises `call_lua`, each time handling any failure: [source,c++] ---- int main() noexcept { std::shared_ptr L=init_lua_state(); for( int i=0; i!=10; ++i ) { leaf::try_handle_all( [&]() -> leaf::result { BOOST_LEAF_AUTO(answer, call_lua(&*L)); std::cout << "do_work succeeded, answer=" << answer << '\n'; <1> return { }; }, [](do_work_error_code e) <2> { std::cout << "Got do_work_error_code = " << e << "!\n"; }, [](e_lua_pcall_error const & err, e_lua_error_message const & msg) <3> { std::cout << "Got e_lua_pcall_error, Lua error code = " << err.value << ", " << msg.value << "\n"; }, [](leaf::error_info const & unmatched) { std::cerr << "Unknown failure detected" << std::endl << "Cryptic diagnostic information follows" << std::endl << unmatched; } ); } ---- [.text-right] <> | <> | <> | <> <1> If the call to `call_lua` succeeded, just print the answer. <2> Handle `do_work` failures. <3> Handle all other `lua_pcall` failures. NOTE: Follow this link to see the complete program: https://github.com/boostorg/leaf/blob/master/example/lua_callback_result.cpp?ts=4[lua_callback_result.cpp]. TIP: When using Lua with {CPP}, we need to protect the Lua interpreter from exceptions that may be thrown from {CPP} functions installed as `lua_CFunction` callbacks. Here is the program from this section rewritten to use a {CPP} exception to safely communicate errors out of the `do_work` function: https://github.com/boostorg/leaf/blob/master/example/lua_callback_eh.cpp?ts=4[lua_callback_eh.cpp]. '''' [[tutorial-diagnostic_information]] === Diagnostic Information LEAF is able to automatically generate diagnostic messages that include information about all error objects available to error handlers: [source,c++] ---- enum class error_code { read_error, write_error }; .... leaf::try_handle_all( []() -> leaf::result <1> { ... return leaf::new_error( error_code::write_error, leaf::e_file_name{ "file.txt" } ); }, []( leaf::match ) <2> { std::cerr << "Read error!" << std::endl; }, []( leaf::verbose_diagnostic_info const & info ) <3> { std::cerr << "Unrecognized error detected, cryptic diagnostic information follows.\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. 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`: ---- 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 ---- 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.: [source,c++] ---- struct e_errno { int value; friend std::ostream & operator<<( std::ostream & os, e_errno const & e ) { return os << "errno = " << 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`. If handling `verbose_diagnostic_info` is considered too costly, use `diagnostic_info` instead: [source,c++] ---- leaf::try_handle_all( []() -> leaf::result { ... return leaf::new_error( error_code::write_error, leaf::e_file_name{ "file.txt" } ); }, []( leaf::match ) { std::cerr << "Read error!" << std::endl; }, []( leaf::diagnostic_info const & info ) { std::cerr << "Unrecognized error detected, cryptic diagnostic information follows.\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] ---- 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. 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. ''' [[tutorial-std_error_code]] === Working with `std::error_code`, `std::error_condition` ==== 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 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`. Let's say we have this `enum`: [source,c++] ---- enum class libfoo_error { e1 = 1, e2, e3 }; ---- We want to be able to transport `libfoo_error` values in `std::error_code` objects. This erases their static type, which enables them to travel freely across API boundaries. To this end, we must define a `std::error_category` that represents our `libfoo_error` type: [source,c++] ---- std::error_category const & libfoo_error_category() { struct category: std::error_category { char const * name() const noexcept override { return "libfoo"; } std::string message(int code) const override { switch( libfoo_error(code) ) { case libfoo_error::e1: return "e1"; case libfoo_error::e2: return "e2"; case libfoo_error::e3: return "e3"; default: return "error"; } } }; static category c; return c; } ---- We also need to inform the standard library that `libfoo_error` is compatible with `std::error_code`, and provide a factory function which can be used to make `std::error_code` objects out of `libfoo_error` values: [source,c++] ---- namespace std { template <> struct is_error_code_enum: std::true_type { }; } std::error_code make_error_code(libfoo_error e) { return std::error_code(int(e), libfoo_error_category()); } ---- With this in place, if we receive a `std::error_code`, we can easily check if it represents some of the `libfoo_error` values we're interested in: [source,c++] ---- std::error_code f(); .... auto ec = f(); if( ec == libfoo_error::e1 || ec == libfoo_error::e2 ) { // We got either a libfoo_error::e1 or a libfoo_error::e2 } ---- This works because the standard library detects that `std::is_error_code_enum::value` is `true`, and then uses `make_error_code` to create a `std::error_code` object it actually uses to compare to `ec`. So far so good, but remember, the standard library defines another type also, `std::error_condition`. The first confusing thing is that in terms of its physical representation, `std::error_condition` is identical to `std::error_code`; that is, it is also like a pair of `std::error_category` reference and an `int`. Why do we need two different types which use identical physical representation? The key to answering this question is to understand that `std::error_code` objects are designed to be returned from functions to indicate failures. In contrast, `std::error_condition` objects are [underline]#never# supposed to be communicated; their purpose is to interpret the `std::error_code` values being communicated. The idea is that in a given program there may be multiple different "physical" (maybe platform-specific) `std::error_code` values which all indicate the same "logical" `std::error_condition`. This leads us to the second confusing thing about `std::error_condition`: it uses the same `std::error_category` type, but for a completely different purpose: to specify what `std::error_code` values are equivalent to what `std::error_condition` values. Let's say that in addition to `libfoo`, our program uses another library, `libbar`, which communicates failures in terms of `std::error_code` with a different error category. Perhaps `libbar_error` looks like this: [source,c++] ---- enum class libbar_error { e1 = 1, e2, e3, e4 }; // Boilerplate omitted: // - libbar_error_category() // - specialization of std::is_error_code_enum // - make_error_code factory function for libbar_error. ---- We can now use `std::error_condition` to define the _logical_ error conditions represented by the `std::error_code` values communicated by `libfoo` and `libbar`: [source,c++] ---- enum class my_error_condition <1> { c1 = 1, c2 }; std::error_category const & libfoo_error_category() <2> { struct category: std::error_category { char const * name() const noexcept override { return "my_error_condition"; } std::string message(int cond) const override { switch( my_error_condition(code) ) { case my_error_condition::c1: return "c1"; case my_error_condition::c2: return "c2"; default: return "error"; } } bool equivalent(std::error_code const & code, int cond) const noexcept { switch( my_error_condition(cond) ) { case my_error_condition::c1: <3> return code == libfoo_error::e1 || code == libbar_error::e3 || code == libbar_error::e4; case my_error_condition::c2: <4> return code == libfoo_error::e2 || code == libbar_error::e1 || code == libbar_error::e2; default: return false; } } }; static category c; return c; } namespace std { template <> <5> class is_error_condition_enum: std::true_type { }; } std::error_condition make_error_condition(my_error_condition e) <6> { return std::error_condition(int(e), my_error_condition_error_category()); } ---- <1> Enumeration of the two logical error conditions, `c1` and `c2`. <2> Define the `std::error_category` for `std::error_condition` objects that represent a `my_error_condition`. <3> Here we specify that any of `libfoo:error::e1`, `libbar_error::e3` and `libbar_error::e4` are logically equivalent to `my_error_condition::c1`, and that... <4> ...any of `libfoo:error::e2`, `libbar_error::e1` and `libbar_error::e2` are logically equivalent to `my_error_condition::c2`. <5> This specialization tells the standard library that the `my_error_condition` enum is designed to be used with `std::error_condition`. <6> The factory function to make `std::error_condition` objects out of `my_error_condition` values. Phew! Now, if we have a `std::error_code` object `ec`, we can easily check if it is equivalent to `my_error_condition::c1` like so: [source,c++] ---- if( ec == my_error_condition::c1 ) { // We have a c1 in our hands } ---- Again, remember that beyond defining the `std::error_category` for `std::error_condition` objects initialized with a `my_error_condition` value, we don't need to interact with the actual `std::error_condition` instances: they're created when needed to compare to a `std::error_code`, and that's pretty much all they're good for. ==== Support in LEAF The `match` predicate can be used as an argument to a LEAF error handler to match a `std::error_code` with a given error condition. For example, to handle `my_error_condition::c1` (see above), we could use: [source,c++] ---- leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( leaf::match m ) { assert(m.matched == my_error_condition::c1); .... } ); ---- See <> for more examples. ''' [[tutorial-boost_exception_integration]] === Boost Exception Integration Instead of the https://www.boost.org/doc/libs/release/libs/exception/doc/get_error_info.html[`boost::get_error_info`] API defined by Boost Exception, it is possible to use LEAF error handlers directly. Consider the following use of `boost::get_error_info`: [source,c++] ---- typedef boost::error_info my_info; void f(); // Throws using boost::throw_exception void g() { try { f(); }, catch( boost::exception & e ) { if( int const * x = boost::get_error_info(e) ) std::cerr << "Got my_info with value = " << *x; } ); } ---- We can rewrite `g` to access `my_info` using LEAF: [source,c++] ---- #include void g() { leaf::try_catch( [] { f(); }, []( my_info x ) { std::cerr << "Got my_info with value = " << x.value(); } ); } ---- [.text-right] <> Taking `my_info` means that the handler will only be selected if the caught exception object carries `my_info` (which LEAF accesses via `boost::get_error_info`). The use of <> is also supported: [source,c++] ---- void g() { leaf::try_catch( [] { f(); }, []( leaf::match_value ) { std::cerr << "Got my_info with value = 42"; } ); } ---- Above, the handler will be selected if the caught exception object carries `my_info` with `.value()` equal to 42. [[example]] == Examples See https://github.com/boostorg/leaf/tree/master/example[github]. [[synopsis]] == Synopsis This section lists each public header file in LEAF, documenting the definitions it provides. LEAF headers are designed to minimize coupling: * Headers needed to report or forward but not handle errors are lighter than headers providing error handling functionality. * Headers that provide exception handling or throwing functionality are separate from headers that provide error handling or reporting but do not use exceptions. A standalone single-header option is available; please see <>. ''' [[synopsis-reporting]] === Error Reporting [[error.hpp]] ==== `error.hpp` ==== .#include [source,c++] ---- namespace boost { namespace leaf { class error_id { public: error_id() noexcept; template error_id( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; error_id( std::error_code const & ec ) noexcept; int value() const noexcept; explicit operator bool() const noexcept; std::error_code to_error_code() const noexept; friend bool operator==( error_id a, error_id b ) noexcept; friend bool operator!=( error_id a, error_id b ) noexcept; friend bool operator<( error_id a, error_id b ) noexcept; template error_id load( Item && ... item ) const noexcept; friend std::ostream & operator<<( std::ostream & os, error_id x ); }; bool is_error_id( std::error_code const & ec ) noexcept; template error_id new_error( Item && ... item ) noexcept; 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 { context_activator( context_activator const & ) = delete; context_activator & operator=( context_activator const & ) = delete; public: explicit context_activator( Ctx & ctx ) noexcept; context_activator( context_activator && ) noexcept; ~context_activator() noexcept; }; template context_activator activate_context( Ctx & ctx ) noexcept; template struct is_result_type: std::false_type { }; template struct is_result_type: is_result_type { }; } } #define BOOST_LEAF_ASSIGN(v, r)\ auto && <> = r;\ if( !<> )\ return <>.error();\ v = std::forward>)>(<>).value() #define BOOST_LEAF_AUTO(v, r)\ BOOST_LEAF_ASSIGN(auto v, r) #define BOOST_LEAF_CHECK(r)\ auto && <> = r;\ if( <> )\ ;\ else\ return <>.error() #define BOOST_LEAF_NEW_ERROR <> ---- [.text-right] Reference: <> | <> | <> | <> | <> | <> | <> | <> | <> | <> | <> | <> ==== [[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); friend std::ostream & operator<<(std::ostream &, e_errno const &); }; namespace windows { struct e_LastError { unsigned value; explicit e_LastError(unsigned value); #if BOOST_LEAF_CFG_WIN32 e_LastError(); friend std::ostream & operator<<(std::ostream &, e_LastError const &); #endif }; } } } ---- [.text-right] Reference: <> | <> | <> | <> | <> | <> | <> ==== [[result.hpp]] ==== `result.hpp` ==== .#include [source,c++] ---- namespace boost { namespace leaf { template class result { public: result() noexcept; result( T && v ) noexcept; result( T const & v ); template result( U && u, <> ); result( error_id err ) noexcept; result( std::shared_ptr && ctx ) noexcept; template result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; result( std::error_code const & ec ) noexcept; result( result && r ) noexcept; template result( result && r ) noexcept; 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; T const & value() const; T & value(); 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; }; template <> class result { public: 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; result( std::error_code const & ec ) noexcept; result( result && r ) noexcept; template result( result && r ) noexcept; result & operator=( result && r ) noexcept; template result & operator=( result && r ) noexcept; explicit operator bool() const noexcept; void value() const; <> error() noexcept; template error_id load( Item && ... item ) noexcept; }; struct bad_result: std::exception { }; template struct is_result_type>: std::true_type { }; } } ---- [.text-right] 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> [[noreturn]] void throw_exception( Ex &&, E && ... ); template <2> [[noreturn]] void throw_exception( E1 &&, E && ... ); [[noreturn]] void throw_exception(); template <1> [[noreturn]] void throw_exception( error_id id, Ex &&, E && ... ); template <2> [[noreturn]] void throw_exception( error_id id, E1 &&, E && ... ); [[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. ==== ==== `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]] === Error Handling [[context.hpp]] ==== `context.hpp` ==== .#include [source,c++] ---- namespace boost { namespace leaf { template class context { context( context const & ) = delete; context & operator=( context const & ) = delete; public: context() noexcept; context( context && x ) noexcept; ~context() noexcept; void activate() noexcept; void deactivate() noexcept; bool is_active() const noexcept; void propagate( error_id ) noexcept; void print( std::ostream & os ) const; template R handle_error( R &, H && ... ) const; }; ////////////////////////////////////////// template using context_type_from_handlers = typename <>::type; template BOOST_LEAF_CONSTEXPR context_type_from_handlers make_context() noexcept; 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: <> | <> | <> | <> ==== [[handle_errors.hpp]] ==== `handle_errors.hpp` ==== .#include [source,c++] ---- namespace boost { namespace leaf { template typename std::decay()().value())>::type try_handle_all( TryBlock && try_block, H && ... h ); template typename std::decay()())>::type try_handle_some( TryBlock && try_block, H && ... h ); template typename std::decay()())>::type try_catch( TryBlock && try_block, H && ... h ); ////////////////////////////////////////// class error_info { //No public constructors public: error_id error() const noexcept; 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 ); }; } } ---- [.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: <> ==== [[pred.hpp]] ==== `pred.hpp` ==== .#include [source,c++] ---- namespace boost { namespace leaf { template struct is_predicate: std::false_type { }; template struct match { E matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; template struct match_value { E matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; template struct match_member; template struct member { E matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; template struct catch_ { std::exception const & matched; // Other members not specified }; template struct catch_ { Ex const & matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; template struct if_not { E matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; template bool category( std::error_code const & ec ) noexcept; template struct condition; } } ---- [.text-right] Reference: <> | <> | <> | <> | <> | <> | <> ==== [[functions]] == Reference: Functions TIP: The contents of each Reference section are organized alphabetically. ''' [[activate_context]] === `activate_context` .#include [source,c++] ---- namespace boost { namespace leaf { template context_activator activate_context( Ctx & ctx ) noexcept { return context_activator(ctx); } } } ---- [.text-right] <> .Example: [source,c++] ---- leaf::context ctx; { auto active_context = activate_context(ctx); <1> } <2> ---- <1> Activate `ctx`. <2> Automatically deactivate `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` .#include [source,c++] ---- namespace boost { namespace leaf { template using context_type_from_handlers = typename <>::type; } } ---- .Example: [source,c++] ---- auto error_handlers = std::make_tuple( [](e_this const & a, e_that const & b) { .... }, [](leaf::diagnostic_info const & info) { .... }, .... ); leaf::context_type_from_handlers ctx; <1> ---- <1> `ctx` will be of type `context`, deduced automatically from the specified error handlers. TIP: Alternatively, a suitable context may be created by calling <>, or allocated dynamically by calling <>. ''' [[current_error]] === `current_error` .#include [source,c++] ---- namespace boost { namespace leaf { error_id current_error() noexcept; } } ---- Returns: :: The `error_id` value returned the last time <> was invoked from the calling thread. TIP: See also <>. ''' [[exception_to_result]] === `exception_to_result` [source,c++] .#include ---- namespace boost { namespace leaf { template <-deduced>> exception_to_result( F && f ) noexcept; } } ---- 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`. Effects: :: . Catches all exceptions, then captures `std::current_exception` in a `std::exception_ptr` object, which is <> with the returned `result`. . Attempts to convert the caught exception, using `dynamic_cast`, to each type `Ex~i~` in `Ex...`. If the cast to `Ex~i~` succeeds, the `Ex~i~` slice of the caught exception is loaded with the returned `result`. TIP: An error handler that takes an argument of an exception type (that is, of a type that derives from `std::exception`) will work correctly whether the object is thrown as an exception or communicated via <> (or converted using `exception_to_result`). .Example: [source,c++] ---- int compute_answer_throws(); //Call compute_answer, convert exceptions to result leaf::result compute_answer() { return leaf::exception_to_result(compute_answer_throws()); } ---- At a later time we can invoke <> / <> as usual, passing handlers that take `ex_type1` or `ex_type2`, for example by reference: [source,c++] ---- return leaf::try_handle_some( [] -> leaf::result { BOOST_LEAF_AUTO(answer, compute_answer()); //Use answer .... return { }; }, [](ex_type1 & ex1) { //Handle ex_type1 .... return { }; }, [](ex_type2 & ex2) { //Handle ex_type2 .... return { }; }, [](std::exception_ptr const & p) { //Handle any other exception from compute_answer. .... return { }; } ); ---- [.text-right] <> | <> | <> WARNING: When a handler takes an argument of an exception type (that is, a type that derives from `std::exception`), if the object is thrown, the argument will be matched dynamically (using `dynamic_cast`); otherwise (e.g. after being converted by `exception_to_result`) it will be matched based on its static type only (which is the same behavior used for types that do not derive from `std::exception`). TIP: See also <> from the tutorial. ''' [[make_context]] === `make_context` .#include [source,c++] ---- namespace boost { namespace leaf { template context_type_from_handlers make_context() noexcept { return { }; } template context_type_from_handlers make_context( H && ... ) noexcept { return { }; } } } ---- [.text-right] <> .Example: [source,c++] ---- auto ctx = leaf::make_context( <1> []( e_this ) { .... }, []( e_that ) { .... } ); ---- <1> `decltype(ctx)` is `leaf::context`. ''' [[make_shared_context]] === `make_shared_context` .#include [source,c++] ---- namespace boost { namespace leaf { template context_ptr make_shared_context() noexcept { return std::make_shared>>(); } template context_ptr make_shared_context( H && ... ) noexcept { return std::make_shared>>(); } } } ---- [.text-right] <> TIP: See also <> from the tutorial. ''' [[new_error]] === `new_error` .#include [source,c++] ---- namespace boost { namespace leaf { template error_id new_error(Item && ... item) noexcept; } } ---- Requires: :: Each of the `Item...` types must be no-throw movable. Effects: :: As if: + [source,c++] ---- error_id id = <>; return id.load(std::forward(item)...); ---- Returns: :: A new `error_id` value, which is unique across the entire program. Ensures: :: `id.value()!=0`, where `id` is the returned `error_id`. NOTE: `new_error` discards error objects which are not used in any active error handling calling scope. CAUTION: When loaded into a `context`, an error object of a type `E` will overwrite the previously loaded object of type `E`, if any. ''' [[on_error]] === `on_error` .#include [source,c++] ---- namespace boost { namespace leaf { template <> on_error(Item && ... item) noexcept; } } ---- Requires: :: Each of the `Item...` types must be no-throw movable. Effects: :: All `item...` objects are forwarded and stored, together with the value returned from `std::unhandled_exceptions`, into the returned object of unspecified type, which should be captured by `auto` and kept alive in the calling scope. When that object is destroyed, if an error has occurred since `on_error` was invoked, LEAF will process the stored items to obtain error objects to be associated with the failure. + On error, LEAF first needs to deduce an `error_id` value `err` to associate error objects with. This is done using the following logic: + -- * If <> was invoked (by the calling thread) since the object returned by `on_error` was created, `err` is initialized with the value returned by <>; * Otherwise, if `std::unhandled_exceptions` returns a greater value than it returned during initialization, `err` is initialized with the value returned by <>; * Otherwise, the stored `item...` objects are discarded and no further action is taken (no error has occurred). -- + Next, LEAF proceeds similarly to: + [source,c++] ---- err.load(std::forward(item)...); ---- + The difference is that unlike <>, `on_error` will not overwrite any error objects already associated with `err`. 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` .#include [source,c++] ---- namespace boost { namespace leaf { template std::variant< typename std::decay()().value())>::type std::tuple< std::optional...>> to_variant( TryBlock && try_block ); } } ---- 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 `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. .Example: [source,c++] ---- enum class E1 { e11, e12, e13 }; enum class E2 { e21, e22, e23 }; enum class E3 { e31, e32, e33 }; .... auto v = leaf::to_variant( []() -> leaf::result { return leaf::new_error( E1::e12, E3::e33 ); } ); assert(v.index() == 1); <1> auto t = std::get<1>(v); <2> assert(std::get<0>(t).value() == E1::e12); <3> assert(!std::get<1>(t).has_value()); <4> assert(std::get<2>(t).value() == E3::e33); <3> ---- <1> We report a failure, so the variant must contain the error object tuple, rather than an `int`. <2> Grab the error tuple. <3> We communicated an `E1` and an `E3` error object... <4> ...but not an `E2` error object. ''' [[try_catch]] === `try_catch` .#include [source,c++] ---- namespace boost { namespace leaf { template typename std::decay()())>::type try_catch( TryBlock && try_block, H && ... h ); } } ---- The `try_catch` function works similarly to <>, except that it does not use or understand the semantics of `result` types; instead: * It assumes that the `try_block` throws to indicate a failure, in which case `try_catch` will attempt to find a suitable handler among `h...`; * If a suitable handler isn't found, the original exception is re-thrown using `throw;`. TIP: See <>. ''' [[try_handle_all]] === `try_handle_all` .#include [source,c++] ---- namespace boost { namespace leaf { template typename std::decay()().value())>::type try_handle_all( TryBlock && try_block, H && ... h ); } } ---- The `try_handle_all` function works similarly to <>, except: * In addition, it requires that at least one of `h...` can be used to handle any error (this requirement is enforced at compile time); * If the `try_block` returns some `result` type, it must be possible to initialize a value of type `T` with the value returned by each of `h...`, and * Because it is required to handle all errors, `try_handle_all` unwraps the `result` object `r` returned by the `try_block`, returning `r.value()` instead of `r`. TIP: See <>. ''' [[try_handle_some]] === `try_handle_some` .#include [source,c++] ---- namespace boost { namespace leaf { template typename std::decay()())>::type try_handle_some( TryBlock && try_block, H && ... h ); } } ---- 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. * 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 an <> 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. * 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. + ** if `try_handle_some` is unable to find a suitable handler, it returns `r`. NOTE: `try_handle_some` is exception-neutral: it does not throw exceptions, however the `try_block` and any of `h...` are permitted to throw. [[handler_selection_procedure]] Handler Selection Procedure: :: + A handler `h` is suitable to handle the failure reported by `r` iff `try_handle_some` is able to produce values to pass as its arguments, using the error objects currently available in `ctx`, associated with the error ID obtained by calling `r.error()`. As soon as it is determined that an argument value can not be produced, the current handler is dropped and the selection process continues with the next handler, if any. + The return value of `r.error()` must be implicitly convertible to <>. Naturally, the `leaf::result` template satisfies this requirement. If an external `result` type is used instead, usually `r.error()` would return a `std::error_code`, which is able to communicate LEAF error IDs; see <>. + If `err` is the `error_id` obtained from `r.error()`, each argument `a~i~` taken by the handler currently under consideration is produced as follows: + * If `a~i~` is of type `A~i~`, `A~i~ const&` or `A~i~&`: + -- ** If an error object of type `A~i~`, associated with `err`, is currently available in `ctx`, `a~i~` is initialized with a reference to that object; otherwise ** If `A~i~` derives from `std::exception`, and the `try_block` throws an object `ex` of type that derives from `std::exception`, LEAF obtains `A~i~* p = dynamic_cast(&ex)`. The handler is dropped if `p` is null, otherwise `a~i~` is initialized with `*p`. ** Otherwise the handler is dropped. -- + .Example: [source,c++] ---- .... auto r = leaf::try_handle_some( []() -> leaf::result { return f(); }, [](leaf::e_file_name const & fn) <1> { std::cerr << "File Name: \"" << fn.value << '"' << std::endl; <2> return 1; } ); ---- + [.text-right] <> | <> + <1> In case the `try_block` indicates a failure, this handler will be selected if `ctx` stores an `e_file_name` associated with the error. Because this is the only supplied handler, if an `e_file_name` is not available, `try_handle_some` will return the `leaf::result` returned by `f`. <2> Print the file name, handle the error. + * If `a~i~` is of type `A~i~` `const*` or `A~i~*`, `try_handle_some` is always able to produce it: first it attempts to produce it as if it is taken by reference; if that fails, rather than dropping the handler, `a~i~` is initialized with `0`. + .Example: [source,c++] ---- .... try_handle_some( []() -> leaf::result { return f(); }, [](leaf::e_file_name const * fn) <1> { if( fn ) <2> std::cerr << "File Name: \"" << fn->value << '"' << std::endl; return 1; } ); } ---- + [.text-right] <> | <> + <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 `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}`. + NOTE: See also: <>. + * If `a~i~` is of type `error_info const &`, `try_handle_some` is always able to produce it. + .Example: [source,c++] ---- .... try_handle_some( [] { return f(); // returns leaf::result }, [](leaf::error_info const & info) <1> { std::cerr << "leaf::error_info:" << std::endl << info; <2> return info.error(); <3> } ); ---- + [.text-right] <> | <> + <1> This handler matches any error. <2> Print error information. <3> Return the original error, which will be returned out of `try_handle_some`. + * If `a~i~` is of type `diagnostic_info const &`, `try_handle_some` is always able to produce it. + .Example: [source,c++] ---- .... try_handle_some( [] { return f(); // throws }, [](leaf::diagnostic_info const & info) <1> { std::cerr << "leaf::diagnostic_information:" << std::endl << info; <2> return info.error(); <3> } ); ---- + [.text-right] <> | <> + <1> This handler matches any error. <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. + .Example: [source,c++] ---- .... try_handle_some( [] { return f(); // throws }, [](leaf::verbose_diagnostic_info const & info) <1> { std::cerr << "leaf::verbose_diagnostic_information:" << std::endl << 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. <3> Return the original error, which will be returned out of `try_handle_some`. [[types]] == Reference: Types TIP: The contents of each Reference section are organized alphabetically. ''' [[context]] === `context` .#include [source,c++] ---- namespace boost { namespace leaf { template class context { context( context const & ) = delete; context & operator=( context const & ) = delete; public: context() noexcept; context( context && x ) noexcept; ~context() noexcept; void activate() noexcept; void deactivate() noexcept; bool is_active() const noexcept; void propagate( error_id ) noexcept; void print( std::ostream & os ) const; template R handle_error( error_id, H && ... ) const; }; template using context_type_from_handlers = typename <>::type; } } ---- [.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. Independently, users can create `context` objects if they need to capture error objects and then transport them, by moving the `context` object itself. Even in that case it is recommended that users do not instantiate the `context` template by explicitly listing the `E...` types they want it to be able to store. Instead, use <> or call the <> function template, which deduce the correct `E...` types from a captured list of handler function objects. 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 <>. 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`. TIP: `context` objects can be moved, as long as they aren't active. WARNING: Moving an active `context` results in undefined behavior. ''' [[context::context]] ==== Constructors .#include [source,c++] ---- namespace boost { namespace leaf { template context::context() noexcept; template context::context( context && x ) noexcept; } } ---- The default constructor initializes an empty `context` object: it provides storage for, but does not contain any error objects. The move constructor moves the stored error objects from one `context` to the other. WARNING: Moving an active `context` object results in undefined behavior. ''' [[context::activate]] ==== `activate` .#include [source,c++] ---- namespace boost { namespace leaf { template void context::activate() noexcept; } } ---- Requires: :: `!<>()`. Effects: :: Associates `*this` with the calling thread. 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`. When an error object is <>, it is moved in the last activated (in the calling thread) `context` object that provides storage for its type (note that this may or may not be the last activated `context` object). If no such storage is available, the error object is discarded. ''' [[context::deactivate]] ==== `deactivate` .#include [source,c++] ---- namespace boost { namespace leaf { template void context::deactivate() noexcept; } } ---- Requires: :: * `<>()`; * `*this` must be the last activated `context` object in the calling thread. Effects: :: Un-associates `*this` with the calling thread. 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 <>. ''' [[context::handle_error]] ==== `handle_error` [source,c++] .#include ---- namespace boost { namespace leaf { template template R context::handle_error( error_id err, H && ... h ) const; } } ---- This function works similarly to <>, but rather than calling a `try_block` and obtaining the <> from a returned `result` type, it matches error objects (stored in `*this`, associated with `err`) with a suitable error handler from the `h...` pack. NOTE: The caller is required to specify the return type `R`. This is because in general the supplied handlers may return different types (which must all be convertible to `R`). ''' [[context::is_active]] ==== `is_active` [source,c++] .#include ---- namespace boost { namespace leaf { template bool context::is_active() const noexcept; } } ---- Returns: :: `true` if the `*this` is active in any thread, `false` otherwise. ''' [[context::print]] ==== `print` .#include [source,c++] ---- namespace boost { namespace leaf { template void context::print( std::ostream & os ) const; } } ---- Effects: :: Prints all error objects currently stored in `*this`, together with the unique error ID each individual error object is associated with. ''' [[context::propagate]] ==== `propagate` .#include [source,c++] ---- namespace boost { namespace leaf { template void context::propagate( error_id id ) noexcept; } } ---- Requires: :: `!<>()`. Effects: :: Each stored error object of some type `E` is moved into another `context` object active in the call stack that provides storage for objects of type `E`, if any, or discarded. Target objects are not overwritten if they are associated with the specified `id`, except if `id.value() == 0`. ''' [[context_activator]] === `context_activator` .#include [source,c++] ---- namespace boost { namespace leaf { template class context_activator { context_activator( context_activator const & ) = delete; context_activator & operator=( context_activator const & ) = delete; public: explicit context_activator( Ctx & ctx ) noexcept; context_activator( context_activator && ) noexcept; ~context_activator() noexcept; }; } } ---- `context_activator` is a simple class that activates and deactivates a <> using RAII: If `<>`() is `true` at the time the `context_activator` is initialized, the constructor and the destructor have no effects. Otherwise: * The constructor stores a reference to `ctx` in `*this` and calls `<>`(). * The destructor: ** Has no effects if `ctx.is_active()` is `false` (that is, it is valid to call <> manually, before the `context_activator` object expires); ** Otherwise, calls `<>`(). For automatic deduction of `Ctx`, use <>. ''' [[diagnostic_info]] === `diagnostic_info` .#include [source,c++] ---- namespace boost { namespace leaf { class diagnostic_info: public error_info { //Constructors unspecified friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x ); }; } } ---- Handlers passed to <>, <> or <> may take an argument of type `diagnostic_info const &` if they need to print diagnostic information about the error. The message printed by `operator<<` includes the message printed by `error_info`, followed by basic information about error objects that were communicated to LEAF (to be associated with the error) for which there was no storage available in any active <> (these error objects were discarded by LEAF, because no handler needed them). The additional information is limited to the type name of the first such error object, as well as their total count. [NOTE] -- The behavior of `diagnostic_info` (and <>) is affected by the value of the macro `BOOST_LEAF_CFG_DIAGNOSTICS`: * If it is 1 (the default), LEAF produces `diagnostic_info` but only if an active error handling context on the call stack takes an argument of type `diagnostic_info`; * If it is 0, the `diagnostic_info` functionality is stubbed out even for error handling contexts that take an argument of type `diagnostic_info`. This could shave a few cycles off the error path in some programs (but it is probably not worth it). -- ''' [[error_id]] === `error_id` .#include [source,c++] ---- namespace boost { namespace leaf { class error_id { public: error_id() noexcept; template result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; error_id( std::error_code const & ec ) noexcept; int value() const noexcept; explicit operator bool() const noexcept; std::error_code to_error_code() const noexcept; friend bool operator==( error_id a, error_id b ) noexcept; friend bool operator!=( error_id a, error_id b ) noexcept; friend bool operator<( error_id a, error_id b ) noexcept; template error_id load( Item && ... item ) const noexcept; friend std::ostream & operator<<( std::ostream & os, error_id x ); }; bool is_error_id( std::error_code const & ec ) noexcept; template error_id new_error( E && ... e ) noexcept; error_id current_error() noexcept; } } ---- [.text-right] <> | <> | <> | <> | <> | <> | <> | <> | <> Values of type `error_id` identify a specific occurrence of a failure across the entire program. They can be copied, moved, assigned to, and compared to other `error_id` objects. They're as efficient as an `int`. ''' [[error_id::error_id]] ==== Constructors .#include [source,c++] ---- namespace boost { namespace leaf { error_id::error_id() noexcept = default; template error_id::error_id( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; error_id::error_id( std::error_code const & ec ) noexcept; } } ---- A default-initialized `error_id` object does not represent a specific failure. It compares equal to any other default-initialized `error_id` object. All other `error_id` objects identify a specific occurrence of a failure. CAUTION: When using an object of type `error_id` to initialize a `result` object, it will be initialized in error state, even when passing a default-initialized `error_id` value. Converting an `error_id` object to `std::error_code` uses an unspecified `std::error_category` which LEAF recognizes. This allows an `error_id` to be transported through interfaces that work with `std::error_code`. The `std::error_code` constructor allows the original `error_id` to be restored. TIP: To check if a given `std::error_code` is actually carrying an `error_id`, use <>. 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, `*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`. ''' [[is_error_id]] ==== `is_error_id` .#include [source,c++] ---- namespace boost { namespace leaf { bool is_error_id( std::error_code const & ec ) noexcept; } } ---- Returns: :: `true` if `ec` uses the LEAF-specific `std::error_category` that identifies it as carrying an error ID rather than another error code; otherwise returns `false`. ''' [[error_id::load]] ==== `load` .#include [source,c++] ---- namespace boost { namespace leaf { template error_id error_id::load( Item && ... item ) const noexcept; } } ---- 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. * 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`. ** Otherwise, the `item` itself is assumed to be an error object, which is associated with `*this`. Returns: :: `*this`. NOTE: `load` discards error objects which are not used in any active error handling calling scope. CAUTION: When loaded into a `context`, an error object of a type `E` will overwrite the previously loaded object of type `E`, if any. See also: :: <>. ''' [[error_id::comparison_operators]] ==== `operator==`, `!=`, `<` .#include [source,c++] ---- namespace boost { namespace leaf { friend bool operator==( error_id a, error_id b ) noexcept; friend bool operator!=( error_id a, error_id b ) noexcept; friend bool operator<( error_id a, error_id b ) noexcept; } } ---- These functions have the usual semantics, comparing `a.value()` and `b.value()`. NOTE: The exact strict weak ordering implemented by `operator<` is not specified. In particular, if for two `error_id` objects `a` and `b`, `a < b` is true, it does not follow that the failure identified by `a` ocurred earlier than the one identified by `b`. ''' [[error_id::operator_bool]] ==== `operator bool` .#include [source,c++] ---- namespace boost { namespace leaf { explicit error_id::operator bool() const noexcept; } } ---- Effects: :: As if `return value()!=0`. ''' [[error_id::to_error_code]] ==== `to_error_code` .#include [source,c++] ---- namespace boost { namespace leaf { std::error_code error_id::to_error_code() const noexcept; } } ---- Effects: :: Returns a `std::error_code` with the same `value()` as `*this`, using an unspecified `std::error_category`. NOTE: The returned object can be used to initialize an `error_id`, in which case the original `error_id` value will be restored. TIP: Use <> to check if a given `std::error_code` carries an `error_id`. ''' [[error_id::value]] ==== `value` .#include [source,c++] ---- namespace boost { namespace leaf { int error_id::value() const noexcept; } } ---- Effects: :: * If `*this` was initialized using the default constructor, returns 0. * Otherwise returns an `int` that is guaranteed to not be 0: a program-wide unique identifier of the failure. ''' [[error_monitor]] === `error_monitor` .#include [source,c++] ---- namespace boost { namespace leaf { class error_monitor { public: error_monitor() noexcept; error_id check() const noexcept; error_id assigned_error_id( E && ... e ) const noexcept; }; } } ---- This class helps obtain an <> to associate error objects with, when augmenting failures communicated using LEAF through uncooperative APIs that do not use LEAF to report errors (and therefore do not return an `error_id` on error). The common usage of this class is as follows: [source,c++] ---- error_code compute_value( int * out_value ) noexcept; <1> leaf::error augmenter() noexcept { leaf::error_monitor cur_err; <2> int val; auto ec = compute_value(&val); if( failure(ec) ) return cur_err.assigned_error_id().load(e1, e2, ...); <3> else return val; <4> } ---- <1> Uncooperative third-party API that does not use LEAF, but may result in calling a user callback that does use LEAF. In case our callback reports a failure, we'll augment it with error objects available in the calling scope, even though `compute_value` can not communicate an <>. <2> Initialize an `error_monitor` object. <3> The call to `compute_value` has failed: - If <> was invoked (by the calling thread) after the `augment` object was initialized, `assigned_error_id` returns the last `error_id` returned by `new_error`. This would be the case if the failure originates in our callback (invoked internally by `compute_value`). - Else, `assigned_error_id` invokes `new_error` and returns that `error_id`. <4> The call was successful, return the computed value. The `check` function works similarly, but instead of invoking `new_error` it returns a default-initialized `error_id`. TIP: See <>. ''' [[e_api_function]] === `e_api_function` .#include [source,c++] ---- namespace boost { namespace leaf { struct e_api_function {char const * value;}; } } ---- The `e_api_function` type is designed to capture the name of the API function that failed. For example, if you're reporting an error from `fread`, you could use `leaf::e_api_function {"fread"}`. WARNING: The passed value is stored as a C string (`char const *`), so `value` should only be initialized with a string literal. ''' [[e_at_line]] === `e_at_line` .#include [source,c++] ---- namespace boost { namespace leaf { struct e_at_line { int value; }; } } ---- `e_at_line` can be used to communicate the line number when reporting errors (for example parse errors) about a text file. ''' [[e_errno]] === `e_errno` .#include [source,c++] ---- namespace boost { namespace leaf { struct e_errno { int value; explicit e_errno(int value=errno); friend std::ostream & operator<<( std::ostream & os, e_errno const & err ); }; } } ---- By default, the constructor initializes `value` with `errno`, but the caller can pass a specific error code instead. When printed in automatically-generated diagnostic messages, `e_errno` objects use `strerror` to convert the error code to string. ''' [[e_file_name]] === `e_file_name` .#include [source,c++] ---- namespace boost { namespace leaf { struct e_file_name { std::string value; }; } } ---- When a file operation fails, you could use `e_file_name` to store the name of the file. TIP: It is probably better to define your own file name wrappers to avoid clashes if different modules all use `leaf::e_file_name`. It is best to use a descriptive name that clarifies what kind of file name it is (e.g. `e_source_file_name`, `e_destination_file_name`), or at least define `e_file_name` in a given module's namespace. ''' [[e_LastError]] === `e_LastError` .#include [source,c++] ---- namespace boost { namespace leaf { namespace windows { struct e_LastError { unsigned value; explicit e_LastError(unsigned value); #if BOOST_LEAF_CFG_WIN32 e_LastError(); friend std::ostream & operator<<(std::ostream &, e_LastError const &); #endif }; } } } ---- `e_LastError` is designed to communicate `GetLastError()` values on Windows. The default constructor initializes `value` via `GetLastError()`. See <>. ''' [[e_source_location]] === `e_source_location` .#include [source,c++] ---- namespace boost { namespace leaf { struct e_source_location { char const * file; int line; char const * function; friend std::ostream & operator<<( std::ostream & os, e_source_location const & x ); }; } } ---- The <> and <> macros capture `pass:[__FILE__]`, `pass:[__LINE__]` and `pass:[__FUNCTION__]` into a `e_source_location` object. ''' [[e_type_info_name]] === `e_type_info_name` .#include [source,c++] ---- namespace boost { namespace leaf { struct e_type_info_name { char const * value; }; } } ---- `e_type_info_name` is designed to store the return value of `std::type_info::name`. ''' [[error_info]] === `error_info` .#include [source,c++] ---- namespace boost { namespace leaf { class error_info { //Constructors unspecified public: error_id error() const noexcept; bool exception_caught() const noexcept; std::exception const * exception() const noexcept; friend std::ostream & operator<<( std::ostream & os, error_info const & x ); }; } } ---- Handlers passed to error handling functions such as <>, <> or <> may take an argument of type `error_info const &` to receive generic information about the error being handled. The `error` member function returns the program-wide unique <> of the error. The `exception_caught` member function returns `true` if the handler that received `*this` is being invoked to handle an exception, `false` otherwise. If handling an exception, the `exception` member function returns a pointer to the `std::exception` subobject of the caught exception, or `0` if that exception could not be converted to `std::exception`. WARNING: It is illegal to call the `exception` member function unless `exception_caught()` is `true`. The `operator<<` overload prints diagnostic information about each error object currently stored in the <> local to the <>, <> or <> scope that invoked the handler, but only if it is associated with the <> returned by `error()`. ''' [[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` .#include [source,c++] ---- namespace boost { namespace leaf { template class result { public: result() noexcept; result( T && v ) noexcept; result( T const & v ); template result( U &&, <> ); result( error_id err ) noexcept; result( std::shared_ptr && ctx ) noexcept; template result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; result( std::error_code const & ec ) noexcept; result( result && r ) noexcept; template result( result && r ) noexcept; 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; T const & value() const; T & value(); 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; }; template <> class result { public: 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; result( std::error_code const & ec ) noexcept; result( result && r ) noexcept; template result( result && r ) noexcept; 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; <> error() noexcept; template error_id load( Item && ... item ) noexcept; }; struct bad_result: std::exception { }; } } ---- [.text-right] <> | <> | <> | <> | <> | <> | <> | <> | <> | <> The `result` type can be returned by functions which produce a value of type `T` but may fail doing so. 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. * 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<<>>`. `result` objects are nothrow-moveable but are not copyable. ''' [[result::result]] ==== Constructors -- .#include [source,c++] ---- namespace boost { namespace leaf { template result::result() noexcept; template result::result( T && v ) noexcept; <1> template result::result( T const & v ); <1> template result::result( U && u, <> ); <2> template result::result( leaf::error_id err ) noexcept; template template result::result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; template result::result( std::error_code const & ec ) noexcept; template result::result( std::shared_ptr && ctx ) noexcept; template result::result( result && ) noexcept; template template result::result( result && ) noexcept; } } ---- <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: + -- * To get a `result` in <>, initialize it with an object of type `T` or use the default constructor. * To get a `result` in <>, initialize it with: ** an <> object. + CAUTION: Initializing a `result` with a default-initialized `error_id` object (for which `.value()` returns `0`) will still result in <>! + ** 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. <>). -- + 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`. Throws: :: * Initializing the `result` in Value state may throw, depending on which constructor of `T` is invoked; * Other constructors do not throw. TIP: A `result` that is in value state converts to `true` in boolean contexts. A `result` that is not in value state converts to `false` in boolean contexts. NOTE: `result` objects are nothrow-moveable but are not copyable. ''' [[result::error]] ==== `error` .#include [source,c++] ---- namespace boost { namespace leaf { template <> result::error() noexcept; } } ---- Returns: A proxy object of unspecified type, implicitly convertible to any instance of the `result` class template, as well as to <>. * If the proxy object is converted to some `result`: ** If `*this` is in <>, returns `result(error_id())`. ** Otherwise the state of `*this` is moved into the returned `result`. * If the proxy object is converted to an `error_id`: ** If `*this` is in <>, returns a default-initialized <> object. ** If `*this` is in <>, all captured error objects are <> in the calling thread, and the captured `error_id` value is returned. ** If `*this` is in <>, returns the stored `error_id`. * If the proxy object is not used, the state of `*this` is not modified. WARNING: The returned proxy object refers to `*this`; avoid holding on to it. ''' [[result::load]] ==== `load` .#include [source,c++] ---- namespace boost { namespace leaf { template template error_id result::load( Item && ... item ) noexcept; } } ---- This member function is designed for use in `return` statements in functions that return `result` to forward additional error objects to the caller. Effects: :: As if `error_id(thispass:[->]error()).load(std::forward(item)...)`. Returns: :: `*this`. ''' [[result::operator_eq]] ==== `operator=` .#include [source,c++] ---- namespace boost { namespace leaf { template result & result::operator=( result && ) noexcept; template template result & result::operator=( result && ) noexcept; } } ---- Effects: :: Destroys `*this`, then re-initializes it as if using the appropriate `result` constructor. Basic exception-safety guarantee. ''' [[result::has_value]] ==== `has_value` .#include [source,c++] ---- namespace boost { namespace leaf { template bool result::has_value() const noexcept; } } ---- Returns: :: If `*this` is in <>, returns `true`, otherwise returns `false`. ''' [[result::has_error]] ==== `has_error` .#include [source,c++] ---- namespace boost { namespace leaf { template bool result::has_error() const noexcept; } } ---- Returns: :: If `*this` is in <>, returns `false`, otherwise returns `true`. ''' [[result::operator_bool]] ==== `operator bool` .#include [source,c++] ---- namespace boost { namespace leaf { template result::operator bool() const noexcept; } } ---- Returns: :: If `*this` is in <>, returns `true`, otherwise returns `false`. ''' [[result::value]] ==== `value` .#include [source,c++] ---- namespace boost { namespace leaf { void result::value() const; template T const & result::value() const; template T & result::value(); struct bad_result: std::exception { }; } } ---- [[result::bad_result]] Effects: :: If `*this` is in <>, returns a reference to the stored value, otherwise throws `bad_result`. ''' [[result::operator_ptr]] ==== `operatorpass:[->]` .#include [source,c++] ---- namespace boost { namespace leaf { template T const * result::operator->() const noexcept; template T * result::operator->() noexcept; } } ---- Returns :: If `*this` is in <>, returns a pointer to the stored value; otherwise returns 0. ''' [[result::operator_deref]] ==== `operator*` .#include [source,c++] ---- namespace boost { namespace leaf { template T const & result::operator*() const noexcept; template T & result::operator*() noexcept; } } ---- Requires: :: `*this` must be in <>. Returns :: a reference to the stored value. ''' [[verbose_diagnostic_info]] === `verbose_diagnostic_info` .#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 ); }; } } ---- 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). The additional information includes the types and the values of all such error objects. [NOTE] -- The behavior of `verbose_diagnostic_info` (and <>) is affected by the value of the macro `BOOST_LEAF_CFG_DIAGNOSTICS`: * 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). -- 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 TIP: The contents of each Reference section are organized alphabetically. A predicate is a special type of error handler argument which enables the <> to consider the _value_ of available error objects, not only their type; see <>. 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: * `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 &`; * A `Pred` instance can be initialized with an object of type `error_type`. When an error handler takes an argument of a predicate type `Pred`, the <> drops the handler if an error object `e` of type `Pred::error_type` is not available. Otherwise, the handler is dropped if `Pred::evaluate(e)` returns `false`. If the handler is invoked, the `Pred` argument is initialized with `Pred{e}`. NOTE: Predicates are evaluated before the error handler is invoked, and so they may not access dynamic state (of course the error handler itself can access dynamic state, e.g. by means of lambda expression captures). .Example 1: [source,c++] ---- enum class my_error { e1 = 1, e2, e3 }; struct my_pred { using error_type = my_error; <1> static bool evaluate(my_error) noexcept; <2> my_error matched; <3> } namespace boost { namespace leaf { template <> struct is_predicate: std::true_type { }; } } ---- <1> This predicate requires an error object of type `my_error`. <2> The handler selection procedure will call this function with an object `e` of type `my_error` to evaluate the predicate... <3> ...and if successful, initialize the `my_pred` error handler argument with `my_pred{e}`. .Example 2: [source,c++] ---- struct my_pred { using error_type = leaf::e_errno; <1> static bool evaluate(leaf::e_errno const &) noexcept; <2> leaf::e_errno const & matched; <3> } namespace boost { namespace leaf { template <> struct is_predicate: std::true_type { }; } } ---- <1> This predicate requires an error object of type <>. <2> The handler selection procedure will call this function with an object `e` of type `e_errno` to evaluate the predicate... <3> ...and if successful, initialize the `my_pred` error handler argument with `my_pred{e}`. ''' [[catch_]] === `catch_` .#include [source,c++] ---- namespace boost { namespace leaf { template struct catch_ { std::exception const & matched; // Other members not specified }; template struct catch_ { Ex const & matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; } } ---- [.text-right] <> When an error handler takes an argument of type that is an instance of the `catch_` template, the <> first checks if a `std::exception` was caught. If not, the handler is dropped. Otherwise, the handler is dropped if the caught `std::exception` can not be `dynamic_cast` to any of the specified types `Ex...`. If the error handler is invoked, the `matched` member can be used to access the exception object. NOTE: See also: <>. TIP: While `catch_` requires that the caught exception object is of type that derives from `std::exception`, it is not required that the `Ex...` types derive from `std::exception`. .Example 1: [source,c++] ---- struct ex1: std::exception { }; struct ex2: std::exception { }; leaf::try_catch( [] { return f(); // throws }, [](leaf::catch_ c) { <1> assert(dynamic_cast(&c.matched) || dynamic_cast(&c.matched)); .... } ); ---- <1> The handler is selected if `f` throws an exception of type `ex1` or `ex2`. .Example 2: [source,c++] ---- struct ex1: std::exception { }; leaf::try_handle_some( [] { return f(); // returns leaf::result }, [](ex1 & e) { <1> .... } ); ---- <1> The handler is selected if `f` throws an exception of type `ex1`. Notice that if we're interested in only one exception type, as long as that type derives from `std::exception`, the use of `catch_` is not required. ''' [[if_not]] === `if_not` .#include [source,c++] ---- namespace boost { namespace leaf { template struct if_not { <> matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; } } ---- [.text-right] <> When an error handler takes an argument of type `if_not

`, where `P` is another predicate type, the <> first checks if an error object of the type `E` required by `P` is available. If not, the handler is dropped. Otherwise, the handler is dropped if `P` evaluates to `true`. If the error handler is invoked, `matched` can be used to access the matched object `E`. NOTE: See also <>. .Example: [source,c++] ---- enum class my_enum { e1, e2, e3 }; leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( leaf::if_not> ) { <1> .... } ); ---- [.text-right] <> | <> <1> The handler is selected if an object of type `my_enum`, which [.underline]#*does not*# compare equal to `e1` or to `e2`, [.underline]#*is*# associated with the detected error. ''' [[match]] === `match` .#include [source,c++] ---- namespace boost { namespace leaf { template class match { <> matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; } } ---- [.text-right] <> When an error handler takes an argument of type `match`, the <> first checks if an error object `e` of type `E` is available. If it is not available, the handler is dropped. Otherwise, the handler is dropped if the following condition is not met: [.text-center] `p~1~ || p~2~ || ... p~n~`. Where `p~i~` is equivalent to `e == V~i~`, except if `V~i~` is pointer to a function [.text-center] `bool (*V~i~)(T x)`. In this case it is required that `V~i~ != 0` and that `x` can be initialized with `E const &`, and then `p~i~` is equivalent to: [.text-center] `V~i~(e)`. [[category]] In particular, it is valid to pass pointer to the function `leaf::category` for any `V~i~`, where: [.text-center] `std::is_error_code_enum::value || std::is_error_condition_enum::value`. In this case, `p~i~` is equivalent to: [.text-center] `&e.category() == &std::error_code(Enum{}).category()`. If the error handler is invoked, `matched` can be used to access `e`. NOTE: See also <>. .Example 1: Handling of a subset of enum values. [source,c++] ---- enum class my_enum { e1, e2, e3 }; leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( leaf::match m ) { <1> static_assert(std::is_same::value); assert(m.matched == my_enum::e1 || m.matched == my_enum::e2); .... } ); ---- <1> The handler is selected if an object of type `my_enum`, which compares equal to `e1` or to `e2`, is associated with the detected error. .Example 2: Handling of a subset of std::error_code enum values (requires at least {CPP}17, see Example 4 for a {CPP}11-compatible workaround). [source,c++] ---- enum class my_enum { e1=1, e2, e3 }; namespace std { template <> struct is_error_code_enum: std::true_type { }; } leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( leaf::match m ) { <1> static_assert(std::is_same::value); assert(m.matched == my_enum::e1 || m.matched == my_enum::e2); .... } ); ---- <1> The handler is selected if an object of type `std::error_code`, which compares equal to `e1` or to `e2`, is associated with the detected error. .Example 3: Handling of a specific std::error_code::category (requires at least {CPP}17). [source,c++] ---- enum class enum_a { a1=1, a2, a3 }; enum class enum_b { b1=1, b2, b3 }; namespace std { template <> struct is_error_code_enum: std::true_type { }; template <> struct is_error_code_enum: std::true_type { }; } leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( leaf::match, enum_b::b2> m ) { <1> static_assert(std::is_same::value); assert(&m.matched.category() == &std::error_code(enum_{}).category() || m.matched == enum_b::b2); .... } ); ---- <1> The handler is selected if an object of type `std::error_code`, which either has the same `std::error_category` as that of `enum_a` or compares equal to `enum_b::b2`, is associated with the detected error. [[condition]] The use of the `leaf::category` template requires automatic deduction of the type of each `V~i~`, which in turn requires {CPP}17 or newer. The same applies to the use of `std::error_code` as `E`, but LEAF provides a compatible {CPP}11 workaround for this case, using the template `condition`. The following is equivalent to Example 2: .Example 4: Handling of a subset of std::error_code enum values using the {CPP}11-compatible API. [source,c++] ---- enum class my_enum { e1=1, e2, e3 }; namespace std { template <> struct is_error_code_enum: std::true_type { }; } leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( leaf::match, my_enum::e1, my_enum::e2> m ) { static_assert(std::is_same::value); assert(m.matched == my_enum::e1 || m.matched == my_enum::e2); .... } ); ---- Instead of a set of values, the `match` template can be given pointers to functions that implement a custom comparison. In the following example, we define a handler which will be selected to handle any error that communicates an object of the user-defined type `severity` with value greater than 4: .Example 5: Handling of failures with severity::value greater than a specified threshold (requires at least {CPP}17). [source,c++] ---- struct severity { int value; } template constexpr bool severity_greater_than( severity const & e ) noexcept { return e.value > S; } leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( leaf::match> m ) { static_assert(std::is_same::value); assert(m.matched.value > 4); .... } ); ---- ''' [[match_member]] === `match_member` .#include [source,c++] ---- namespace boost { namespace leaf { template struct match_member; template struct match_member { E const & matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; } } ---- [.text-right] <> This predicate is similar to <>, but able to bind any accessible data member of `E`; e.g. `match_member<&E::value, V...>` is equivalent to `match_value`. NOTE: See also <>. WARNING: `match_member` requires at least {CPP}17, whereas `match_value` does not. ''' [[match_value]] === `match_value` .#include [source,c++] ---- namespace boost { namespace leaf { template struct match_value { E const & matched; // Other members not specified }; template struct is_predicate>: std::true_type { }; } } ---- [.text-right] <> This predicate is similar to <>, but where `match` compares the available error object `e` of type `E` to the specified values `V...`, `match_value` works with `e.value`. NOTE: See also <>. .Example: [source,c++] ---- struct e_errno { int value; } leaf::try_handle_some( [] { return f(); // returns leaf::result }, []( leaf::match_value m ) { <1> static_assert(std::is_same::value); assert(m.matched.value == ENOENT); .... } ); ---- <1> The handler is selected if an object of type <>, with `.value` equal to `ENOENT`, is associated with the detected error. [[traits]] == Reference: Traits TIP: The contents of each Reference section are organized alphabetically. [[is_predicate]] === `is_predicate` [source,c++] .#include > ---- namespace boost { namespace leaf { template struct is_predicate: std::false_type { }; } } ---- The `is_predicate` template is used by the <> to detect predicate types. See <>. ''' [[is_result_type]] === `is_result_type` [source,c++] .#include > ---- namespace boost { namespace leaf { template struct is_result_type: std::false_type { }; } } ---- The error handling functionality provided by <> and <> -- including the ability to <> error objects of arbitrary types -- is compatible with any external `result` type R, as long as for a given object `r` of type `R`: * If `bool(r)` is `true`, `r` indicates success, in which case it is valid to call `r.value()` to recover the `T` value. * Otherwise `r` indicates a failure, in which case it is valid to call `r.error()`. The returned value is used to initialize an `error_id` (note: `error_id` can be initialized by `std::error_code`). To use an external `result` 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<<>>`. [[macros]] == Reference: Macros TIP: The contents of each Reference section are organized alphabetically. ''' [[BOOST_LEAF_ASSIGN]] === `BOOST_LEAF_ASSIGN` .#include [source,c++] ---- #define BOOST_LEAF_ASSIGN(v, r)\ auto && <> = r;\ if( !<> )\ return <>.error();\ v = std::forward>)>(<>).value() ---- `BOOST_LEAF_ASSIGN` is useful when calling a function that returns `result` (other than `result`), if the desired behavior is to forward any errors to the caller verbatim. In case of success, the result `value()` of type `T` is assigned to the specified variable `v`, which must have been declared prior to invoking `BOOST_LEAF_ASSIGN`. However, it is possible to use `BOOST_LEAF_ASSIGN` to declare a new variable, by passing in `v` its type together with its name, e.g. `BOOST_LEAF_ASSIGN(auto && x, f())` calls `f`, forwards errors to the caller, while capturing successful values in `x`. NOTE: See also <>. ''' [[BOOST_LEAF_AUTO]] === `BOOST_LEAF_AUTO` .#include [source,c++] ---- #define BOOST_LEAF_AUTO(v, r)\ BOOST_LEAF_ASSIGN(auto v, r) ---- [.text-right] <> `BOOST_LEAF_AUTO` is useful when calling a function that returns `result` (other than `result`), if the desired behavior is to forward any errors to the caller verbatim. .Example: [source,c++] ---- leaf::result compute_value(); leaf::result add_values() { BOOST_LEAF_AUTO(v1, compute_value()); <1> BOOST_LEAF_AUTO(v2, compute_value()); <2> return v1 + v2; } ---- <1> Call `compute_value`, bail out on failure, define a local variable `v1` on success. <2> Call `compute_value` again, bail out on failure, define a local variable `v2` on success. Of course, we could write `add_value` without using `BOOST_LEAF_AUTO`. This is equivalent: ---- leaf::result add_values() { auto v1 = compute_value(); if( !v1 ) return v1.error(); auto v2 = compute_value(); if( !v2 ) return v2.error(); return v1.value() + v2.value(); } ---- NOTE: See also <>. ''' [[BOOST_LEAF_CHECK]] === `BOOST_LEAF_CHECK` .#include [source,c++] ---- #if BOOST_LEAF_CFG_GNUC_STMTEXPR #define BOOST_LEAF_CHECK(r)\ ({\ auto && <> = (r);\ if( !<> )\ return <>.error();\ std::move(<>);\ }).value() #else #define BOOST_LEAF_CHECK(r)\ {\ auto && <> = (r);\ if( !<> )\ return <>.error();\ } #endif ---- `BOOST_LEAF_CHECK` is useful when calling a function that returns `result`, if the desired behavior is to forward any errors to the caller verbatim. .Example: [source,c++] ---- leaf::result send_message( char const * msg ); leaf::result compute_value(); leaf::result say_hello_and_compute_value() { BOOST_LEAF_CHECK(send_message("Hello!")); <1> return compute_value(); } ---- <1> Try to send a message, then compute a value, report errors using BOOST_LEAF_CHECK. Equivalent implementation without `BOOST_LEAF_CHECK`: ---- leaf::result add_values() { auto r = send_message("Hello!"); if( !r ) return r.error(); return compute_value(); } ---- If `BOOST_LEAF_CFG_GNUC_STMTEXPR` is `1` (which is the default under `pass:[__GNUC__]`), `BOOST_LEAF_CHECK` expands to a https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html[GNU C statement expression], which allows its use with non-`void` result types in any expression; see <>. ''' [[BOOST_LEAF_THROW_EXCEPTION]] === `BOOST_LEAF_THROW_EXCEPTION` [source,c++] .#include ---- #define BOOST_LEAF_THROW_EXCEPTION <> ---- 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). ''' [[BOOST_LEAF_NEW_ERROR]] === `BOOST_LEAF_NEW_ERROR` .#include [source,c++] ---- #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). [[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. We're now ready to define our Design goals: :: * *Error initiating* functions should be able to communicate [underline]#all# information available to them that is relevant to the failure being reported. * *Error neutral* functions should not be coupled with error types communicated by lower-level _error initiating_ functions. They should be able to augment any failure with additional relevant information available to them. * *Error handling* functions should be able to access all the information communicated by _error initiating_ or _error neutral_ functions that is needed in order to deal with failures. The design goal that _error neutral_ functions are not coupled with the static type of error objects that pass through them seems to require dynamic polymorphism and therefore dynamic memory allocations (the Boost Exception library meets this design goal at the cost of dynamic memory allocation). As it turns out, dynamic memory allocation is not necessary due to the following Fact: :: * *Error handling* functions "know" which of the information _error initiating_ and _error neutral_ functions are [.underline]#able# to communicate is [.underline]#actually needed# in order to deal with failures in a particular program. Ideally, no resources should be [.line-through]#used# wasted storing or communicating information which is not currently needed to handle errors, [.underline]#even if it is relevant to the failure#. For example, if a library function is able to communicate an error code but the program does not need to know the exact error code, then that information may be ignored at the time the library function attempts to communicate it. On the other hand, if an _error handling_ function needs that information, the memory needed to store it can be reserved statically in its scope. The LEAF functions <>, <> and <> implement this idea. Users provide error handling lambda functions, each taking arguments of the types it needs in order to recover from a particular error condition. LEAF simply provides the space needed to store these types (in the form of a `std::tuple`, using automatic storage duration) until they are passed to a suitable handler. At the time this space is reserved in the scope of an error handling function, `thread_local` pointers of the required error types are set to point to the corresponding objects within it. Later on, _error initiating_ or _error neutral_ functions wanting to communicate an error object of a given type `E` use the corresponding `thread_local` pointer to detect if there is currently storage available for this type: * If the pointer is not null, storage is available and the object is moved into the pointed storage, exactly once -- regardless of how many levels of function calls must unwind before an _error handling_ function is reached. * If the pointer is null, storage is not available and the error object is discarded, since no error handling function makes any use of it in this program -- saving resources. This almost works, except we need to make sure that _error handling_ functions are protected from accessing stale error objects stored in response to previous failures, which would be a serious logic error. To this end, each occurrence of an error is assigned a unique <>. Each of the `E...` objects stored in error handling scopes is assigned an `error_id` as well, permanently associating it with a particular failure. Thus, to handle a failure we simply match the available error objects (associated with its unique `error_id`) with the argument types required by each user-provided error handling function. In terms of {CPP} exception handling, it is as if we could write something like: [source,c++] ---- try { auto r = process_file(); //Success, use r: .... } catch(file_read_error &, e_file_name const & fn, e_errno const & err) { std::cerr << "Could not read " << fn << ", errno=" << err << std::endl; } catch(file_read_error &, e_errno const & err) { std::cerr << "File read error, errno=" << err << std::endl; } catch(file_read_error &) { std::cerr << "File read error!" << std::endl; } ---- Of course this syntax is not valid, so LEAF uses lambda functions to express the same idea: [source,c++] ---- leaf::try_catch( [] { auto r = process_file(); //Throws in case of failure, error objects stored inside the try_catch scope //Success, use r: .... } [](file_read_error &, e_file_name const & fn, e_errno const & err) { std::cerr << "Could not read " << fn << ", errno=" << err << std::endl; }, [](file_read_error &, e_errno const & err) { std::cerr << "File read error, errno=" << err << std::endl; }, [](file_read_error &) { std::cerr << "File read error!" << std::endl; } ); ---- [.text-right] <> | <> | <> Similar syntax works without exception handling as well. Below is the same snippet, written using `<>`: [source,c++] ---- return leaf::try_handle_some( []() -> leaf::result { BOOST_LEAF_AUTO(r, process_file()); //In case of errors, error objects are stored inside the try_handle_some scope //Success, use r: .... return { }; } [](leaf::match, e_file_name const & fn, e_errno const & err) { std::cerr << "Could not read " << fn << ", errno=" << err << std::endl; }, [](leaf::match, e_errno const & err) { std::cerr << "File read error, errno=" << err << std::endl; }, [](leaf::match) { std::cerr << "File read error!" << std::endl; } ); ---- [.text-right] <> | <> | <> | <> | <> NOTE: Please post questions and feedback on the Boost Developers Mailing List. ''' [[exception_specifications]] === Critique 1: Error Types Do Not Participate in Function Signatures A knee-jerk critique of the LEAF design is that it does not statically enforce that each possible error condition is recognized and handled by the program. One idea I've heard from multiple sources is to add `E...` parameter pack to `result`, essentially turning it into `expected`, so we could write something along these lines: [source,c++] ---- expected f() noexcept; <1> expected g() noexcept <2> { if( expected r = f() ) { return r; //Success, return the T } else { return r.handle_error( [] ( .... ) <3> { .... } ); } } ---- <1> `f` may only return error objects of type `E1`, `E2`, `E3`. <2> `g` narrows that to only `E1` and `E3`. <3> Because `g` may only return error objects of type `E1` and `E3`, it uses `handle_error` to deal with `E2`. In case `r` contains `E1` or `E3`, `handle_error` simply returns `r`, narrowing the error type parameter pack from `E1, E2, E3` down to `E1, E3`. If `r` contains an `E2`, `handle_error` calls the supplied lambda, which is required to return one of `E1`, `E3` (or a valid `T`). The motivation here is to help avoid bugs in functions that handle errors that pop out of `g`: as long as the programmer deals with `E1` and `E3`, he can rest assured that no error is left unhandled. Congratulations, we've just discovered exception specifications. The difference is that exception specifications, before being removed from {CPP}, were enforced dynamically, while this idea is equivalent to statically-enforced exception specifications, like they are in Java. Why not use the equivalent of exception specifications, even if they are enforced statically? "The short answer is that nobody knows how to fix exception specifications in any language, because the dynamic enforcement {CPP} chose has only different (not greater or fewer) problems than the static enforcement Java chose. ... When you go down the Java path, people love exception specifications until they find themselves all too often encouraged, or even forced, to add `throws Exception`, which immediately renders the exception specification entirely meaningless. (Example: Imagine writing a Java generic that manipulates an arbitrary type `T`).footnote:[https://herbsutter.com/2007/01/24/questions-about-exception-specifications/]" -- Herb Sutter Consider again the example above: assuming we don't want important error-related information to be lost, values of type `E1` and/or `E3` must be able to encode any `E2` value dynamically. But like Sutter points out, in generic contexts we don't know what errors may result in calling a user-supplied function. The only way around that is to specify a single type (e.g. `std::error_code`) that can communicate any and all errors, which ultimately defeats the idea of using static type checking to enforce correct error handling. That said, in every program there are certain _error handling_ functions (e.g. `main`) which are required to handle any error, and it is highly desirable to be able to enforce this requirement at compile-time. In LEAF, the `try_handle_all` function implements this idea: if the user fails to supply at least one handler that will match any error, the result is a compile error. This guarantees that the scope invoking `try_handle_all` is prepared to recover from any failure. ''' [[translation]] === Critique 2: LEAF Does Not Facilitate Mapping Between Different Error Types Most {CPP} programs use multiple C and {CPP} libraries, and each library may provide its own system of error codes. But because it is difficult to define static interfaces that can communicate arbitrary error code types, a popular idea is to map each library-specific error code to a common program-wide enum. For example, if we have -- [source,c++,options="nowrap"] ---- namespace lib_a { enum error { ok, ec1, ec2, .... }; } ---- [source,c++,options="nowrap"] ---- namespace lib_b { enum error { ok, ec1, ec2, .... }; } ---- -- we could define: [source,c++] ---- namespace program { enum error { ok, lib_a_ec1, lib_a_ec2, .... lib_b_ec1, lib_b_ec2, .... }; } ---- An error handling library could provide conversion API that uses the {CPP} static type system to automate the mapping between the different error enums. For example, it may define a class template `result` with value-or-error variant semantics, so that: * `lib_a` errors are transported in `result`, * `lib_b` errors are transported in `result`, * then both are automatically mapped to `result` once control reaches the appropriate scope. There are several problems with this idea: * It is prone to errors, both during the initial implementation as well as under maintenance. * It does not compose well. For example, if both of `lib_a` and `lib_b` use `lib_c`, errors that originate in `lib_c` would be obfuscated by the different APIs exposed by each of `lib_a` and `lib_b`. * It presumes that all errors in the program can be specified by exactly one error code, which is false. To elaborate on the last point, consider a program that attempts to read a configuration file from three different locations: in case all of the attempts fail, it should communicate each of the failures. In theory `result` handles this case well: [source,c++] ---- struct attempted_location { std::string path; error ec; }; struct config_error { attempted_location current_dir, user_dir, app_dir; }; result read_config(); ---- This looks nice, until we realize what the `config_error` type means for the automatic mapping API we wanted to define: an `enum` can not represent a `struct`. It is a fact that we can not assume that all error conditions can be fully specified by an `enum`; an error handling library must be able to transport arbitrary static types efficiently. [[errors_are_not_implementation_details]] === Critique 3: LEAF Does Not Treat Low Level Error Types as Implementation Details This critique is a combination of <> and <>, but it deserves special attention. Let's consider this example using LEAF: [source,c++] ---- leaf::result read_line( reader & r ); leaf::result parse_line( std::string const & line ); leaf::result read_and_parse_line( reader & r ) { BOOST_LEAF_AUTO(line, read_line(r)); <1> BOOST_LEAF_AUTO(parsed, parse_line(line)); <2> return parsed; } ---- [.text-right] <> | <> <1> Read a line, forward errors to the caller. <2> Parse the line, forward errors to the caller. The objection is that LEAF will forward verbatim the errors that are detected in `read_line` or `parse_line` to the caller of `read_and_parse_line`. The premise of this objection is that such low-level errors are implementation details and should be treated as such. Under this premise, `read_and_parse_line` should act as a translator of sorts, in both directions: * When called, it should translate its own arguments to call `read_line` and `parse_line`; * If an error is detected, it should translate the errors from the error types returned by `read_line` and `parse_line` to a higher-level type. The motivation is to isolate the caller of `read_and_parse_line` from its implementation details `read_line` and `parse_line`. There are two possible ways to implement this translation: *1)* `read_and_parse_line` understands the semantics of *all possible failures* that may be reported by both `read_line` and `parse_line`, implementing a non-trivial mapping which both _erases_ information that is considered not relevant to its caller, as well as encodes _different_ semantics in the error it reports. In this case `read_and_parse_line` assumes full responsibility for describing precisely what went wrong, using its own type specifically designed for the job. *2)* `read_and_parse_line` returns an error object that essentially indicates which of the two inner functions failed, and also transports the original error object without understanding its semantics and without any loss of information, wrapping it in a new error type. The problem with *1)* is that typically the caller of `read_and_parse_line` is not going to handle the error, but it does need to forward it to its caller. In our attempt to protect the *one* error handling function from "implementation details", we've coupled the interface of *all* intermediate error neutral functions with the static types of errors they do not understand and do not handle. Consider the case where `read_line` communicates `errno` in its errors. What is `read_and_parse_line` supposed to do with e.g. `EACCESS`? Turn it into `READ_AND_PARSE_LINE_EACCESS`? To what end, other than to obfuscate the original (already complex and platform-specific) semantics of `errno`? And what if the call to `read` is polymorphic, which is also typical? What if it involves a user-supplied function object? What kinds of errors does it return and why should `read_and_parse_line` care? Therefore, we're left with *2)*. There's almost nothing wrong with this option, since it passes any and all error-related information from lower level functions without any loss. However, using a wrapper type to grant (presumably dynamic) access to any lower-level error type it may be transporting is cumbersome and (like Niall Douglas <>) in general probably requires dynamic allocations. It is better to use independent error types that communicate the additional information not available in the original error object, while error handlers rely on LEAF to provide efficient access to any and all low-level error types, as needed. == Alternatives to LEAF * https://www.boost.org/doc/libs/release/libs/exception/doc/boost-exception.html[Boost Exception] * https://ned14.github.io/outcome[Boost Outcome] * https://github.com/TartanLlama/expected[`tl::expected`] Below we offer a comparison of Boost LEAF to Boost Exception and to Boost Outcome. [[boost_exception]] === Comparison to Boost Exception While LEAF can be used without exception handling, in the use case when errors are communicated by throwing exceptions, it can be viewed as a better, more efficient alternative to Boost Exception. LEAF has the following advantages over Boost Exception: * LEAF does not allocate memory dynamically; * LEAF does not waste system resources communicating error objects not used by specific error handling functions; * LEAF does not store the error objects in the exception object, and therefore it is able to augment exceptions thrown by external libraries (Boost Exception can only augment exceptions of types that derive from `boost::exception`). The following tables outline the differences between the two libraries which should be considered when code that uses Boost Exception is refactored to use LEAF instead. NOTE: It is possible to access Boost Exception error information using the LEAF error handling interface. See <>. .Defining a custom type for transporting values of type T [cols="1a,1a",options="header",stripes=none] |==== | Boost Exception | LEAF | [source,c++,options="nowrap"] ---- typedef error_info my_info; ---- [.text-right] https://www.boost.org/doc/libs/release/libs/exception/doc/error_info.html[`boost::error_info`] | [source,c++,options="nowrap"] ---- struct my_info { T value; }; ---- |==== .Passing arbitrary info at the point of the throw [cols="1a,1a",options="header",stripes=none] |==== | Boost Exception | LEAF | [source,c++,options="nowrap"] ---- throw my_exception() << my_info(x) << my_info(y); ---- [.text-right] https://www.boost.org/doc/libs/release/libs/exception/doc/exception_operator_shl.html[`operator<<`] | [source,c++,options="nowrap"] ---- leaf::throw_exception( my_exception(), my_info{x}, my_info{y} ); ---- [.text-right] <> |==== .Augmenting exceptions in error neutral contexts [cols="1a,1a",options="header",stripes=none] |==== | Boost Exception | LEAF | [source,c++,options="nowrap"] ---- try { f(); } catch( boost::exception & e ) { e << my_info(x); throw; } ---- [.text-right] https://www.boost.org/doc/libs/release/libs/exception/doc/exception.html[`boost::exception`] \| https://www.boost.org/doc/libs/release/libs/exception/doc/exception_operator_shl.html[`operator<<`] | [source,c++,options="nowrap"] ---- auto load = leaf::on_error( my_info{x} ); f(); ---- [.text-right] <> |==== .Obtaining arbitrary info at the point of the catch [cols="1a,1a",options="header",stripes=none] |==== | Boost Exception | LEAF | [source,c++,options="nowrap"] ---- try { f(); } catch( my_exception & e ) { if( T * v = get_error_info(e) ) { //my_info is available in e. } } ---- [.text-right] https://www.boost.org/doc/libs/release/libs/exception/doc/get_error_info.html[`boost::get_error_info`] | [source,c++,options="nowrap"] ---- leaf::try_catch( [] { f(); // throws } [](my_exception &, my_info const & x) { //my_info is available with //the caught exception. } ); ---- [.text-right] <> |==== .Transporting of error objects [cols="1a,1a",options="header",stripes=none] |==== | Boost Exception | LEAF | All supplied https://www.boost.org/doc/libs/release/libs/exception/doc/error_info.html[`boost::error_info`] objects are allocated dynamically and stored in the https://www.boost.org/doc/libs/release/libs/exception/doc/exception.html[`boost::exception`] subobject of exception objects. | User-defined error objects are stored statically in the scope of <>, but only if their types are needed to handle errors; otherwise they are discarded. |==== .Transporting of error objects across thread boundaries [cols="1a,1a",options="header",stripes=none] |==== | Boost Exception | LEAF | https://www.boost.org/doc/libs/release/libs/exception/doc/exception_ptr.html[`boost::exception_ptr`] automatically captures https://www.boost.org/doc/libs/release/libs/exception/doc/error_info.html[`boost::error_info`] objects stored in a `boost::exception` and can transport them across thread boundaries. | Transporting error objects across thread boundaries requires the use of <>. |==== .Printing of error objects in automatically-generated diagnostic information messages [cols="1a,1a",options="header",stripes=none] |==== | Boost Exception | LEAF | `boost::error_info` types may define conversion to `std::string` by providing `to_string` overloads *or* by overloading `operator<<` for `std::ostream`. | LEAF does not use `to_string`. Error types may define `operator<<` overloads for `std::ostream`. |==== [WARNING] ==== The fact that Boost Exception stores all supplied `boost::error_info` objects -- while LEAF discards them if they aren't needed -- affects the completeness of the message we get when we print `leaf::<>` objects, compared to the string returned by https://www.boost.org/doc/libs/release/libs/exception/doc/diagnostic_information.html[`boost::diagnostic_information`]. If the user requires a complete diagnostic message, the solution is to use `leaf::<>`. In this case, before unused error objects are discarded by LEAF, they are converted to string and printed. Note that this allocates memory dynamically. ==== ''' [[boost_outcome]] === Comparison to Boost Outcome ==== Design Differences Like LEAF, the https://ned14.github.io/outcome[Boost Outcome] library is designed to work in low latency environments. It provides two class templates, `result<>` and `outcome<>`: * `result` can be used as the return type in `noexcept` functions which may fail, where `T` specifies the type of the return value in case of success, while `EC` is an "error code" type. Semantically, `result` is similar to `std::variant`. Naturally, `EC` defaults to `std::error_code`. * `outcome` is similar to `result<>`, but in case of failure, in addition to the "error code" type `EC` it can hold a "pointer" object of type `EP`, which defaults to `std::exception_ptr`. NOTE: `NVP` is a policy type used to customize the behavior of `.value()` when the `result<>` or the `outcome<>` object contains an error. The idea is to use `result<>` to communicate failures which can be fully specified by an "error code", and `outcome<>` to communicate failures that require additional information. Another way to describe this design is that `result<>` is used when it suffices to return an error object of some static type `EC`, while `outcome<>` can also transport a polymorphic error object, using the pointer type `EP`. NOTE: In the default configuration of `outcome` the additional information -- or the additional polymorphic object -- is an exception object held by `std::exception_ptr`. This targets the use case when an exception thrown by a lower-level library function needs to be transported through some intermediate contexts that are not exception-safe, to a higher-level context able to handle it. LEAF directly supports this use as well, see <>. Similar reasoning drives the design of LEAF as well. The difference is that while both libraries recognize the need to transport "something else" in addition to an "error code", LEAF provides an efficient solution to this problem, while Outcome shifts this burden to the user. The `leaf::result<>` template deletes both `EC` and `EP`, which decouples it from the type of the error objects that are transported in case of a failure. This enables lower-level functions to freely communicate anything and everything they "know" about the failure: error code, even multiple error codes, file names, URLs, port numbers, etc. At the same time, the higher-level error handling functions control which of this information is needed in a specific client program and which is not. This is ideal, because: * Authors of lower-level library functions lack context to determine which of the information that is both relevant to the error _and_ naturally available to them needs to be communicated in order for a particular client program to recover from that error; * Authors of higher-level error handling functions can easily and confidently make this determination, which they communicate naturally to LEAF, by simply writing the different error handlers. LEAF will transport the needed error objects while discarding the ones handlers don't care to use, saving resources. TIP: The LEAF examples include an adaptation of the program from the https://ned14.github.io/outcome/tutorial/essential/result/[Boost Outcome `result<>` tutorial]. You can https://github.com/boostorg/leaf/blob/master/example/print_half.cpp?ts=4[view it on GitHub]. NOTE: Programs using LEAF for error handling are not required to use `leaf::result`; for example, it is possible to use `outcome::result` with LEAF. [[interoperability]] ==== The Interoperability Problem The Boost Outcome documentation discusses the important problem of bringing together multiple libraries -- each using its own error reporting mechanism -- and incorporating them in a robust error handling infrastructure in a client program. Users are advised that whenever possible they should use a common error handling system throughout their entire codebase, but because this is not practical, both the `result<>` and the `outcome<>` templates can carry user-defined "payloads". The following analysis is from the Boost Outcome documentation: ==== If library A uses `result`, and library B uses `result` and so on, there becomes a problem for the application writer who is bringing in these third party dependencies and tying them together into an application. As a general rule, each third party library author will not have built in explicit interoperation support for unknown other third party libraries. The problem therefore lands with the application writer. The application writer has one of three choices: . In the application, the form of result used is `result>` where `E1, E2 …` are the failure types for every third party library in use in the application. This has the advantage of preserving the original information exactly, but comes with a certain amount of use inconvenience and maybe excessive coupling between high level layers and implementation detail. . One can translate/map the third party’s failure type into the application’s failure type at the point of the failure exiting the third party library and entering the application. One might do this, say, with a C preprocessor macro wrapping every invocation of the third party API from the application. This approach may lose the original failure detail, or mis-map under certain circumstances if the mapping between the two systems is not one-one. . One can type erase the third party’s failure type into some application failure type, which can later be reconstituted if necessary. *This is the cleanest solution with the least coupling issues and no problems with mis-mapping*, but it almost certainly requires the use of `malloc` which the previous two did not. ==== The analysis above (emphasis added) is clear and precise, but LEAF and Boost Outcome tackle the interoperability problem differently: * The Boost Outcome design asserts that the "cleanest" solution based on type-erasure is suboptimal ("almost certainly requires the use of `malloc`pass:[]"), and instead provides a system for injecting custom converters into the `outcome::convert` namespace, used to translate between library-specific and program-wide error types, even though this approach "may lose the original failure detail". * The LEAF design asserts that coupling the signatures of <> functions with the static types of the error objects they need to forward to the caller <>, and instead transports error objects directly to error handling scopes where they are stored statically, effectively implementing the third choice outlined above (without the use of `malloc`). Further, consider that Outcome aims to hopefully become _the_ one error handling API all libraries would use, and in theory everyone would benefit from uniformity and standardization. But the reality is that this is wishful thinking. In fact, that reality is reflected in the design of `outcome::result<>`, in its lack of commitment to using `std::error_code` for its intended purpose: to be _the_ standard type for transporting error codes. The fact is that `std::error_code` became _yet another_ error code type programmers need to understand and support. In contrast, the design of LEAF acknowledges that {CPP} programmers don't even agree on what a string is. If your project uses 10 different libraries, this probably means 15 different ways to report errors, sometimes across uncooperative interfaces (e.g. C APIs). LEAF helps you get the job done. == Benchmark https://github.com/boostorg/leaf/blob/master/benchmark/benchmark.md[This benchmark] compares the performance of LEAF, Boost Outcome and `tl::expected`. == Running the Unit Tests The unit tests can be run with https://mesonbuild.com[Meson Build] or with Boost Build. To run the unit tests: === Meson Build Clone LEAF into any local directory and execute: [source,sh] ---- cd leaf meson bld/debug cd bld/debug meson test ---- See `meson_options.txt` found in the root directory for available build options. === Boost Build Assuming the current working directory is `/libs/leaf`: [source,sh] ---- ../../b2 test ---- [[configuration]] == Configuration The following configuration macros are recognized: * `BOOST_LEAF_CFG_DIAGNOSTICS`: Defining this macro as `0` stubs out both <> and <> (if the macro is left undefined, LEAF defines it as `1`). * `BOOST_LEAF_CFG_STD_SYSTEM_ERROR`: Defining this macro as `0` disables the `std::error_code` / `std::error_condition` integration. In this case LEAF does not `#include `, which may be too heavy for embedded platforms (if the macro is left undefined, LEAF defines it as `1`). * `BOOST_LEAF_CFG_STD_STRING`: Defining this macro as `0` disables all use of `std::string` (this requires `BOOST_LEAF_CFG_DIAGNOSTICS=0` as well). In this case LEAF does not `#include ` which may be too heavy for embedded platforms (if the macro is left undefined, LEAF defines it as `1`). * `BOOST_LEAF_CFG_CAPTURE`: Defining this macro as `0` disables the ability of `leaf::result` to transport errors between threads. In this case LEAF does not `#include `, which may be too heavy for embedded platforms (if the macro is left undefined, LEAF defines it as `1`). * `BOOST_LEAF_CFG_GNUC_STMTEXPR`: This macro controls whether or not <> is defined in terms of a https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html[GNU C statement expression], which enables its use to check for errors similarly to how the questionmark operator works in some languages (see <>). By default the macro is defined as `1` under `pass:[__GNUC__]`, otherwise as `0`. * `BOOST_LEAF_CFG_WIN32`: Defining this macro as 1 enables the default constructor in <>, and the automatic conversion to string (via `FormatMessageA`) when <> is printed. If the macro is left undefined, LEAF defines it as `0` (even on windows, since including `windows.h` is generally not desirable). Note that the `e_LastError` type itself is available on all platforms, there is no need for conditional compilation in error handlers that use it. * `BOOST_LEAF_NO_EXCEPTIONS`: Disables all exception handling support. If left undefined, LEAF defines it automatically based on the compiler configuration (e.g. `-fno-exceptions`). * `BOOST_LEAF_NO_THREADS`: Disables all thread safety in LEAF. [[configuring_tls_access]] === Configuring TLS Access LEAF requires support for thread-local `void` pointers. By default, this is implemented by means of the {CPP}11 `thread_local` keyword, but in order to support <>, it is possible to configure LEAF to use an array of thread local pointers instead, by defining `BOOST_LEAF_USE_TLS_ARRAY`. In this case, the user is required to define the following two functions to implement the required TLS access: [source,c++] ---- namespace boost { namespace leaf { namespace tls { void * read_void_ptr( int tls_index ) noexcept; void write_void_ptr( int tls_index, void * p ) noexcept; } } } ---- TIP: For efficiency, `read_void_ptr` and `write_void_ptr` should be defined `inline`. Under `BOOST_LEAF_USE_TLS_ARRAY` the following additional configuration macros are recognized: * `BOOST_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. Ivo Belchev, Sean Palmer, Jason King, Vinnie Falco, Glen Fernandes, Augustín Bergé -- thanks for the valuable feedback. Documentation rendered by https://asciidoctor.org/[Asciidoctor] with https://github.com/zajo/asciidoctor_skin[these customizations]. ================================================ FILE: doc/rouge-github.css ================================================ .highlight table td { padding: 5px; } .highlight table pre { margin: 0; } .highlight .cm { color: #999988; font-style: italic; } .highlight .cp { color: #999999; font-weight: bold; } .highlight .c1 { color: #999988; font-style: italic; } .highlight .cs { color: #999999; font-weight: bold; font-style: italic; } .highlight .c, .highlight .cd { color: #999988; font-style: italic; } .highlight .err { } .highlight .gd { color: #000000; background-color: #ffdddd; } .highlight .ge { color: #000000; font-style: italic; } .highlight .gr { color: #aa0000; } .highlight .gh { color: #999999; } .highlight .gi { color: #000000; background-color: #ddffdd; } .highlight .go { color: #888888; } .highlight .gp { color: #555555; } .highlight .gs { font-weight: bold; } .highlight .gu { color: #aaaaaa; } .highlight .gt { color: #aa0000; } .highlight .kc { font-weight: bold; } .highlight .kd { font-weight: bold; } .highlight .kn { font-weight: bold; } .highlight .kp { font-weight: bold; } .highlight .kr { font-weight: bold; } .highlight .kt { color: #445588; font-weight: bold; } .highlight .k, .highlight .kv { font-weight: bold; } .highlight .mf { color: #009999; } .highlight .mh { color: #009999; } .highlight .il { color: #009999; } .highlight .mi { color: #009999; } .highlight .mo { color: #009999; } .highlight .m, .highlight .mb, .highlight .mx { color: #009999; } .highlight .sb { color: #d14; } .highlight .sc { color: #d14; } .highlight .sd { color: #d14; } .highlight .s2 { color: #d14; } .highlight .se { color: #d14; } .highlight .sh { color: #d14; } .highlight .si { color: #d14; } .highlight .sx { color: #d14; } .highlight .sr { color: #009926; } .highlight .s1 { color: #d14; } .highlight .ss { color: #990073; } .highlight .s { color: #d14; } .highlight .na { color: #008080; } .highlight .bp { color: #999999; } .highlight .nb { color: #0086B3; } .highlight .nc { color: #445588; font-weight: bold; } .highlight .no { color: #008080; } .highlight .nd { color: #3c5d5d; font-weight: bold; } .highlight .ni { color: #800080; } .highlight .ne { color: #990000; font-weight: bold; } .highlight .nf { color: #990000; font-weight: bold; } .highlight .nl { color: #990000; font-weight: bold; } .highlight .nn { color: #555555; } .highlight .nt { color: #000080; } .highlight .vc { color: #008080; } .highlight .vg { color: #008080; } .highlight .vi { color: #008080; } .highlight .nv { color: #008080; } .highlight .ow { font-weight: bold; } .highlight .o { font-weight: bold; } .highlight .o { font-weight: bold; } .highlight .w { color: #bbbbbb; } ================================================ FILE: doc/whitepaper.md ================================================ # Error Handling Principles and Practices ## Abstract Error handling is an important part of language design and programming in general. We deconstruct the problem domain in an attempt to derive an objective understanding of the pros and cons of the various approaches to error handling. While we use C++ throughout this paper, our reasoning applies to any statically-typed language. We present, with implementation, a novel method for communication of error objects of arbitrary types safely, without using dynamic memory allocation. In addition, we analyze the effect of aggressive inlining on the overhead of exception handling in C++, without a need to change the standard or the ABIs. ## 1. The semantics of a failure Programmers have an intuitive understanding of the nature of error handling: while coding, we naturally reason in terms of "what if something goes wrong". One way to express this reasoning is to return from functions which may fail some `expected` variant type, which holds a `T` in case of success or an `E` in case of failure. For example: ```c++ expected compute_value(); ``` Above, `compute_value` produces an `int`, but if that fails, it would communicate an object of type `error_code`, which would indicate the reason for the failure. But here is an interesting question: what happens if the type we pass for `T` to `expected` is itself a variant type? Of course this isn't a problem: ```c++ expected, error_code> compute_value(); // (A) ``` What makes the above function interesting is that syntactically, it returns an `int`, or a `float`, or an `error_code`; and since we're already returning a variant, could we ditch `expected` altogether? We most definitely could: ```c++ variant compute_value(); // (B) ``` Are the two functions (A) and (B) semantically equivalent? It appears that any algorithm working with the result from (A) can be transformed to handle a call to (B) without any loss of functionality. This follows directly form the fact that either way there are three distinct outcomes, so the differences should be purely mechanical rather than in logic. In fact there is one subtle but critical difference: (A) encodes explicitly in the return object an additional bit of information -- "success-or-error" -- while in (B) that knowledge is implicit: we have to keep it in mind as we write the caller function, but it is not reflected in the program state. > **Definition:** The one bit of information that indicates whether a function has failed is called the *failure flag*. Therefore it is not true that any algorithm working with the result from (A) can be transformed to handle a call to (B): the exception is algorithms that respond generically to any error, based solely on observing the *failure flag* being set. The ability to implement such algorithms is the reason why explicitly encoding this extra bit of information in (A) is not pure overhead, compared to (B). Of course, this reasoning applies in general: if a function reports a failure, it is important for the caller to be able to react to it without further semantic understanding of each possible error condition; that is, it is a good idea to optimize error handling for this relatively common use case. ## 2. Classification of functions based on their affinity to errors > **Definition:** Functions that create error objects and initiate error handling are called *error initiating* functions. These are functions which, based on the semantics of the operations they perform, flag certain outcomes as failures, reporting the causes to their caller. > **Definition:** Functions which forward to the caller error information communicated by lower-level functions are called *error neutral* functions. These functions react solely based on the [*failure flag*](#1-the-semantics-of-a-failure) indicated by a lower-level function, forwarding failures to the caller without understanding the semantics of the error ("something went wrong"). For example, an *error initiating* function may initialize a new `std::error_code` object to describe a failure, while an *error neutral* function may just forward the `std::error_code` returned by a lower-level function to its own caller. Of course, *error neutral* functions may contribute additional error information. The key difference between *error initiating* and *error neutral* functions is that the latter do not understand the semantics of lower-level failures, they simply react based on the value of the *failure flag*. > **Definition:** > Functions which dispose of error objects they have received and recover normal program operation are called *error handling* functions. All information communicated by *error initiating* and *error neutral* functions in case of a failure targets an *error handling* function found up the call stack. In order to take appropriate action to resume normal program operation, that function must understand the semantics of at least some possible error conditions that may occur in lower-level functions (the exception is functions that act as catch-all handlers, which are designed to recover from any and all error conditions, possibly after logging all available relevant information.) Note that an *error handling* function may act as *error neutral* as well, by forwarding to its caller some failures it does not recognize and therefore can not recover from. ## 3. Types of error information based on context Consider a function which opens a file using [`open()`](http://man7.org/linux/man-pages/man2/open.2.html), reads it then parses it. If it fails, we need to know what failed: * Did the file fail to open? * Was the file opened successfully but the attempt to read it failed? * Was there a parsing error after the file was successfully read? Such simple booleans may be sufficient sometimes, but usually they are not. Reasonably, we need to respond differently depending on whether the call to `open()` resulted in `ENOENT` vs. `EACCESS` -- and if we got `EEXIST`, that would be a logic error. Therefore we need to know the relevant `errno` also. Secondly, if the file failed to open, we need to know the `pathname` passed to `open()`, in case it happens to be incorrect. But what if it is correct and yet `open()` failed? Right, we probably need to know the `flags` argument passed to `open()` as well. Similar reasoning applies to the reading step, except there is an additional complication: in the function that reads the file we use the `int` handle to identify the file, and therefore we don't have access to the `pathname` to report in case the call to [`read()`](http://man7.org/linux/man-pages/man2/read.2.html) fails. And if the failure is detected in the parsing step, the file may be closed already, so we may not even have the handle available. Is it important to know the name of the file which we failed to read or parse? It sure is. What got us on the error handling path (*error neutral* functions forwarding the failure to their caller, until an *error handling* scope is reached) may be a failure to read or parse the file, but once we reach a scope where the `pathname` is available, we should be able to report it in addition to the initial error information. ## 4. Handling of error information In the previous section we weren't concerned with how the error information (`errno`, `pathname`, etc.) is handled, we were only reasoning about what we need to know in case a failure occurs. But the question remains: yes, the `pathname` and `flags` passed to `open()` are relevant to any failure in any operation related to that file, but what are we supposed to do with them? There are several options: * Don't bother with any error information beyond a basic error code. * Print the information in a log. * Convert relevant error information to string and store that in the object returned in case of failure. * Store them, in a type-safe manner, in the object returned in case of failure. We'll examine each option in more detail below. ### 4.1. Communicating an error code and nothing more This approach is actually perfect for low-level libraries. The burden of transporting additional necessary information is shifted to the caller, which is arguably where it should be in this case: all relevant information leading to failures detected in a low-level function is available in the calling scopes. For example, it would be inappropriate if a function like `read()` tries to log anything or return error information beyond an error code, because all other relevant information is available in the various scopes leading to the failure. However, this approach does not compose: as the error code bubbles up, each scope may hold additional relevant information that needs to be communicated or lost forever as that scope is exited; and that can't be done with a simple error code. For example, it may be difficult to deal with `ENOENT` without knowing the relevant `pathname` -- and if we're aborting a scope where that information is available, we should communicate it at that point. ### 4.2. Communicating an error code, logging other relevant information This approach offers the simplicity of communicating just an error code, but it is usable in higher-level libraries. If a low-level function reports a failure, we log any relevant information we have, then return an error code to the caller, and the process repeats until an *error handling* function is reached. Alternatively, the logging may be done as a matter of routine, not only in case a failure is detected. There are several problems with this approach: * It couples us with a logging system, which may not be a problem in the domain of a particular project, but certainly is not ideal for a universal library. * Depending on the use case, it may be too costly to hit the file system or some other logging target while handling errors. * The information in the log is developer-friendly, but not user-friendly. There are many projects where this is not a problem (for example, internet servers), but generally it is not appropriate to present a wall of cryptic diagnostic information to a user in hopes he will find clues in it to help fix the problem. But even a developer-facing command line utility has to print error information in plain English -- and the typical user-friendly app has to be able to use different languages. ### 4.3. Communicating an error code + a string The main appeal of this approach is that like logging error information, it composes nicely: if a lower level function communicates an error code, we can easily convert it to string, together with any other information available in our scope (e.g. the `pathname`), then return the string plus an error code to the caller. And of course this can be repeated in each calling scope: concatenate relevant information to the string and pass it on together with an(other) error code. What's more, in C++ the conversion of any type of error information to string is easy to define in terms of `std::ostream` `operator<<` overloads, so at each level we can process lower-level failures generically. In the end, the error handling function gets an error code (so it knows what went wrong), plus a string with relevant information that can be presented (or even logged) as "the reason" for the failure. While this is similar to writing the relevant error information in a log, this approach is arguably better because we don't depend on a logging system; but other downsides remain: * The result of the automatic conversion to string is not user-friendly. * The ability to concatenate strings usually requires dynamic memory allocations, which may be too slow in some cases. * Dynamic allocations may also fail, which is especially problematic during error handling. ### 4.4. Communicating all error information with type-safety The error handling strategies we discussed so far work well as long as automatically-printed (or logged) error information is sufficient. And while there are many problem domains where this is true, we still need a solution for the case when error handling code has to react to failures intelligently and to understand the available error information, rather than just print it for a developer to analyze. This requires that the various error objects delivered to an *error handling* function retain their static type even as they cross library boundaries; for example, in case of errors, the `flags` argument passed to `open()` should be communicated as an `int` rather than a `std::string`. More generally, this is known as "The Interoperability Problem". The following analysis is from Niall Douglas:[1](#reference) >If library A uses `result`, and library B uses `result` and so on, there becomes a problem for the application writer who is bringing in these third party dependencies and tying them together into an application. As a general rule, each third party library author will not have built in explicit interoperation support for unknown other third party libraries. The problem therefore lands with the application writer. > >The application writer has one of three choices: > >1. In the application, the form of result used is `result>` where `E1`, `E2` … are the failure types for every third party library in use in the application. This has the advantage of preserving the original information exactly, but comes with a certain amount of use inconvenience and maybe excessive coupling between high level layers and implementation detail. > >2. One can translate/map the third party’s failure type into the application’s failure type at the point of the failure exiting the third party library and entering the application. One might do this, say, with a C preprocessor macro wrapping every invocation of the third party API from the application. This approach may lose the original failure detail, or mis-map under certain circumstances if the mapping between the two systems is not one-one. > >3. One can type erase the third party’s failure type into some application failure type, which can later be reconstituted if necessary. This is the cleanest solution with the least coupling issues and no problems with mis-mapping, but it almost certainly requires the use of `malloc` which the previous two did not. An interesting observation is that the excessive coupling mentioned in the first point above is very similar to exception specifications. For example, if we have: ```c++ struct error_info { int error_code; std::string file_name; }; ``` And then: ```c++ expected compute_value(....); // (A) ``` This is very similar to: ```c++ int compute_value(....) throw(error_info); // (B) ``` The difference, of course, is that in (A) the compatibility with the caller is enforced statically, while C++ exception specifications were enforced dynamically ("were", because they are now removed from the language). So, in truth, (A) is equivalent not to (B), but to statically-enforced exception specifications, as they are in Java. What is the problem with statically-enforced exception specifications? Herb Sutter explains:[2](#reference) > The short answer is that nobody knows how to fix exception specifications in any language, because the dynamic enforcement C++ 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`). In other words, in the presence of dynamic or static polymorphism, it is impractical to force a user-supplied function to conform to a specific set of error types. For example, at the point of a polymorphic call to a `read()` function, we can not reasonably predict or statically specify all the error objects it may need to communicate. But what about non-generic contexts? Is the equivalent of statically-enforced exception specifications a good idea in that case? We'll discuss this important question next. ## 5. Error handling and function signatures Designers of any programming language, but especially statically-typed languages, take care to provide for compile-time checks to ensure that function calls work as intended. For example, the compiler itself should be able to automatically detect bugs where the caller provides the wrong number or type of arguments. In turn, the programmer would use the principle of encapsulation to logically decouple the caller of each function from the interface of lower level functions (A.K.A. implementation details). This is desirable because, assuming the interface of each function is correct, as long as *what* it does doesn't change, we can easily modify *how* it is done, with minimal disruption. This results in tight coupling between a caller and a callee: in order to call a function, we must understand its semantics and the semantics of each of its arguments; it's preconditions and postconditions, etc. Of course, this is not a problem, in fact this coupling is the reason why the compiler is able to detect many errors before the program even runs. On the other hand, not all objects a function needs to use should be passed through the narrow interface specified by its signature. For example, it is possible to pass a logger object as one of the arguments of each function which may need to print diagnostic information, but this is almost never done in practice; instead, the logging system is accessible globally. If we require that the logger is passed down as an argument, this would create difficulties for intermediate functions which don't need it: they would be coupled with an object they do not necessarily understand, only so they can pass it down to another function which may actually use it, but possibly just to pass it down to yet another function. When an object must be communicated down the call stack to a function several levels removed from the one that initiates the call, it is usually desirable to decouple the signature of all intermediate functions from that object, because their interface has nothing to do with it. The same reasoning applies to *error neutral* functions with regards to failures originating in lower-level functions. While it is possible to couple the signatures of intermediate functions with the static type of all the [error information they may need to communicate](#4-handling-of-error-information), this essentially destroys their neutrality towards failures. That's because, in order for each function to define a specific type to report all possible error objects statically, it must understand the exact semantics of all lower level error types. This turns what would have been a chain of calls to *error neutral* functions into a game of telephone, requiring each node to both understand and correctly re-encode each communicated failure. ## 6. Alternative mechanisms for transporting of error objects So far we established that in general it is not a good idea to couple return values (or function signatures) of *error neutral* functions with the static type of all error objects they may need to communicate. In this section we'll discuss the alternative approaches. ### 6.1. `GetLastError` / `errno` A typical classical approach is to only communicate the *failure flag* in the return value, while additional information is delivered through a separate mechanism. Here is an example from the Windows API: ```c BOOL DeleteFileW( LBCWSTR lpFileName ); ``` If the function succeeds, the return value is non-zero. If the function fails, the return value is zero. In case of failure, the user can call `GetLastError()` to obtain an error code: ```c DWORD GetLastError(); ``` This approach is appealing because it frees the return value from the burden of transporting any error information beyond the *failure flag*, a single bit. For example: ```c HANDLE CreateFileW( LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ); ``` Had the above function returned an error code, it would have to take one more argument to output the `HANDLE` in case of success. Instead, the return value *is* the file handle, reserving the special `INVALID_HANDLE_VALUE` to indicate a failure, while additional error information is obtained by calling `GetLastError()`. This same approach is used in many POSIX APIs, for example `open()`: ```c int open(const char *pathname, int flags); ``` The function attempts to open the file, returning the file handle or the special value `-1` to indicate a failure. In this case, the caller inspects `errno` for the error code. But there is another important benefit to this approach which is easy to overlook: it is specifically designed to facilitate the implementation of *error neutral* functions: ```c float read_data_and_compute_value(const char *pathname) { // Open the file, return INVALID_VALUE in case that fails: int fh = open(pathname, O_RDONLY); if (fh == -1) return INVALID_VALUE; // Read data, compute the value .... } ``` The above function computes a `float` value based on the contents of the specified file, reserving a single `INVALID_VALUE` (possibly a NaN) to allow the caller to effectively inspect the *failure flag*. In case of failure to `open()`, our function stays out of the way: the error code is communicated from `open()` (which sets the `errno`) *directly* to an *error handling* function up the call stack (which examines the `errno` in order to understand the failure), while the return value of each intermediate function needs only communicate a single bit of data (the *failure flag*). The major drawback of this appoach is that the *failure flag* is not communicated uniformly, which means that *error neutral* functions can't check for errors generically (e.g. each layer needs to know about the different `INVALID_VALUE`s). ### 6.2. C++ Exceptions In C++, the default mechanism for dealing with failures is exception handling. In this case, the check for errors is not only generic but completely automated: *by default*, if a function fails, the error will be communicated to the caller. Literally, the programmer can't forget to check the *failure flag*. The drawback of virtually all implementations is overhead, both in terms of space and speed. Below we'll analyze the reasons for this overhead, and point out ways to alleviate them. #### 6.2.1. Contemporary ABIs Contemporary C++ exception handling is notorious for overhead[3](#reference). There are two major flavors of exception handling implementations: frame-based and table-based: * **Frame-based** implementations (e.g. x86) add to the cost of stack frames (that is, function calls), which is already not insignificant in performance-critical parts of the program. The added cost affects both the happy and the sad path: function calls become a bit more expensive even if no exception is thrown. * **Table-based** implementations (e.g. Itanium, x64) add to the cost of stack frames but only on the sad path. In fact, the performance of the happy path is often improved. However, if an exception is thrown and stack unwinding must commence, the table-based approach leads to a reduction in speed, compared to frame-based implementations. Table-based exception handling has been designed based on the questionable assumption that it is critical to eliminate speed overhead in programs that don't `throw`. I'm saying questionable, because in practice such programs are compiled with `-fno-exceptions`. Ironically, the (older and less sophisticated) frame-based approach is preferable when we need to better control the cost of exception handling. The reason is that the overhead added to the happy path can be easily eliminated by inlining -- which is what we do anyway to deal with all other function-call overhead. This leaves only the cost of the sad path, which is also much more predictable, compared to the table-based approach. #### 6.2.2. Communicating the *failure flag* Current implementations do not communicate the *failure flag* explicitly. Instead, when throwing an exception, the compiler uses some form of automatic stack unwinding (possibly similar to `longjmp`) to reach the appropriate `catch` block, and to know which destructors to call. A much better approach would be for functions which may throw to communicate the *failure flag* explicitly, hopefully in the registers rather than spilling it to memory. This would allow each exception-neutral function to implement the error check, as well as to call the correct destructors in case of an error, with very little overhead. #### 6.2.3. Allocation of exception objects Consider the following exception type: ```c++ struct my_error: std::exception {}; ``` A catch statement designed to handle `my_error` exceptions: ```c++ try { f(); } catch(my_error & e) { .... } ``` If the above `catch` was only required to match objects of type `my_error`, they could be allocated on the stack, in the error handling scope, using automatic storage duration. However, `catch` must also match objects of any type that derives from `my_error`, and therefore the size of the exception object can not in general be known in this scope. For this reason, contemporary implementations allocate the memory for exception objects dynamically. A better approach[4](#reference) is to pre-allocate a stack-based buffer of some generally sufficient static size, leaving the option to allocate very large exception objects dynamically, similarly to the way `std::string` is typically implemented using small string optimization. #### 6.2.4. We do not need a new language (not even a new ABI) There are several ongoing efforts to improve the performance of exception handling[5](#reference), however most of them propose (and require) changes to the C++ language definition. Here we offer an alternative idea which does not, and will likely significantly alleviate the need for further improvements. Consider the following program: ```c++ #include int main() { try { throw std::exception(); } catch(std::exception & e) { } return 0; } ``` And here is the generated code ([Godbolt](https://godbolt.org/z/_a8eg9)): ```x86asm main: push rcx mov edi, 8 call __cxa_allocate_exception mov edx, OFFSET FLAT:_ZNSt9exceptionD1Ev mov esi, OFFSET FLAT:_ZTISt9exception mov QWORD PTR [rax], OFFSET FLAT:_ZTVSt9exception+16 mov rdi, rax call __cxa_throw mov rdi, rax dec rdx je .L3 call _Unwind_Resume .L3: call __cxa_begin_catch call __cxa_end_catch xor eax, eax pop rdx ret ``` Bluntly, this is not acceptable, since it is trivial to determine at compile time that the `throw`/`catch` pair is noop. What if the generated code is improved _only_ in this simple use case, where the `throw` and the matching `catch` are in the same stack frame? Under this condition, there is no need to invoke the ABI machinery to allocate an exception object or navigate the unwind tables; the analysis of the control flow can and should happen at compile time. We'd end up with simply ```x86asm main: xor eax, eax ret ``` Why is optimizing this simplest of use cases important? Because this leads to complete and total elimination of exception handling overhead whenever function inlining occurs; and in C++ the critical path is already heavily reliant on inlining, because the function call overhead is not insignificant even if exception handling is disabled. ### 6.3. Boost LEAF Boost LEAF[6](#reference) is a universal error handling library for C++ which works with or without exception handling. It provides a low-cost alternative to transporting error objects in return values. Using LEAF, *error handling* functions match error objects similarly to the way `catch` matches exceptions, with two important differences: * Each handler can specify multiple objects to be matched by type, rather than only one. * The error objects are matched dynamically, but solely based on their static type. This allows *all* error objects to be allocated on the stack, using automatic storage duration. Whithout exception handling, this is achieved using the following syntax: ```c++ leaf::handle_all( // The first function passed to handle_all is akin to a try-block. []() -> leaf::result { // Operations which may fail, returning a T in case of success. // If case of an error, any number of error objects of arbitrary // types can be associated with the returned result object. }, // The handler below is invoked if both an object of type my_error // and an object of another_type are associated with the error returned // by the try-block (above). [](my_error const & e1, another_type const & e2) { .... }, // This handler is invoked if an object of type my_error is associated // with the error returned by the try-block. [](my_error const & e1) { .... }, // This handler is invoked in all other cases, similarly to catch(...) [] { .... } ); ``` With exception handling: ```c++ leaf::try_catch( // The first function passed to handle_all is akin to a try-block. []() -> T { // Operations which may fail, returning a T in case of success. // If case of an error, any number of error objects of arbitrary // types can be associated with the thrown exception object. }, // The handler below is invoked if both an object of type my_error // and an object of another_type are associated with the exception // thrown by the try-block (above). [](my_error const & e1, another_type const & e2) { .... }, // This handler is invoked if an object of type my_error is associated // with the exception thrown by the try-block. [](my_error const & e1) { .... }, // This handler is invoked in all other cases, similarly to catch(...) [] { .... } ); ``` In LEAF, error objects are allocated using automatic duration, stored in a `std::tuple` in the scope of `leaf::handle_all` (or `leaf::try_catch`). The type arguments of the `std::tuple` template are automatically deduced from the types of the arguments of the error handling lambdas. If the try-block attempts to communicate error objects of any other type, these objects are discarded, since no error handler can make any use of them. The `leaf::result` template can be used as a return value for functions that may fail to produce a `T`. It carries the [*failure flag*](#1-the-semantics-of-a-failure) and, in case it is set, an integer serial number of the failure, while actual error objects are immediately moved into the matching storage reserved in the scope of an error handling function (e.g. `handle_all`) found in the call stack. ## 7. Exception-safety vs. failure-safety Many programmers dread C++ exception-safety[7](#reference): the ability of C++ programs to respond correctly to a function call that results in throwing an exception. This fear is well founded, though it shouldn't be limited to throwing exceptions, but to all error handling, regardless of the underlying mechanism. In "Exception Safety: Concepts and Techniques"[8](#reference) Bjarne Stroustrup explains: > An operation on an object is said to be exception safe if that operation leaves the object in a valid state when the operation is terminated by throwing an exception. This valid state could be an error state requiring cleanup, but it must be well defined so that reasonable error handling code can be written for the object. Consider the following edits: > An operation on an object is said to be ~~exception-safe~~ failure-safe if that operation leaves the object in a valid state when the operation ~~is terminated by throwing an exception~~ fails. This valid state could be an error state requiring cleanup, but it must be well defined so that reasonable error handling code can be written for the object. Without limiting the discussion to exception throwing, the second definition remains entirely correct. With this in mind, let's continue with Stroustrup's explanation of safety-guarantees of operations on standard library components after ~~an exception is thrown~~ a failure has occurred: > * *Basic guarantee for all operations:* The basic invariants of the standard library are maintained, and no resources, such as memory, are leaked. > > * *Strong guarantee for key operations:* In addition to providing the basic guarantee, either the operation succeeds, or has no effects. This guarantee is provided for key library operations, such as `push_back()`, single-element `insert()` on a list, and `uninitialized_copy()` > > * *~~Nothrow~~ No-fail guarantee for some operations:* In addition to providing the basic guarantee, some operations are guaranteed not to ~~throw an exception~~ fail. This guarantee is provided for a few simple operations, such as `swap()` and `pop_back()`. Does this generalization make sense? Is there a marked difference in safety-guarantees when throwing exceptions vs. any other error reporting mechanism? The answer depends on how *error neutral* functions respond to failures. For example, Boost Outcome offers the macro `OUTCOME_TRY`, which can be invoked with two arguments, like so: ```c++ OUTCOME_TRY(i, BigInt::fromString(text)); ``` The above expands to something like: ```c++ auto&& __result = BigInt::fromString(text); if (!__result) return __result.as_failure(); auto&& i = __result.value(); ``` The idea of `OUTCOME_TRY` is to support generic response to failures in *error neutral* functions. It relies on two things: 1. That the [*failure flag* can be observed generically](#1-the-semantics-of-a-failure), and 2. That it is safe to simply return from an [*error neutral* function](#2-classification-of-functions-based-on-their-affinity-to-errors) in case of a failure, forwarding error objects to the caller. Logically, this behavior is equivalent to the compiler-generated code when calling a function which may throw an exception. Consequently, all reasoning applicable to object invariants when throwing exceptions applies equally when using `OUTCOME_TRY` (or the [LEAF](https://boostorg.github.io/leaf) analog, `BOOST_LEAF_AUTO`). > **NOTE:** Lately there seems to be a debate in the C++ community whether the *basic guarantee* should be the minimum requirement for all user-defined types, that is, whether it should be required that even when operations fail, the basic object invariants are in place. Arguably this is beyond the scope of this paper, but the previous paragraph holds regardless: *safety-guarantees* are equally applicable, with or without exception handling. ## Summary * We examined several [different approaches to error handling](#4-handling-of-error-information), as well as several mechanisms for [transporting of error objects of arbitrary static types safely](#44-communicating-all-error-information-with-type-safety). * We demonstrated that [generally](#44-communicating-all-error-information-with-type-safety) it is not a good idea to [couple function signatures with the types of all error objects they need to communicate](#5-error-handling-and-function-signatures). * We presented a novel method for transporting of error objects of arbitrary static types without using dynamic memory allocation, implemented by the [Boost LEAF library](#63-boost-leaf). * We described an [alternative approach to implementing C++ exception handling](#62-c-exceptions) which would eliminate most overhead in practice. * We showed that the three formal safety guarantees (*Basic*, *Strong*, *~~Nothrow~~ No-fail*) are useful when reasoning about object invariants, [regardless of how errors are communicated](#7-exception-safety-vs-failure-safety). ## Conclusions * Error handling is a dynamic process, so the static type system is of limited assistance; for example, `ENOENT` is a *value* and not a *type*, and therefore the appropriate error handler has to be matched dynamically rather than statically. * Because most of the functions in a program are *error neutral*, the ability to automatically (e.g. when using exception handling) or at least generically (e.g. `OUTCOME_TRY`, `BOOST_LEAF_AUTO`) forward errors to the caller is critical for correctness. * The formal ~~exception-safety~~ failure-safety guarantees are applicable to *error neutral* functions responding to failures generically, even when not using exception handling. * Exception-handling overhead can be virtually eliminated by ABI changes that require no changes in the C++ standard; in the case when exception-neutral functions are inlined, all overhead may be removed even without ABI changes. ## Reference [1](#44-communicating-all-error-information-with-type-safety). Niall Douglas\ Incommensurate E types (Outcome library documentation)\ https://ned14.github.io/outcome/tutorial/advanced/interop/problem [2](#44-communicating-all-error-information-with-type-safety). Herb Sutter\ Questions About Exception Specifications (Sutter's Mill)\ https://herbsutter.com/2007/01/24/questions-about-exception-specifications [3](#621-contemporary-abis). Ben Craig\ Error speed benchmarking\ http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1886r0.html [4](#623-allocation-of-exception-objects). James Renwick, Tom Spink, Björn Franke\ Low-Cost Deterministic C++ Exceptions for Embedded Systems\ https://www.research.ed.ac.uk/portal/files/78829292/low_cost_deterministic_C_exceptions_for_embedded_systems.pdf [5](#624-we-do-not-need-a-new-language-not-even-a-new-abi-). Herb Sutter\ Zero-overhead deterministic exceptions: Throwing values\ http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r1.pdf [6](#63-leaf). Emil Dotchevski\ Lightweight Error Augmentation Framework (library documentation)\ https://boostorg.github.io/leaf [7](#7-exception-safety-vs-failure-safety). David Abrahams\ Exception-Safety in Generic Components\ https://www.boost.org/community/exception_safety.html [8](#7-exception-safety-vs-failure-safety). Bjarne Stroustrup\ Exception Safety: Concepts and Techniques\ http://www.stroustrup.com/except.pdf ================================================ FILE: doc/zajo-dark.css ================================================ /* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */ /* Uncomment @import statement below to use as custom stylesheet */ /*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/ /* Zajo's custom font import. The rest of the customizations are at the bottom of this css file, which is otherwise kept unchanged */ @import "https://fonts.googleapis.com/css?family=Anonymous+Pro|Istok+Web|Quicksand|Poiret+One"; article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block} audio,canvas,video{display:inline-block} audio:not([controls]){display:none;height:0} script{display:none!important} html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%} a{background:transparent} a:focus{outline:thin dotted} a:active,a:hover{outline:0} h1{font-size:2em;margin:.67em 0} abbr[title]{border-bottom:1px dotted} b,strong{font-weight:bold} dfn{font-style:italic} hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0} mark{background:#ff0;color:#000} code,kbd,pre,samp{font-family:monospace;font-size:1em} pre{white-space:pre-wrap} q{quotes:"\201C" "\201D" "\2018" "\2019"} small{font-size:80%} sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline} sup{top:-.5em} sub{bottom:-.25em} img{border:0} svg:not(:root){overflow:hidden} figure{margin:0} fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em} legend{border:0;padding:0} button,input,select,textarea{font-family:inherit;font-size:100%;margin:0} button,input{line-height:normal} button,select{text-transform:none} button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer} button[disabled],html input[disabled]{cursor:default} input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0} button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0} textarea{overflow:auto;vertical-align:top} table{border-collapse:collapse;border-spacing:0} *,*::before,*::after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box} html,body{font-size:100%} body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto;tab-size:4;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased} a:hover{cursor:pointer} img,object,embed{max-width:100%;height:auto} object,embed{height:100%} img{-ms-interpolation-mode:bicubic} .left{float:left!important} .right{float:right!important} .text-left{text-align:left!important} .text-right{text-align:right!important} .text-center{text-align:center!important} .text-justify{text-align:justify!important} .hide{display:none} img,object,svg{display:inline-block;vertical-align:middle} textarea{height:auto;min-height:50px} select{width:100%} .center{margin-left:auto;margin-right:auto} .stretch{width:100%} .subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em} div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr} a{color:#2156a5;text-decoration:underline;line-height:inherit} a:hover,a:focus{color:#1d4b8f} a img{border:none} p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility} p aside{font-size:.875em;line-height:1.35;font-style:italic} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em} h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0} h1{font-size:2.125em} h2{font-size:1.6875em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em} h4,h5{font-size:1.125em} h6{font-size:1em} hr{border:solid #dddddf;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0} em,i{font-style:italic;line-height:inherit} strong,b{font-weight:bold;line-height:inherit} small{font-size:60%;line-height:inherit} code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)} ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit} ul,ol{margin-left:1.5em} ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em} ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit} ul.square{list-style-type:square} ul.circle{list-style-type:circle} ul.disc{list-style-type:disc} ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0} dl dt{margin-bottom:.3125em;font-weight:bold} dl dd{margin-bottom:1.25em} abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help} abbr{text-transform:none} blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd} blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)} blockquote cite::before{content:"\2014 \0020"} blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)} blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)} @media screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2} h1{font-size:2.75em} h2{font-size:2.3125em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em} h4{font-size:1.4375em}} table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede} table thead,table tfoot{background:#f7f8f7} table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left} table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)} table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7} table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em} h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400} .clearfix::before,.clearfix::after,.float-group::before,.float-group::after{content:" ";display:table} .clearfix::after,.float-group::after{clear:both} *:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed;word-wrap:break-word} *:not(pre)>code.nobreak{word-wrap:normal} *:not(pre)>code.nowrap{white-space:nowrap} pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed} em em{font-style:normal} strong strong{font-weight:400} .keyseq{color:rgba(51,51,51,.8)} kbd{font-family:"Droid Sans Mono","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} .keyseq kbd:first-child{margin-left:0} .keyseq kbd:last-child{margin-right:0} .menuseq,.menuref{color:#000} .menuseq b:not(.caret),.menuref{font-weight:inherit} .menuseq{word-spacing:-.02em} .menuseq b.caret{font-size:1.25em;line-height:.8} .menuseq i.caret{font-weight:bold;text-align:center;width:.45em} b.button::before,b.button::after{position:relative;top:-1px;font-weight:400} b.button::before{content:"[";padding:0 3px 0 2px} b.button::after{content:"]";padding:0 2px 0 3px} p a>code:hover{color:rgba(0,0,0,.9)} #header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em} #header::before,#header::after,#content::before,#content::after,#footnotes::before,#footnotes::after,#footer::before,#footer::after{content:" ";display:table} #header::after,#content::after,#footnotes::after,#footer::after{clear:both} #content{margin-top:1.25em} #content::before{content:none} #header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0} #header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #dddddf} #header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #dddddf;padding-bottom:8px} #header .details{border-bottom:1px solid #dddddf;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap} #header .details span:first-child{margin-left:-.125em} #header .details span.email a{color:rgba(0,0,0,.85)} #header .details br{display:none} #header .details br+span::before{content:"\00a0\2013\00a0"} #header .details br+span.author::before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)} #header .details br+span#revremark::before{content:"\00a0|\00a0"} #header #revnumber{text-transform:capitalize} #header #revnumber::after{content:"\00a0"} #content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #dddddf;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem} #toc{border-bottom:1px solid #e7e7e9;padding-bottom:.5em} #toc>ul{margin-left:.125em} #toc ul.sectlevel0>li>a{font-style:italic} #toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0} #toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none} #toc li{line-height:1.3334;margin-top:.3334em} #toc a{text-decoration:none} #toc a:active{text-decoration:underline} #toctitle{color:#7a2518;font-size:1.2em} @media screen and (min-width:768px){#toctitle{font-size:1.375em} body.toc2{padding-left:15em;padding-right:0} #toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #e7e7e9;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto} #toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em} #toc.toc2>ul{font-size:.9em;margin-bottom:0} #toc.toc2 ul ul{margin-left:0;padding-left:1em} #toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em} body.toc2.toc-right{padding-left:0;padding-right:15em} body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #e7e7e9;left:auto;right:0}} @media screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0} #toc.toc2{width:20em} #toc.toc2 #toctitle{font-size:1.375em} #toc.toc2>ul{font-size:.95em} #toc.toc2 ul ul{padding-left:1.25em} body.toc2.toc-right{padding-left:0;padding-right:20em}} #content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} #content #toc>:first-child{margin-top:0} #content #toc>:last-child{margin-bottom:0} #footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em} #footer-text{color:rgba(255,255,255,.8);line-height:1.44} #content{margin-bottom:.625em} .sect1{padding-bottom:.625em} @media screen and (min-width:768px){#content{margin-bottom:1.25em} .sect1{padding-bottom:1.25em}} .sect1:last-child{padding-bottom:0} .sect1+.sect1{border-top:1px solid #e7e7e9} #content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400} #content h1>a.anchor::before,h2>a.anchor::before,h3>a.anchor::before,#toctitle>a.anchor::before,.sidebarblock>.content>.title>a.anchor::before,h4>a.anchor::before,h5>a.anchor::before,h6>a.anchor::before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em} #content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible} #content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none} #content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221} .audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em} .admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic} table.tableblock.fit-content>caption.title{white-space:nowrap;width:0} .paragraph.lead>p,#preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:1.21875em;line-height:1.6;color:rgba(0,0,0,.85)} table.tableblock #preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:inherit} .admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%} .admonitionblock>table td.icon{text-align:center;width:80px} .admonitionblock>table td.icon img{max-width:none} .admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase} .admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddf;color:rgba(0,0,0,.6)} .admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0} .exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px} .exampleblock>.content>:first-child{margin-top:0} .exampleblock>.content>:last-child{margin-bottom:0} .sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} .sidebarblock>:first-child{margin-top:0} .sidebarblock>:last-child{margin-bottom:0} .sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center} .exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0} .literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8} .sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1} .literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;overflow-x:auto;padding:1em;font-size:.8125em} @media screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}} @media screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}} .literalblock pre.nowrap,.literalblock pre.nowrap pre,.listingblock pre.nowrap,.listingblock pre.nowrap pre{white-space:pre;word-wrap:normal} .literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)} .listingblock pre.highlightjs{padding:0} .listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px} .listingblock pre.prettyprint{border-width:0} .listingblock>.content{position:relative} .listingblock code[data-lang]::before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999} .listingblock:hover code[data-lang]::before{display:block} .listingblock.terminal pre .command::before{content:attr(data-prompt);padding-right:.5em;color:#999} .listingblock.terminal pre .command:not([data-prompt])::before{content:"$"} table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none} table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45} table.pyhltable td.code{padding-left:.75em;padding-right:0} pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #dddddf} pre.pygments .lineno{display:inline-block;margin-right:.25em} table.pyhltable .linenodiv{background:none!important;padding-right:0!important} .quoteblock{margin:0 1em 1.25em 1.5em;display:table} .quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em} .quoteblock blockquote,.quoteblock p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify} .quoteblock blockquote{margin:0;padding:0;border:0} .quoteblock blockquote::before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)} .quoteblock blockquote>.paragraph:last-child p{margin-bottom:0} .quoteblock .attribution{margin-top:.75em;margin-right:.5ex;text-align:right} .verseblock{margin:0 1em 1.25em} .verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility} .verseblock pre strong{font-weight:400} .verseblock .attribution{margin-top:1.25rem;margin-left:.5ex} .quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic} .quoteblock .attribution br,.verseblock .attribution br{display:none} .quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)} .quoteblock.abstract blockquote::before,.quoteblock.excerpt blockquote::before,.quoteblock .quoteblock blockquote::before{display:none} .quoteblock.abstract blockquote,.quoteblock.abstract p,.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{line-height:1.6;word-spacing:0} .quoteblock.abstract{margin:0 1em 1.25em;display:block} .quoteblock.abstract>.title{margin:0 0 .375em;font-size:1.15em;text-align:center} .quoteblock.excerpt,.quoteblock .quoteblock{margin:0 0 1.25em;padding:0 0 .25em 1em;border-left:.25em solid #dddddf} .quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{color:inherit;font-size:1.0625rem} .quoteblock.excerpt .attribution,.quoteblock .quoteblock .attribution{color:inherit;text-align:left;margin-right:0} table.tableblock{max-width:100%;border-collapse:separate} p.tableblock:last-child{margin-bottom:0} td.tableblock>.content{margin-bottom:-1.25em} table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede} table.grid-all>thead>tr>.tableblock,table.grid-all>tbody>tr>.tableblock{border-width:0 1px 1px 0} table.grid-all>tfoot>tr>.tableblock{border-width:1px 1px 0 0} table.grid-cols>*>tr>.tableblock{border-width:0 1px 0 0} table.grid-rows>thead>tr>.tableblock,table.grid-rows>tbody>tr>.tableblock{border-width:0 0 1px} table.grid-rows>tfoot>tr>.tableblock{border-width:1px 0 0} table.grid-all>*>tr>.tableblock:last-child,table.grid-cols>*>tr>.tableblock:last-child{border-right-width:0} table.grid-all>tbody>tr:last-child>.tableblock,table.grid-all>thead:last-child>tr>.tableblock,table.grid-rows>tbody>tr:last-child>.tableblock,table.grid-rows>thead:last-child>tr>.tableblock{border-bottom-width:0} table.frame-all{border-width:1px} table.frame-sides{border-width:0 1px} table.frame-topbot,table.frame-ends{border-width:1px 0} table.stripes-all tr,table.stripes-odd tr:nth-of-type(odd){background:#f8f8f7} table.stripes-none tr,table.stripes-odd tr:nth-of-type(even){background:none} th.halign-left,td.halign-left{text-align:left} th.halign-right,td.halign-right{text-align:right} th.halign-center,td.halign-center{text-align:center} th.valign-top,td.valign-top{vertical-align:top} th.valign-bottom,td.valign-bottom{vertical-align:bottom} th.valign-middle,td.valign-middle{vertical-align:middle} table thead th,table tfoot th{font-weight:bold} tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7} tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold} p.tableblock>code:only-child{background:none;padding:0} p.tableblock{font-size:1em} td>div.verse{white-space:pre} ol{margin-left:1.75em} ul li ol{margin-left:1.5em} dl dd{margin-left:1.125em} dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0} ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em} ul.checklist,ul.none,ol.none,ul.no-bullet,ol.no-bullet,ol.unnumbered,ul.unstyled,ol.unstyled{list-style-type:none} ul.no-bullet,ol.no-bullet,ol.unnumbered{margin-left:.625em} ul.unstyled,ol.unstyled{margin-left:0} ul.checklist{margin-left:.625em} ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1.25em;font-size:.8em;position:relative;bottom:.125em} ul.checklist li>p:first-child>input[type="checkbox"]:first-child{margin-right:.25em} ul.inline{display:-ms-flexbox;display:-webkit-box;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap;list-style:none;margin:0 0 .625em -1.25em} ul.inline>li{margin-left:1.25em} .unstyled dl dt{font-weight:400;font-style:normal} ol.arabic{list-style-type:decimal} ol.decimal{list-style-type:decimal-leading-zero} ol.loweralpha{list-style-type:lower-alpha} ol.upperalpha{list-style-type:upper-alpha} ol.lowerroman{list-style-type:lower-roman} ol.upperroman{list-style-type:upper-roman} ol.lowergreek{list-style-type:lower-greek} .hdlist>table,.colist>table{border:0;background:none} .hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none} td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em} td.hdlist1{font-weight:bold;padding-bottom:1.25em} .literalblock+.colist,.listingblock+.colist{margin-top:-.5em} .colist td:not([class]):first-child{padding:.4em .75em 0;line-height:1;vertical-align:top} .colist td:not([class]):first-child img{max-width:none} .colist td:not([class]):last-child{padding:.25em 0} .thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd} .imageblock.left{margin:.25em .625em 1.25em 0} .imageblock.right{margin:.25em 0 1.25em .625em} .imageblock>.title{margin-bottom:0} .imageblock.thumb,.imageblock.th{border-width:6px} .imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em} .image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0} .image.left{margin-right:.625em} .image.right{margin-left:.625em} a.image{text-decoration:none;display:inline-block} a.image object{pointer-events:none} sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super} sup.footnote a,sup.footnoteref a{text-decoration:none} sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline} #footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em} #footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em;border-width:1px 0 0} #footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;margin-bottom:.2em} #footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;margin-left:-1.05em} #footnotes .footnote:last-of-type{margin-bottom:0} #content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0} .gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0} .gist .file-data>table td.line-data{width:99%} div.unbreakable{page-break-inside:avoid} .big{font-size:larger} .small{font-size:smaller} .underline{text-decoration:underline} .overline{text-decoration:overline} .line-through{text-decoration:line-through} .aqua{color:#00bfbf} .aqua-background{background-color:#00fafa} .black{color:#000} .black-background{background-color:#000} .blue{color:#0000bf} .blue-background{background-color:#0000fa} .fuchsia{color:#bf00bf} .fuchsia-background{background-color:#fa00fa} .gray{color:#606060} .gray-background{background-color:#7d7d7d} .green{color:#006000} .green-background{background-color:#007d00} .lime{color:#00bf00} .lime-background{background-color:#00fa00} .maroon{color:#600000} .maroon-background{background-color:#7d0000} .navy{color:#000060} .navy-background{background-color:#00007d} .olive{color:#606000} .olive-background{background-color:#7d7d00} .purple{color:#600060} .purple-background{background-color:#7d007d} .red{color:#bf0000} .red-background{background-color:#fa0000} .silver{color:#909090} .silver-background{background-color:#bcbcbc} .teal{color:#006060} .teal-background{background-color:#007d7d} .white{color:#bfbfbf} .white-background{background-color:#fafafa} .yellow{color:#bfbf00} .yellow-background{background-color:#fafa00} span.icon>.fa{cursor:default} a span.icon>.fa{cursor:inherit} .admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default} .admonitionblock td.icon .icon-note::before{content:"\f05a";color:#19407c} .admonitionblock td.icon .icon-tip::before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111} .admonitionblock td.icon .icon-warning::before{content:"\f071";color:#bf6900} .admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#bf3400} .admonitionblock td.icon .icon-important::before{content:"\f06a";color:#bf0000} .conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold} .conum[data-value] *{color:#fff!important} .conum[data-value]+b{display:none} .conum[data-value]::after{content:attr(data-value)} pre .conum[data-value]{position:relative;top:-.125em} b.conum *{color:inherit!important} .conum:not([data-value]):empty{display:none} dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility} h1,h2,p,td.content,span.alt{letter-spacing:-.01em} p strong,td.content strong,div.footnote strong{letter-spacing:-.005em} p,blockquote,dt,td.content,span.alt{font-size:1.0625rem} p{margin-bottom:1.25rem} .sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em} .exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc} .print-only{display:none!important} @page{margin:1.25cm .75cm} @media print{*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important} html{font-size:80%} a{color:inherit!important;text-decoration:underline!important} a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important} a[href^="http:"]:not(.bare)::after,a[href^="https:"]:not(.bare)::after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em} abbr[title]::after{content:" (" attr(title) ")"} pre,blockquote,tr,img,object,svg{page-break-inside:avoid} thead{display:table-header-group} svg{max-width:100%} p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3} h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid} #toc,.sidebarblock,.exampleblock>.content{background:none!important} #toc{border-bottom:1px solid #dddddf!important;padding-bottom:0!important} body.book #header{text-align:center} body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em} body.book #header .details{border:0!important;display:block;padding:0!important} body.book #header .details span:first-child{margin-left:0!important} body.book #header .details br{display:block} body.book #header .details br+span::before{content:none!important} body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important} body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always} .listingblock code[data-lang]::before{display:block} #footer{padding:0 .9375em} .hide-on-print{display:none!important} .print-only{display:block!important} .hide-for-print{display:none!important} .show-for-print{display:inherit!important}} @media print,amzn-kf8{#header>h1:first-child{margin-top:1.25rem} .sect1{padding:0!important} .sect1+.sect1{border:0} #footer{background:none} #footer-text{color:rgba(0,0,0,.6);font-size:.9em}} @media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}} /* Zajo's customizations applied on top of the standard asciidoctor css above */ h1{font-size:4em} h2{font-size:1.74em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.5em} h4{font-size:1.2em} h5{font-size:1em} h6{font-size:1em} #toc {text-align:left} #toc ul code{font-size:111%} #toc a:hover code {color:#00cc99} a:focus{outline:0} .colist td{color:rgba(255,255,255,.67)} body{text-align:left; background:#202020;color:rgba(255,255,255,.67);padding:0;margin:0;font-family:"Istok Web","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto;tab-size:4;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased} .subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#a0a0a0;font-weight:400;margin-top:0;margin-bottom:.25em} .literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#101010} table{background:#202020;margin-bottom:1.25em;border:solid 1px #dedede} table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(255,255,255,.67)} table tr.even,table tr.alt,table tr:nth-of-type(even){background:#202020} table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{color:rgba(255,255,255,.67)} th{background-color:#404040} a{color:#FFFFFF;text-decoration:underline;line-height:inherit} 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} 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} h1 code{color:#00cc99; font-size:113%} h2 code{color:#00cc99; font-size:113%} h3 code{color:#00cc99; font-size:113%} h4 code{color:#00cc99; font-size:113%} h5 code{color:#00cc99; font-size:113%} #header>h1:first-child{font-family:"Poiret One";color:#00cc99;margin-top:2.25rem;margin-bottom:0;letter-spacing:-.07em} #author{color:#a366ff} #toc ul{font-family:"Quicksand","DejaVu Sans",sans-serif;list-style-type:none} #toc a:hover{color:#00cc99} #toc.toc2{background-color:#404040} .admonitionblock td.icon .icon-note::before{content:"\f05a";color:#00cc99} .admonitionblock td.icon .icon-tip::before{content:"\f0eb";color:#00cc99;text-shadow:none} .admonitionblock td.icon .icon-warning::before{content:"\f071";color:#a366ff} .admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#a366ff} .admonitionblock td.icon .icon-important::before{content:"\f06a";color:#a366ff} .admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddf;color:rgba(255,255,255,.67)} .conum[data-value]{display:inline-block;color:black!important;background-color:#d9d9d9;-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold} .exampleblock>.content{background-color:#404040;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc} .quoteblock {background-color:#404040} .quoteblock blockquote,.quoteblock p{color:rgba(255,255,255,.67);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify;background-color:#404040} .quoteblock blockquote::before{margin-left:-.8em;color:#00cc99} .quoteblock blockquote{font-family:"Istok Web","DejaVu Serif"; font-size:1.0625rem; padding:0.5em} .quoteblock .attribution{padding-top:.75ex;margin-top:0;margin-right:0;padding-right:.5ex;text-align:right;background-color:#202020} .text-right{margin-top:-1em} ================================================ FILE: doc/zajo-light.css ================================================ /* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */ /* Uncomment @import statement below to use as custom stylesheet */ /*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/ /* Zajo's custom font import. The rest of the customizations are at the bottom of this css file, which is otherwise kept unchanged */ @import "https://fonts.googleapis.com/css?family=Anonymous+Pro|Istok+Web|Quicksand|Poiret+One"; article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block} audio,canvas,video{display:inline-block} audio:not([controls]){display:none;height:0} script{display:none!important} html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%} a{background:transparent} a:focus{outline:thin dotted} a:active,a:hover{outline:0} h1{font-size:2em;margin:.67em 0} abbr[title]{border-bottom:1px dotted} b,strong{font-weight:bold} dfn{font-style:italic} hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0} mark{background:#ff0;color:#000} code,kbd,pre,samp{font-family:monospace;font-size:1em} pre{white-space:pre-wrap} q{quotes:"\201C" "\201D" "\2018" "\2019"} small{font-size:80%} sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline} sup{top:-.5em} sub{bottom:-.25em} img{border:0} svg:not(:root){overflow:hidden} figure{margin:0} fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em} legend{border:0;padding:0} button,input,select,textarea{font-family:inherit;font-size:100%;margin:0} button,input{line-height:normal} button,select{text-transform:none} button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer} button[disabled],html input[disabled]{cursor:default} input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0} button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0} textarea{overflow:auto;vertical-align:top} table{border-collapse:collapse;border-spacing:0} *,*::before,*::after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box} html,body{font-size:100%} body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto;tab-size:4;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased} a:hover{cursor:pointer} img,object,embed{max-width:100%;height:auto} object,embed{height:100%} img{-ms-interpolation-mode:bicubic} .left{float:left!important} .right{float:right!important} .text-left{text-align:left!important} .text-right{text-align:right!important} .text-center{text-align:center!important} .text-justify{text-align:justify!important} .hide{display:none} img,object,svg{display:inline-block;vertical-align:middle} textarea{height:auto;min-height:50px} select{width:100%} .center{margin-left:auto;margin-right:auto} .stretch{width:100%} .subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em} div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr} a{color:#2156a5;text-decoration:underline;line-height:inherit} a:hover,a:focus{color:#1d4b8f} a img{border:none} p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility} p aside{font-size:.875em;line-height:1.35;font-style:italic} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em} h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0} h1{font-size:2.125em} h2{font-size:1.6875em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em} h4,h5{font-size:1.125em} h6{font-size:1em} hr{border:solid #dddddf;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0} em,i{font-style:italic;line-height:inherit} strong,b{font-weight:bold;line-height:inherit} small{font-size:60%;line-height:inherit} code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)} ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit} ul,ol{margin-left:1.5em} ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em} ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit} ul.square{list-style-type:square} ul.circle{list-style-type:circle} ul.disc{list-style-type:disc} ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0} dl dt{margin-bottom:.3125em;font-weight:bold} dl dd{margin-bottom:1.25em} abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help} abbr{text-transform:none} blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd} blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)} blockquote cite::before{content:"\2014 \0020"} blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)} blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)} @media screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2} h1{font-size:2.75em} h2{font-size:2.3125em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em} h4{font-size:1.4375em}} table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede} table thead,table tfoot{background:#f7f8f7} table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left} table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)} table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7} table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em} h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400} .clearfix::before,.clearfix::after,.float-group::before,.float-group::after{content:" ";display:table} .clearfix::after,.float-group::after{clear:both} *:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed;word-wrap:break-word} *:not(pre)>code.nobreak{word-wrap:normal} *:not(pre)>code.nowrap{white-space:nowrap} pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed} em em{font-style:normal} strong strong{font-weight:400} .keyseq{color:rgba(51,51,51,.8)} kbd{font-family:"Droid Sans Mono","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} .keyseq kbd:first-child{margin-left:0} .keyseq kbd:last-child{margin-right:0} .menuseq,.menuref{color:#000} .menuseq b:not(.caret),.menuref{font-weight:inherit} .menuseq{word-spacing:-.02em} .menuseq b.caret{font-size:1.25em;line-height:.8} .menuseq i.caret{font-weight:bold;text-align:center;width:.45em} b.button::before,b.button::after{position:relative;top:-1px;font-weight:400} b.button::before{content:"[";padding:0 3px 0 2px} b.button::after{content:"]";padding:0 2px 0 3px} p a>code:hover{color:rgba(0,0,0,.9)} #header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em} #header::before,#header::after,#content::before,#content::after,#footnotes::before,#footnotes::after,#footer::before,#footer::after{content:" ";display:table} #header::after,#content::after,#footnotes::after,#footer::after{clear:both} #content{margin-top:1.25em} #content::before{content:none} #header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0} #header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #dddddf} #header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #dddddf;padding-bottom:8px} #header .details{border-bottom:1px solid #dddddf;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap} #header .details span:first-child{margin-left:-.125em} #header .details span.email a{color:rgba(0,0,0,.85)} #header .details br{display:none} #header .details br+span::before{content:"\00a0\2013\00a0"} #header .details br+span.author::before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)} #header .details br+span#revremark::before{content:"\00a0|\00a0"} #header #revnumber{text-transform:capitalize} #header #revnumber::after{content:"\00a0"} #content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #dddddf;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem} #toc{border-bottom:1px solid #e7e7e9;padding-bottom:.5em} #toc>ul{margin-left:.125em} #toc ul.sectlevel0>li>a{font-style:italic} #toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0} #toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none} #toc li{line-height:1.3334;margin-top:.3334em} #toc a{text-decoration:none} #toc a:active{text-decoration:underline} #toctitle{color:#7a2518;font-size:1.2em} @media screen and (min-width:768px){#toctitle{font-size:1.375em} body.toc2{padding-left:15em;padding-right:0} #toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #e7e7e9;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto} #toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em} #toc.toc2>ul{font-size:.9em;margin-bottom:0} #toc.toc2 ul ul{margin-left:0;padding-left:1em} #toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em} body.toc2.toc-right{padding-left:0;padding-right:15em} body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #e7e7e9;left:auto;right:0}} @media screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0} #toc.toc2{width:20em} #toc.toc2 #toctitle{font-size:1.375em} #toc.toc2>ul{font-size:.95em} #toc.toc2 ul ul{padding-left:1.25em} body.toc2.toc-right{padding-left:0;padding-right:20em}} #content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} #content #toc>:first-child{margin-top:0} #content #toc>:last-child{margin-bottom:0} #footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em} #footer-text{color:rgba(255,255,255,.8);line-height:1.44} #content{margin-bottom:.625em} .sect1{padding-bottom:.625em} @media screen and (min-width:768px){#content{margin-bottom:1.25em} .sect1{padding-bottom:1.25em}} .sect1:last-child{padding-bottom:0} .sect1+.sect1{border-top:1px solid #e7e7e9} #content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400} #content h1>a.anchor::before,h2>a.anchor::before,h3>a.anchor::before,#toctitle>a.anchor::before,.sidebarblock>.content>.title>a.anchor::before,h4>a.anchor::before,h5>a.anchor::before,h6>a.anchor::before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em} #content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible} #content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none} #content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221} .audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em} .admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic} table.tableblock.fit-content>caption.title{white-space:nowrap;width:0} .paragraph.lead>p,#preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:1.21875em;line-height:1.6;color:rgba(0,0,0,.85)} table.tableblock #preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:inherit} .admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%} .admonitionblock>table td.icon{text-align:center;width:80px} .admonitionblock>table td.icon img{max-width:none} .admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase} .admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddf;color:rgba(0,0,0,.6)} .admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0} .exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px} .exampleblock>.content>:first-child{margin-top:0} .exampleblock>.content>:last-child{margin-bottom:0} .sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} .sidebarblock>:first-child{margin-top:0} .sidebarblock>:last-child{margin-bottom:0} .sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center} .exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0} .literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8} .sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1} .literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;overflow-x:auto;padding:1em;font-size:.8125em} @media screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}} @media screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}} .literalblock pre.nowrap,.literalblock pre.nowrap pre,.listingblock pre.nowrap,.listingblock pre.nowrap pre{white-space:pre;word-wrap:normal} .literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)} .listingblock pre.highlightjs{padding:0} .listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px} .listingblock pre.prettyprint{border-width:0} .listingblock>.content{position:relative} .listingblock code[data-lang]::before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999} .listingblock:hover code[data-lang]::before{display:block} .listingblock.terminal pre .command::before{content:attr(data-prompt);padding-right:.5em;color:#999} .listingblock.terminal pre .command:not([data-prompt])::before{content:"$"} table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none} table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45} table.pyhltable td.code{padding-left:.75em;padding-right:0} pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #dddddf} pre.pygments .lineno{display:inline-block;margin-right:.25em} table.pyhltable .linenodiv{background:none!important;padding-right:0!important} .quoteblock{margin:0 1em 1.25em 1.5em;display:table} .quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em} .quoteblock blockquote,.quoteblock p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify} .quoteblock blockquote{margin:0;padding:0;border:0} .quoteblock blockquote::before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)} .quoteblock blockquote>.paragraph:last-child p{margin-bottom:0} .quoteblock .attribution{margin-top:.75em;margin-right:.5ex;text-align:right} .verseblock{margin:0 1em 1.25em} .verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility} .verseblock pre strong{font-weight:400} .verseblock .attribution{margin-top:1.25rem;margin-left:.5ex} .quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic} .quoteblock .attribution br,.verseblock .attribution br{display:none} .quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)} .quoteblock.abstract blockquote::before,.quoteblock.excerpt blockquote::before,.quoteblock .quoteblock blockquote::before{display:none} .quoteblock.abstract blockquote,.quoteblock.abstract p,.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{line-height:1.6;word-spacing:0} .quoteblock.abstract{margin:0 1em 1.25em;display:block} .quoteblock.abstract>.title{margin:0 0 .375em;font-size:1.15em;text-align:center} .quoteblock.excerpt,.quoteblock .quoteblock{margin:0 0 1.25em;padding:0 0 .25em 1em;border-left:.25em solid #dddddf} .quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{color:inherit;font-size:1.0625rem} .quoteblock.excerpt .attribution,.quoteblock .quoteblock .attribution{color:inherit;text-align:left;margin-right:0} table.tableblock{max-width:100%;border-collapse:separate} p.tableblock:last-child{margin-bottom:0} td.tableblock>.content{margin-bottom:-1.25em} table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede} table.grid-all>thead>tr>.tableblock,table.grid-all>tbody>tr>.tableblock{border-width:0 1px 1px 0} table.grid-all>tfoot>tr>.tableblock{border-width:1px 1px 0 0} table.grid-cols>*>tr>.tableblock{border-width:0 1px 0 0} table.grid-rows>thead>tr>.tableblock,table.grid-rows>tbody>tr>.tableblock{border-width:0 0 1px} table.grid-rows>tfoot>tr>.tableblock{border-width:1px 0 0} table.grid-all>*>tr>.tableblock:last-child,table.grid-cols>*>tr>.tableblock:last-child{border-right-width:0} table.grid-all>tbody>tr:last-child>.tableblock,table.grid-all>thead:last-child>tr>.tableblock,table.grid-rows>tbody>tr:last-child>.tableblock,table.grid-rows>thead:last-child>tr>.tableblock{border-bottom-width:0} table.frame-all{border-width:1px} table.frame-sides{border-width:0 1px} table.frame-topbot,table.frame-ends{border-width:1px 0} table.stripes-all tr,table.stripes-odd tr:nth-of-type(odd){background:#f8f8f7} table.stripes-none tr,table.stripes-odd tr:nth-of-type(even){background:none} th.halign-left,td.halign-left{text-align:left} th.halign-right,td.halign-right{text-align:right} th.halign-center,td.halign-center{text-align:center} th.valign-top,td.valign-top{vertical-align:top} th.valign-bottom,td.valign-bottom{vertical-align:bottom} th.valign-middle,td.valign-middle{vertical-align:middle} table thead th,table tfoot th{font-weight:bold} tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7} tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold} p.tableblock>code:only-child{background:none;padding:0} p.tableblock{font-size:1em} td>div.verse{white-space:pre} ol{margin-left:1.75em} ul li ol{margin-left:1.5em} dl dd{margin-left:1.125em} dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0} ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em} ul.checklist,ul.none,ol.none,ul.no-bullet,ol.no-bullet,ol.unnumbered,ul.unstyled,ol.unstyled{list-style-type:none} ul.no-bullet,ol.no-bullet,ol.unnumbered{margin-left:.625em} ul.unstyled,ol.unstyled{margin-left:0} ul.checklist{margin-left:.625em} ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1.25em;font-size:.8em;position:relative;bottom:.125em} ul.checklist li>p:first-child>input[type="checkbox"]:first-child{margin-right:.25em} ul.inline{display:-ms-flexbox;display:-webkit-box;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap;list-style:none;margin:0 0 .625em -1.25em} ul.inline>li{margin-left:1.25em} .unstyled dl dt{font-weight:400;font-style:normal} ol.arabic{list-style-type:decimal} ol.decimal{list-style-type:decimal-leading-zero} ol.loweralpha{list-style-type:lower-alpha} ol.upperalpha{list-style-type:upper-alpha} ol.lowerroman{list-style-type:lower-roman} ol.upperroman{list-style-type:upper-roman} ol.lowergreek{list-style-type:lower-greek} .hdlist>table,.colist>table{border:0;background:none} .hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none} td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em} td.hdlist1{font-weight:bold;padding-bottom:1.25em} .literalblock+.colist,.listingblock+.colist{margin-top:-.5em} .colist td:not([class]):first-child{padding:.4em .75em 0;line-height:1;vertical-align:top} .colist td:not([class]):first-child img{max-width:none} .colist td:not([class]):last-child{padding:.25em 0} .thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd} .imageblock.left{margin:.25em .625em 1.25em 0} .imageblock.right{margin:.25em 0 1.25em .625em} .imageblock>.title{margin-bottom:0} .imageblock.thumb,.imageblock.th{border-width:6px} .imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em} .image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0} .image.left{margin-right:.625em} .image.right{margin-left:.625em} a.image{text-decoration:none;display:inline-block} a.image object{pointer-events:none} sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super} sup.footnote a,sup.footnoteref a{text-decoration:none} sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline} #footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em} #footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em;border-width:1px 0 0} #footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;margin-bottom:.2em} #footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;margin-left:-1.05em} #footnotes .footnote:last-of-type{margin-bottom:0} #content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0} .gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0} .gist .file-data>table td.line-data{width:99%} div.unbreakable{page-break-inside:avoid} .big{font-size:larger} .small{font-size:smaller} .underline{text-decoration:underline} .overline{text-decoration:overline} .line-through{text-decoration:line-through} .aqua{color:#00bfbf} .aqua-background{background-color:#00fafa} .black{color:#000} .black-background{background-color:#000} .blue{color:#0000bf} .blue-background{background-color:#0000fa} .fuchsia{color:#bf00bf} .fuchsia-background{background-color:#fa00fa} .gray{color:#606060} .gray-background{background-color:#7d7d7d} .green{color:#006000} .green-background{background-color:#007d00} .lime{color:#00bf00} .lime-background{background-color:#00fa00} .maroon{color:#600000} .maroon-background{background-color:#7d0000} .navy{color:#000060} .navy-background{background-color:#00007d} .olive{color:#606000} .olive-background{background-color:#7d7d00} .purple{color:#600060} .purple-background{background-color:#7d007d} .red{color:#bf0000} .red-background{background-color:#fa0000} .silver{color:#909090} .silver-background{background-color:#bcbcbc} .teal{color:#006060} .teal-background{background-color:#007d7d} .white{color:#bfbfbf} .white-background{background-color:#fafafa} .yellow{color:#bfbf00} .yellow-background{background-color:#fafa00} span.icon>.fa{cursor:default} a span.icon>.fa{cursor:inherit} .admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default} .admonitionblock td.icon .icon-note::before{content:"\f05a";color:#19407c} .admonitionblock td.icon .icon-tip::before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111} .admonitionblock td.icon .icon-warning::before{content:"\f071";color:#bf6900} .admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#bf3400} .admonitionblock td.icon .icon-important::before{content:"\f06a";color:#bf0000} .conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold} .conum[data-value] *{color:#fff!important} .conum[data-value]+b{display:none} .conum[data-value]::after{content:attr(data-value)} pre .conum[data-value]{position:relative;top:-.125em} b.conum *{color:inherit!important} .conum:not([data-value]):empty{display:none} dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility} h1,h2,p,td.content,span.alt{letter-spacing:-.01em} p strong,td.content strong,div.footnote strong{letter-spacing:-.005em} p,blockquote,dt,td.content,span.alt{font-size:1.0625rem} p{margin-bottom:1.25rem} .sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em} .exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc} .print-only{display:none!important} @page{margin:1.25cm .75cm} @media print{*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important} html{font-size:80%} a{color:inherit!important;text-decoration:underline!important} a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important} a[href^="http:"]:not(.bare)::after,a[href^="https:"]:not(.bare)::after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em} abbr[title]::after{content:" (" attr(title) ")"} pre,blockquote,tr,img,object,svg{page-break-inside:avoid} thead{display:table-header-group} svg{max-width:100%} p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3} h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid} #toc,.sidebarblock,.exampleblock>.content{background:none!important} #toc{border-bottom:1px solid #dddddf!important;padding-bottom:0!important} body.book #header{text-align:center} body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em} body.book #header .details{border:0!important;display:block;padding:0!important} body.book #header .details span:first-child{margin-left:0!important} body.book #header .details br{display:block} body.book #header .details br+span::before{content:none!important} body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important} body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always} .listingblock code[data-lang]::before{display:block} #footer{padding:0 .9375em} .hide-on-print{display:none!important} .print-only{display:block!important} .hide-for-print{display:none!important} .show-for-print{display:inherit!important}} @media print,amzn-kf8{#header>h1:first-child{margin-top:1.25rem} .sect1{padding:0!important} .sect1+.sect1{border:0} #footer{background:none} #footer-text{color:rgba(0,0,0,.6);font-size:.9em}} @media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}} /* Zajo's customizations applied on top of the standard asciidoctor css above */ h1{font-size:4em} h2{font-size:1.74em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.5em} h4{font-size:1.2em} h5{font-size:1em} h6{font-size:1em} #toc {text-align:left} #toc ul code{font-size:111%} #toc a:hover code {color:#4101a7} a:focus{outline:0} .colist td{color:rgba(0,0,0,.67)} body{text-align:left; background:#fff;color:rgba(0,0,0,.67);padding:0;margin:0;font-family:"Istok Web","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto;tab-size:4;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased} .subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#a0a0a0;font-weight:400;margin-top:0;margin-bottom:.25em} a{color:#000000;text-decoration:underline;line-height:inherit} 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} 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} h1 code{color:#4101a7; font-size:113%} h2 code{color:#4101a7; font-size:113%} h3 code{color:#4101a7; font-size:113%} h4 code{color:#4101a7; font-size:113%} h5 code{color:#4101a7; font-size:113%} #header>h1:first-child{font-family:"Poiret One";color:#ff5100;margin-top:2.25rem;margin-bottom:0;letter-spacing:-.07em} #author{color: #4101a7;} #toc ul{font-family:"Quicksand","DejaVu Sans",sans-serif;list-style-type:none} #toc a:hover{color:#4101a7} #toc.toc2{background-color:#f7f8f7} .admonitionblock td.icon .icon-note::before{content:"\f05a";color:#606060} .admonitionblock td.icon .icon-tip::before{content:"\f0eb";color:#606060;text-shadow:none} .admonitionblock td.icon .icon-warning::before{content:"\f071";color:#ff5100} .admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#ff5100} .admonitionblock td.icon .icon-important::before{content:"\f06a";color:#ff5100} .conum[data-value]{display:inline-block;color:#fff!important;background-color:#606060;-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold} .exampleblock>.content{background-color:#ffffff;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc} .quoteblock blockquote::before{margin-left:-.8em;color:#4101a7} .quoteblock blockquote{font-family:"Istok Web","DejaVu Serif"; font-size:1.0625rem; padding:0.5em} .text-right{margin-top:-1em} ================================================ FILE: example/asio_beast_leaf_rpc.cpp ================================================ // 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. leaf::throw_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); } ================================================ FILE: example/capture_in_exception.cpp ================================================ // 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) // This is a simple program that demonstrates the use of LEAF to transport error // objects between threads, using exception handling. See capture_in_result.cpp // for the version that does not use exception handling. #include #include #include #include #include #include #include #include namespace leaf = boost::leaf; // Define several error types. struct e_thread_id { std::thread::id value; }; struct e_failure_info1 { std::string value; }; struct e_failure_info2 { int value; }; // A type that represents a successfully returned result from a task. struct task_result { }; // This is our task function. It produces objects of type task_result, but it // may fail. task_result task() { bool succeed = (rand()%4) != 0; //...at random. if( succeed ) return { }; else leaf::throw_exception( e_thread_id{std::this_thread::get_id()}, e_failure_info1{"info"}, e_failure_info2{42} ); }; 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; // 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. std::generate_n( std::back_inserter(fut), task_count, [&] { return std::async( std::launch::async, [&] { return leaf::capture(leaf::make_shared_context(error_handlers), &task); } ); } ); // Wait on the futures, get the task results, handle errors. for( auto & f : fut ) { f.wait(); leaf::try_catch( [&] { task_result 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. }, error_handlers ); } } ================================================ FILE: example/capture_in_result.cpp ================================================ // 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) // 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 // for the version that uses exception handling. #include #include #include #include #include #include #include #include namespace leaf = boost::leaf; // Define several error types. struct e_thread_id { std::thread::id value; }; struct e_failure_info1 { std::string value; }; struct e_failure_info2 { int value; }; // A type that represents a successfully returned result from a task. struct task_result { }; // This is our task function. It produces objects of type task_result, but it // may fail. leaf::result task() { bool succeed = (rand()%4) != 0; //...at random. if( succeed ) return { }; else return leaf::new_error( e_thread_id{std::this_thread::get_id()}, e_failure_info1{"info"}, e_failure_info2{42} ); }; 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. std::generate_n( std::back_inserter(fut), task_count, [&] { return std::async( std::launch::async, [&] { return leaf::capture(leaf::make_shared_context(error_handlers), &task); } ); } ); // Wait on the futures, get the task results, handle errors. for( auto & f : fut ) { f.wait(); leaf::try_handle_all( [&]() -> leaf::result { 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 ); } } //////////////////////////////////////// #ifdef BOOST_LEAF_NO_EXCEPTIONS namespace 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; [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } } #endif ================================================ FILE: example/error_log.cpp ================================================ // 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) // This program demonstrates the use of leaf::on_error to print the path an // error takes as it bubbles up the call stack. The printing code only runs if: // - An error occurs, and // - A handler that takes e_error_log argument is present. Otherwise none of the // error log machinery will be invoked by LEAF. // This example is similar to error_trace, except the path the error takes is // not captured, only printed. #include #include #include #define ENABLE_ERROR_LOG 1 namespace leaf = boost::leaf; // The error log is activated only if an error handling scope provides a handler // for e_error_log. struct e_error_log { struct rec { char const * file; int line; friend std::ostream & operator<<( std::ostream & os, rec const & x ) { return os << x.file << '(' << x.line << ')'; } }; e_error_log() { std::cerr << "Error! Log:" << std::endl; } // Our e_error_log instance is stateless, used only as a target to // operator<<. template friend std::ostream & operator<<( e_error_log const &, T const & x ) { return std::cerr << x << std::endl; } }; // The ERROR_LOG macro is designed for use in functions that detect or forward // errors up the call stack. If an error occurs, and if an error handling scope // provides a handler for e_error_log, the supplied lambda is executed as the // error bubbles up. #define ERROR_LOG auto _log = leaf::on_error( []( e_error_log & log ) { log << e_error_log::rec{__FILE__, __LINE__}; } ) // Each function in the sequence below calls the previous function, and each // function has failure_percent chance of failing. If a failure occurs, the // ERROR_LOG macro will cause the path the error takes to be printed. int const failure_percent = 25; leaf::result f1() { ERROR_LOG; if( (std::rand()%100) > failure_percent ) return { }; else return leaf::new_error(); } leaf::result f2() { ERROR_LOG; if( (std::rand()%100) > failure_percent ) return f1(); else return leaf::new_error(); } leaf::result f3() { ERROR_LOG; if( (std::rand()%100) > failure_percent ) return f2(); else return leaf::new_error(); } leaf::result f4() { ERROR_LOG; if( (std::rand()%100) > failure_percent ) return f3(); else return leaf::new_error(); } leaf::result f5() { ERROR_LOG; if( (std::rand()%100) > failure_percent ) return f4(); else return leaf::new_error(); } int main() { for( int i=0; i!=10; ++i ) leaf::try_handle_all( [&]() -> leaf::result { std::cout << "Run # " << i << ": "; BOOST_LEAF_CHECK(f5()); std::cout << "Success!" << std::endl; return { }; }, #if ENABLE_ERROR_LOG // This single #if enables or disables the printing of the error log. []( e_error_log const & ) { }, #endif [] { std::cerr << "Error!" << std::endl; } ); return 0; } //////////////////////////////////////// #ifdef BOOST_LEAF_NO_EXCEPTIONS namespace 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; [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } } #endif ================================================ FILE: example/error_trace.cpp ================================================ // 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) // This program demonstrates the use of leaf::on_error to capture the path an // error takes as is bubbles up the call stack. The error path-capturing code // only runs if: // - An error occurs, and // - A handler that takes e_error_trace argument is present. Otherwise none of // the error trace machinery will be invoked by LEAF. // This example is similar to error_log, except the path the error takes is // recorded in a std::deque, rather than just printed in-place. #include #include #include #include #define ENABLE_ERROR_TRACE 1 namespace leaf = boost::leaf; // The error trace is activated only if an error handling scope provides a // handler for e_error_trace. struct e_error_trace { struct rec { char const * file; int line; friend std::ostream & operator<<( std::ostream & os, rec const & x ) { return os << x.file << '(' << x.line << ')' << std::endl; } }; std::deque value; friend std::ostream & operator<<( std::ostream & os, e_error_trace const & tr ) { for( auto & i : tr.value ) os << i; return os; } }; // The ERROR_TRACE macro is designed for use in functions that detect or forward // errors up the call stack. If an error occurs, and if an error handling scope // provides a handler for e_error_trace, the supplied lambda is executed as the // error bubbles up. #define ERROR_TRACE auto _trace = leaf::on_error( []( e_error_trace & tr ) { tr.value.emplace_front(e_error_trace::rec{__FILE__, __LINE__}); } ) // Each function in the sequence below calls the previous function, and each // function has failure_percent chance of failing. If a failure occurs, the // ERROR_TRACE macro will cause the path the error takes to be captured in an // e_error_trace. int const failure_percent = 25; leaf::result f1() { ERROR_TRACE; if( (std::rand()%100) > failure_percent ) return { }; else return leaf::new_error(); } leaf::result f2() { ERROR_TRACE; if( (std::rand()%100) > failure_percent ) return f1(); else return leaf::new_error(); } leaf::result f3() { ERROR_TRACE; if( (std::rand()%100) > failure_percent ) return f2(); else return leaf::new_error(); } leaf::result f4() { ERROR_TRACE; if( (std::rand()%100) > failure_percent ) return f3(); else return leaf::new_error(); } leaf::result f5() { ERROR_TRACE; if( (std::rand()%100) > failure_percent ) return f4(); else return leaf::new_error(); } int main() { for( int i=0; i!=10; ++i ) leaf::try_handle_all( [&]() -> leaf::result { std::cout << "Run # " << i << ": "; BOOST_LEAF_CHECK(f5()); std::cout << "Success!" << std::endl; return { }; }, #if ENABLE_ERROR_TRACE // This single #if enables or disables the capturing of the error trace. []( e_error_trace const & tr ) { std::cerr << "Error! Trace:" << std::endl << tr; }, #endif [] { std::cerr << "Error!" << std::endl; } ); return 0; } //////////////////////////////////////// #ifdef BOOST_LEAF_NO_EXCEPTIONS namespace 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; [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } } #endif ================================================ FILE: example/exception_to_result.cpp ================================================ // 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) // This example demonstrates how to transport exceptions thrown by a low level // function through an intermediate scopes that are not exception-safe, to be // handled in a high level function which may or may not be exception-safe. #include #include namespace leaf = boost::leaf; class error_base: public virtual std::exception { }; class error_a: public virtual error_base { }; class error_b: public virtual error_base { }; class error_c: public virtual error_base { }; // Lower-level library function which throws exceptions. int compute_answer_throws() { switch( rand()%4 ) { default: return 42; case 1: throw error_a(); case 2: throw error_b(); case 3: throw error_c(); } } // Call compute_answer_throws, switch to result for error handling. leaf::result compute_answer() noexcept { // Convert exceptions of types error_a and error_b to be communicated by // leaf::result. Any other exception will be communicated as a // std::exception_ptr. return leaf::exception_to_result( [] { return compute_answer_throws(); } ); } // Print the answer if the call to compute_answer is successful. leaf::result print_answer() noexcept { BOOST_LEAF_AUTO( answer, compute_answer()); std::cout << "Answer: " << answer << std::endl; return { }; } int main() { // Exercise print_answer a few times and handle errors. Note that the // exception objects that compute_answer_throws throws are not handled as // exceptions, but as regular LEAF error error objects... for( int i=0; i!=42; ++i ) { leaf::try_handle_all( []() -> leaf::result { BOOST_LEAF_CHECK(print_answer()); return { }; }, []( error_a const & ) { std::cerr << "Error A!" << std::endl; }, []( error_b const & ) { std::cerr << "Error B!" << std::endl; }, // ...except for error_c errors, which (for demonstration) are // captured as exceptions into std::exception_ptr as "unknown" // exceptions. Presumably this should not happen, therefore at this // point we treat this situation as a logic error: we print // diagnostic information and bail out. []( std::exception_ptr const * ep ) { std::cerr << "Got unknown error!" << std::endl; // Above, why do we take ep as a pointer? Because handle_all // requires that the last handler matches any error and, taken // as a pointer, if there isn't a std::exception_ptr associated // with the error, the handler will still be matched (with 0 // passed for ep). Had we taken it by value or by const &, the // program would not have compiled. if( ep ) leaf::try_catch( [&] { std::rethrow_exception(*ep); }, []( leaf::error_info const & unmatched ) { std::cerr << unmatched; } ); } ); } return 0; } ================================================ FILE: example/lua_callback_eh.cpp ================================================ // 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) // This is a simple program that shows how to report error objects out of a // C-callback (which may not throw exceptions). extern "C" { #include "lua.h" #include "lauxlib.h" } #include #include #include namespace leaf = boost::leaf; enum do_work_error_code { ec1=1, ec2 }; struct e_lua_pcall_error { int value; friend std::ostream & operator<<( std::ostream & os, e_lua_pcall_error const & x ) { os << "Lua error code = " << x.value; switch( x.value ) { case LUA_ERRRUN: return os << " (LUA_ERRRUN)"; case LUA_ERRMEM: return os << " (LUA_ERRMEM)"; case LUA_ERRERR: return os << " (LUA_ERRERR)"; default: return os << " (unknown)"; } } }; struct e_lua_error_message { std::string value; }; struct e_lua_exception { std::exception_ptr value; }; // A noexcept wrapper for a lua_CFunction pointer. We capture the // std::current_exception and wrap it in a e_lua_exception object. template int wrap_lua_CFunction( lua_State * L ) noexcept { return leaf::try_catch( [&] { return F(L); }, [&]( leaf::error_info const & ei ) { ei.error().load( e_lua_exception{std::current_exception()} ); return luaL_error(L, "C++ Exception"); // luaL_error does not return (longjmp). } ); } // This is a C callback with a specific signature, callable from programs // written in Lua. If it succeeds, it returns an int answer, by pushing it onto // the Lua stack. But "sometimes" it fails, in which case it throws an // exception, which will be processed by wrap_lua_CFunction (above). int do_work( lua_State * L ) { bool success = rand() % 2; // "Sometimes" do_work fails. if( success ) { lua_pushnumber(L, 42); // Success, push the result on the Lua stack, return to Lua. return 1; } else { leaf::throw_exception(ec1); } } std::shared_ptr init_lua_state() { // Create a new lua_State, we'll use std::shared_ptr for automatic cleanup. std::shared_ptr L(lua_open(), &lua_close); // Register the do_work function (above) as a C callback, under the global // Lua name "do_work". With this, calls from Lua programs to do_work will // land in the do_work C function we've registered. lua_register( &*L, "do_work", &wrap_lua_CFunction<&do_work> ); // Pass some Lua code as a C string literal to Lua. This creates a global // Lua function called "call_do_work", which we will later ask Lua to // execute. luaL_dostring( &*L, "\ \n function call_do_work()\ \n return do_work()\ \n end" ); return L; } // Here we will ask Lua to execute the function call_do_work, which is written // in Lua, and returns the value from do_work, which is written in C++ and // registered with the Lua interpreter as a C callback. // If do_work succeeds, we return the resulting int answer. If it fails, we'll // communicate that failure to our caller. int call_lua( lua_State * L ) { return leaf::try_catch( [&] { leaf::error_monitor cur_err; // Ask the Lua interpreter to call the global Lua function call_do_work. lua_getfield( L, LUA_GLOBALSINDEX, "call_do_work" ); if( int err = lua_pcall(L, 0, 1, 0) ) { std::string msg = lua_tostring(L, 1); lua_pop(L,1); // We got a Lua error which may be the error we're reporting // from do_work, or some other error. If it is another error, // 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. leaf::throw_exception( cur_err.assigned_error_id().load( e_lua_pcall_error{err}, e_lua_error_message{std::move(msg)} ) ); } else { // Success! Just return the int answer. int answer = lua_tonumber(L, -1); lua_pop(L, 1); return answer; } }, []( e_lua_exception e ) -> int { // This is the exception communicated out of wrap_lua_CFunction. std::rethrow_exception( e.value ); } ); } int main() { std::shared_ptr L=init_lua_state(); for( int i=0; i!=10; ++i ) { leaf::try_catch( [&] { int answer = call_lua(&*L); std::cout << "do_work succeeded, answer=" << answer << '\n'; }, []( do_work_error_code e, e_lua_error_message const & msg ) { std::cout << "Got do_work_error_code = " << e << ", " << msg.value << "\n"; }, []( e_lua_pcall_error const & err, e_lua_error_message const & msg ) { std::cout << "Got e_lua_pcall_error, " << err << ", " << msg.value << "\n"; }, []( leaf::error_info const & unmatched ) { std::cerr << "Unknown failure detected" << std::endl << "Cryptic diagnostic information follows" << std::endl << unmatched; } ); } return 0; } ================================================ FILE: example/lua_callback_result.cpp ================================================ // 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) // This is a simple program that shows how to report error objects out of a // C-callback, converting them to leaf::result as soon as controlreaches C++. extern "C" { #include "lua.h" #include "lauxlib.h" } #include #include #include namespace leaf = boost::leaf; enum do_work_error_code { ec1=1, ec2 }; struct e_lua_pcall_error { int value; friend std::ostream & operator<<( std::ostream & os, e_lua_pcall_error const & x ) { os << "Lua error code = " << x.value; switch( x.value ) { case LUA_ERRRUN: return os << " (LUA_ERRRUN)"; case LUA_ERRMEM: return os << " (LUA_ERRMEM)"; case LUA_ERRERR: return os << " (LUA_ERRERR)"; default: return os << " (unknown)"; } } }; struct e_lua_error_message { std::string value; }; // This is a C callback with a specific signature, callable from programs // written in Lua. If it succeeds, it returns an int answer, by pushing it onto // the Lua stack. But "sometimes" it fails, in which case it calls luaL_error. // This causes the Lua interpreter to abort and pop back into the C++ code which // called it (see call_lua below). int do_work( lua_State * L ) { bool success = rand() % 2; // "Sometimes" do_work fails. if( success ) { lua_pushnumber(L, 42); // Success, push the result on the Lua stack, return to Lua. return 1; } else { return leaf::new_error(ec1), luaL_error(L,"do_work_error"); // luaL_error does not return (longjmp). } } std::shared_ptr init_lua_state() { // Create a new lua_State, we'll use std::shared_ptr for automatic cleanup. std::shared_ptr L(lua_open(), &lua_close); // Register the do_work function (above) as a C callback, under the global // Lua name "do_work". With this, calls from Lua programs to do_work will // land in the do_work C function we've registered. lua_register( &*L, "do_work", &do_work ); // Pass some Lua code as a C string literal to Lua. This creates a global // Lua function called "call_do_work", which we will later ask Lua to // execute. luaL_dostring( &*L, "\ \n function call_do_work()\ \n return do_work()\ \n end" ); return L; } // Here we will ask Lua to execute the function call_do_work, which is written // in Lua, and returns the value from do_work, which is written in C++ and // registered with the Lua interpreter as a C callback. // If do_work succeeds, we return the resulting int answer. If it fails, we'll // communicate that failure to our caller. leaf::result call_lua( lua_State * L ) { leaf::error_monitor cur_err; // Ask the Lua interpreter to call the global Lua function call_do_work. lua_getfield( L, LUA_GLOBALSINDEX, "call_do_work" ); if( int err = lua_pcall(L, 0, 1, 0) ) // Ask Lua to call the global function call_do_work. { std::string msg = lua_tostring(L, 1); lua_pop(L, 1); // We got a Lua error which may be the error we're reporting from // do_work, or some other error. If it is another error, // cur_err.assigned_error_id() will return a new leaf::error_id, // otherwise we'll be working with the original value returned by // leaf::new_error in do_work. return cur_err.assigned_error_id().load( e_lua_pcall_error{err}, e_lua_error_message{std::move(msg)} ); } else { // Success! Just return the int answer. int answer = lua_tonumber(L, -1); lua_pop(L, 1); return answer; } } int main() { std::shared_ptr L=init_lua_state(); for( int i=0; i!=10; ++i ) { leaf::try_handle_all( [&]() -> leaf::result { BOOST_LEAF_AUTO(answer, call_lua(&*L)); std::cout << "do_work succeeded, answer=" << answer << '\n'; return { }; }, []( do_work_error_code e, e_lua_error_message const & msg ) { std::cout << "Got do_work_error_code = " << e << ", " << msg.value << "\n"; }, []( e_lua_pcall_error const & err, e_lua_error_message const & msg ) { std::cout << "Got e_lua_pcall_error, " << err << ", " << msg.value << "\n"; }, []( leaf::error_info const & unmatched ) { std::cerr << "Unknown failure detected" << std::endl << "Cryptic diagnostic information follows" << std::endl << unmatched; } ); } return 0; } #ifdef BOOST_LEAF_NO_EXCEPTIONS namespace 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; [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } } #endif ================================================ FILE: example/print_file/print_file_eh.cpp ================================================ // 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) // This is the program presented in // https://boostorg.github.io/leaf/#introduction-eh. // 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. #include #include #include namespace leaf = boost::leaf; // First, we need an enum to define our error codes: enum error_code { bad_command_line = 1, open_error, read_error, size_error, eof_error, output_error }; // We will handle all failures in our main function, but first, here are the // declarations of the functions it calls, each communicating failures by // throwing exceptions // Parse the command line, return the file name. char const * parse_command_line( int argc, char const * argv[] ); // Open a file for reading. std::shared_ptr file_open( char const * file_name ); // Return the size of the file. std::size_t file_size( FILE & f ); // Read size bytes from f into buf. void file_read( FILE & f, void * buf, std::size_t size ); // The main function, which handles all errors. int main( int argc, char const * argv[] ) { return leaf::try_catch( [&] { char const * file_name = parse_command_line(argc,argv); auto load = leaf::on_error( leaf::e_file_name{file_name} ); std::shared_ptr f = file_open(file_name); std::size_t s = file_size(*f); std::string buffer(1 + s, '\0'); file_read(*f, &buffer[0], buffer.size()-1); std::cout << buffer; std::cout.flush(); if( std::cout.fail() ) leaf::throw_exception(output_error, leaf::e_errno{errno}); return 0; }, // Each of the lambdas below is an error handler. LEAF will consider // them, in order, and call the first one that matches the available // error objects. // This handler will be called if the error includes: // - an object of type error_code equal to open_error, and // - an object of type leaf::e_errno that has .value equal to ENOENT, // and // - an object of type leaf::e_file_name. []( leaf::match, leaf::match_value, leaf::e_file_name const & fn ) { std::cerr << "File not found: " << fn.value << std::endl; return 1; }, // This handler will be called if the error includes: // - an object of type error_code equal to open_error, and // - an object of type leaf::e_errno (regardless of its .value), and // - an object of type leaf::e_file_name. []( leaf::match, leaf::e_errno const & errn, leaf::e_file_name const & fn ) { std::cerr << "Failed to open " << fn.value << ", errno=" << errn << std::endl; return 2; }, // This handler will be called if the error includes: // - an object of type error_code equal to any of size_error, // read_error, eof_error, and // - an optional object of type leaf::e_errno (regardless of its // .value), and // - an object of type leaf::e_file_name. []( leaf::match, leaf::e_errno const * errn, leaf::e_file_name const & fn ) { std::cerr << "Failed to access " << fn.value; if( errn ) std::cerr << ", errno=" << *errn; std::cerr << std::endl; return 3; }, // This handler will be called if the error includes: // - an object of type error_code equal to output_error, and // - an object of type leaf::e_errno (regardless of its .value), []( leaf::match, leaf::e_errno const & errn ) { std::cerr << "Output error, errno=" << errn << std::endl; return 4; }, // This handler will be called if we've got a bad_command_line []( leaf::match ) { std::cout << "Bad command line argument" << std::endl; return 5; }, // This last handler matches any error: it prints diagnostic information // to help debug logic errors in the program, since it failed to match // an appropriate error handler to the error condition it encountered. // In this program this handler will never be called. []( leaf::error_info const & unmatched ) { std::cerr << "Unknown failure detected" << std::endl << "Cryptic diagnostic information follows" << std::endl << unmatched; return 6; } ); } // Implementations of the functions called by main: // Parse the command line, return the file name. char const * parse_command_line( int argc, char const * argv[] ) { if( argc==2 ) return argv[1]; else leaf::throw_exception(bad_command_line); } // Open a file for reading. std::shared_ptr file_open( char const * file_name ) { if( FILE * f = fopen(file_name, "rb") ) return std::shared_ptr(f, &fclose); else leaf::throw_exception(open_error, leaf::e_errno{errno}); } // Return the size of the file. std::size_t file_size( FILE & f ) { auto load = leaf::on_error([] { return leaf::e_errno{errno}; }); if( fseek(&f, 0, SEEK_END) ) leaf::throw_exception(size_error); long s = ftell(&f); if( s==-1L ) leaf::throw_exception(size_error); if( fseek(&f,0,SEEK_SET) ) leaf::throw_exception(size_error); return std::size_t(s); } // Read size bytes from f into buf. void file_read( FILE & f, void * buf, std::size_t size ) { std::size_t n = fread(buf, 1, size, &f); if( ferror(&f) ) leaf::throw_exception(read_error, leaf::e_errno{errno}); if( n!=size ) leaf::throw_exception(eof_error); } ================================================ FILE: example/print_file/print_file_outcome_result.cpp ================================================ // 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) // This is the program presented in // https://boostorg.github.io/leaf/#introduction-result, converted to use // outcome::result instead of leaf::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. #include #include #include #include namespace outcome = boost::outcome_v2; namespace leaf = boost::leaf; // First, we need an enum to define our error codes: enum error_code { bad_command_line = 1, open_error, read_error, size_error, eof_error, output_error }; template using result = outcome::std_result; // To enable LEAF to work with outcome::result, we need to specialize the // is_result_type template: namespace boost { namespace leaf { template struct is_result_type>: std::true_type { }; } } // We will handle all failures in our main function, but first, here are the // declarations of the functions it calls, each communicating failures using // result: // Parse the command line, return the file name. result parse_command_line( int argc, char const * argv[] ); // Open a file for reading. result> file_open( char const * file_name ); // Return the size of the file. result file_size( FILE & f ); // Read size bytes from f into buf. result file_read( FILE & f, void * buf, std::size_t size ); // The main function, which handles all errors. int main( int argc, char const * argv[] ) { return leaf::try_handle_all( [&]() -> result { BOOST_LEAF_AUTO(file_name, parse_command_line(argc,argv)); auto load = leaf::on_error( leaf::e_file_name{file_name} ); BOOST_LEAF_AUTO(f, file_open(file_name)); BOOST_LEAF_AUTO(s, file_size(*f)); std::string buffer(1 + s, '\0'); BOOST_LEAF_CHECK(file_read(*f, &buffer[0], buffer.size()-1)); std::cout << buffer; std::cout.flush(); if( std::cout.fail() ) return leaf::new_error(output_error, leaf::e_errno{errno}).to_error_code(); return 0; }, // Each of the lambdas below is an error handler. LEAF will consider // them, in order, and call the first one that matches the available // error objects. // This handler will be called if the error includes: // - an object of type error_code equal to open_error, and // - an object of type leaf::e_errno that has .value equal to ENOENT, // and // - an object of type leaf::e_file_name. []( leaf::match, leaf::match_value, leaf::e_file_name const & fn ) { std::cerr << "File not found: " << fn.value << std::endl; return 1; }, // This handler will be called if the error includes: // - an object of type error_code equal to open_error, and // - an object of type leaf::e_errno (regardless of its .value), and // - an object of type leaf::e_file_name. []( leaf::match, leaf::e_errno const & errn, leaf::e_file_name const & fn ) { std::cerr << "Failed to open " << fn.value << ", errno=" << errn << std::endl; return 2; }, // This handler will be called if the error includes: // - an object of type error_code equal to any of size_error, // read_error, eof_error, and // - an optional object of type leaf::e_errno (regardless of its // .value), and // - an object of type leaf::e_file_name. []( leaf::match, leaf::e_errno const * errn, leaf::e_file_name const & fn ) { std::cerr << "Failed to access " << fn.value; if( errn ) std::cerr << ", errno=" << *errn; std::cerr << std::endl; return 3; }, // This handler will be called if the error includes: // - an object of type error_code equal to output_error, and // - an object of type leaf::e_errno (regardless of its .value), []( leaf::match, leaf::e_errno const & errn ) { std::cerr << "Output error, errno=" << errn << std::endl; return 4; }, // This handler will be called if we've got a bad_command_line []( leaf::match ) { std::cout << "Bad command line argument" << std::endl; return 5; }, // This last handler matches any error: it prints diagnostic information // to help debug logic errors in the program, since it failed to match // an appropriate error handler to the error condition it encountered. // In this program this handler will never be called. []( leaf::error_info const & unmatched ) { std::cerr << "Unknown failure detected" << std::endl << "Cryptic diagnostic information follows" << std::endl << unmatched; return 6; } ); } // Implementations of the functions called by main: // Parse the command line, return the file name. result parse_command_line( int argc, char const * argv[] ) { if( argc==2 ) return argv[1]; else return leaf::new_error(bad_command_line).to_error_code(); } // Open a file for reading. 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 the size of the file. 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(); long s = ftell(&f); if( s==-1L ) return leaf::new_error(size_error).to_error_code(); if( fseek(&f,0,SEEK_SET) ) return leaf::new_error(size_error).to_error_code(); return std::size_t(s); } // Read size bytes from f into buf. result file_read( FILE & f, void * buf, std::size_t size ) { 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(); if( n!=size ) return leaf::new_error(eof_error).to_error_code(); return outcome::success(); } //////////////////////////////////////// #ifdef BOOST_LEAF_NO_EXCEPTIONS namespace 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; [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } } #endif ================================================ FILE: example/print_file/print_file_result.cpp ================================================ // 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) // This is the program presented in // 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. The version that // does use exception handling is in print_file_eh.cpp. #include #include #include namespace leaf = boost::leaf; // First, we need an enum to define our error codes: enum error_code { bad_command_line = 1, open_error, read_error, size_error, eof_error, output_error }; template using result = leaf::result; // We will handle all failures in our main function, but first, here are the // declarations of the functions it calls, each communicating failures using // result: // Parse the command line, return the file name. result parse_command_line( int argc, char const * argv[] ); // Open a file for reading. result> file_open( char const * file_name ); // Return the size of the file. result file_size( FILE & f ); // Read size bytes from f into buf. result file_read( FILE & f, void * buf, std::size_t size ); // The main function, which handles all errors. int main( int argc, char const * argv[] ) { return leaf::try_handle_all( [&]() -> result { BOOST_LEAF_AUTO(file_name, parse_command_line(argc,argv)); auto load = leaf::on_error( leaf::e_file_name{file_name} ); BOOST_LEAF_AUTO(f, file_open(file_name)); BOOST_LEAF_AUTO(s, file_size(*f)); std::string buffer(1 + s, '\0'); BOOST_LEAF_CHECK(file_read(*f, &buffer[0], buffer.size()-1)); std::cout << buffer; std::cout.flush(); if( std::cout.fail() ) return leaf::new_error(output_error, leaf::e_errno{errno}); return 0; }, // Each of the lambdas below is an error handler. LEAF will consider // them, in order, and call the first one that matches the available // error objects. // This handler will be called if the error includes: // - an object of type error_code equal to open_error, and // - an object of type leaf::e_errno that has .value equal to ENOENT, // and // - an object of type leaf::e_file_name. []( leaf::match, leaf::match_value, leaf::e_file_name const & fn ) { std::cerr << "File not found: " << fn.value << std::endl; return 1; }, // This handler will be called if the error includes: // - an object of type error_code equal to open_error, and // - an object of type leaf::e_errno (regardless of its .value), and // - an object of type leaf::e_file_name. []( leaf::match, leaf::e_errno const & errn, leaf::e_file_name const & fn ) { std::cerr << "Failed to open " << fn.value << ", errno=" << errn << std::endl; return 2; }, // This handler will be called if the error includes: // - an object of type error_code equal to any of size_error, // read_error, eof_error, and // - an optional object of type leaf::e_errno (regardless of its // .value), and // - an object of type leaf::e_file_name. []( leaf::match, leaf::e_errno const * errn, leaf::e_file_name const & fn ) { std::cerr << "Failed to access " << fn.value; if( errn ) std::cerr << ", errno=" << *errn; std::cerr << std::endl; return 3; }, // This handler will be called if the error includes: // - an object of type error_code equal to output_error, and // - an object of type leaf::e_errno (regardless of its .value), []( leaf::match, leaf::e_errno const & errn ) { std::cerr << "Output error, errno=" << errn << std::endl; return 4; }, // This handler will be called if we've got a bad_command_line []( leaf::match ) { std::cout << "Bad command line argument" << std::endl; return 5; }, // This last handler matches any error: it prints diagnostic information // to help debug logic errors in the program, since it failed to match // an appropriate error handler to the error condition it encountered. // In this program this handler will never be called. []( leaf::error_info const & unmatched ) { std::cerr << "Unknown failure detected" << std::endl << "Cryptic diagnostic information follows" << std::endl << unmatched; return 6; } ); } // Implementations of the functions called by main: // Parse the command line, return the file name. result parse_command_line( int argc, char const * argv[] ) { if( argc==2 ) return argv[1]; else return leaf::new_error(bad_command_line); } // Open a file for reading. 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}); } // Return the size of the file. 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); 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 std::size_t(s); } // Read size bytes from f into buf. result file_read( FILE & f, void * buf, std::size_t size ) { 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 ) return leaf::new_error(eof_error); return { }; } //////////////////////////////////////// #ifdef BOOST_LEAF_NO_EXCEPTIONS namespace 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; [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } } #endif ================================================ FILE: example/print_file/readme.md ================================================ # 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: * [print_file_result.cpp](./print_file_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_eh.cpp](./print_file_eh.cpp) throws on error, using an error code `enum` for classification of failures. ================================================ FILE: example/print_half.cpp ================================================ // 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) // This program is an adaptation of the following Boost Outcome example: // https://github.com/ned14/outcome/blob/master/doc/src/snippets/using_result.cpp #include #include #include #include #include namespace leaf = boost::leaf; enum class ConversionErrc { EmptyString = 1, IllegalChar, TooLong }; leaf::result convert(const std::string& str) noexcept { if (str.empty()) return leaf::new_error(ConversionErrc::EmptyString); if (!std::all_of(str.begin(), str.end(), ::isdigit)) return leaf::new_error(ConversionErrc::IllegalChar); if (str.length() > 9) return leaf::new_error(ConversionErrc::TooLong); return atoi(str.c_str()); } // Do not static_store BigInt to actually work -- it's a stub. struct BigInt { static leaf::result fromString(const std::string& s) { return BigInt{s}; } explicit BigInt(const std::string&) { } BigInt half() const { return BigInt{""}; } friend std::ostream& operator<<(std::ostream& o, const BigInt&) { return o << "big int half"; } }; // This function handles ConversionErrc::TooLong errors, forwards any other // error to the caller. leaf::result print_half(const std::string& text) { return leaf::try_handle_some( [&]() -> leaf::result { BOOST_LEAF_AUTO(r,convert(text)); std::cout << r / 2 << std::endl; return { }; }, [&]( leaf::match ) -> leaf::result { BOOST_LEAF_AUTO(i, BigInt::fromString(text)); std::cout << i.half() << std::endl; return { }; } ); } int main( int argc, char const * argv[] ) { return leaf::try_handle_all( [&]() -> leaf::result { BOOST_LEAF_CHECK( print_half(argc<2 ? "" : argv[1]) ); std::cout << "ok" << std::endl; return 0; }, []( leaf::match ) { std::cerr << "Empty string!" << std::endl; return 1; }, []( leaf::match ) { std::cerr << "Illegal char!" << std::endl; return 2; }, []( leaf::error_info const & unmatched ) { // This will never execute in this program, but it would detect // logic errors where an unknown error reaches main. In this case, // we print diagnostic information. std::cerr << "Unknown failure detected" << std::endl << "Cryptic diagnostic information follows" << std::endl << unmatched; return 3; } ); } //////////////////////////////////////// #ifdef BOOST_LEAF_NO_EXCEPTIONS namespace 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; [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } } #endif ================================================ FILE: example/readme.md ================================================ # 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. * [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. * [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. * [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. ================================================ FILE: gen/generate_single_header.py ================================================ """ Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. Copyright (c) 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) This program generates a single header file from a file including multiple C/C++ headers. Usage: python3 generate_single_header.py --help e.g. python3 generate_single_header.py -i include/boost/leaf/detail/all.hpp -p include -o test/leaf.hpp boost/leaf """ import argparse import os import re from datetime import date import subprocess included = {} total_line_count = 11 def append(input_file_name, input_file, output_file, regex_includes, include_folder): global total_line_count line_count = 1 for line in input_file: line_count += 1 result = regex_includes.search(line) if result: 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)) 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)) 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)) total_line_count += 2 else: output_file.write(line) total_line_count += 1 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)") 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( '#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")) if args.hash: output_file.write( ' from https://github.com/boostorg/leaf/tree/' + args.hash[0:7]) output_file.write( '.\n' '// Latest version of this file: https://raw.githubusercontent.com/boostorg/leaf/gh-pages/leaf.hpp.\n' '\n') append(args.input, input_file, output_file, regex_includes, args.path) output_file.write( '\n' '#endif\n' ) # print("%d" % total_line_count) if __name__ == "__main__": _main() ================================================ FILE: include/boost/leaf/capture.hpp ================================================ #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_uint(unsigned(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(); leaf_detail::throw_exception_impl( capturing_exception(std::current_exception(), std::move(ctx)) ); } catch(...) { ctx->captured_id_ = cur_err.assigned_error_id(); leaf_detail::throw_exception_impl( 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(); leaf_detail::throw_exception_impl( capturing_exception(std::current_exception(), std::move(ctx)) ); } catch(...) { ctx->captured_id_ = cur_err.assigned_error_id(); leaf_detail::throw_exception_impl( 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 ================================================ FILE: include/boost/leaf/common.hpp ================================================ #ifndef BOOST_LEAF_COMMON_HPP_INCLUDED #define BOOST_LEAF_COMMON_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_STD_STRING # include #endif #include #if BOOST_LEAF_CFG_WIN32 # include # include # ifdef min # undef min # endif # ifdef max # undef max # endif #endif namespace boost { namespace leaf { struct BOOST_LEAF_SYMBOL_VISIBLE e_api_function { char const * value; }; #if BOOST_LEAF_CFG_STD_STRING struct BOOST_LEAF_SYMBOL_VISIBLE e_file_name { std::string value; }; #else struct BOOST_LEAF_SYMBOL_VISIBLE e_file_name { constexpr static char const * const value = ""; BOOST_LEAF_CONSTEXPR explicit e_file_name( char const * ) { } }; #endif struct BOOST_LEAF_SYMBOL_VISIBLE e_errno { int value; explicit e_errno(int val=errno): value(val) { } template friend std::basic_ostream & operator<<(std::basic_ostream & os, e_errno const & err) { return os << type() << ": " << err.value << ", \"" << std::strerror(err.value) << '"'; } }; struct BOOST_LEAF_SYMBOL_VISIBLE e_type_info_name { char const * value; }; struct BOOST_LEAF_SYMBOL_VISIBLE e_at_line { int value; }; namespace windows { struct e_LastError { unsigned 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) { struct msg_buf { LPVOID * p; msg_buf(): p(nullptr) { } ~msg_buf() noexcept { if(p) LocalFree(p); } }; msg_buf mb; if( FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, err.value, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), (LPSTR)&mb.p, 0, nullptr) ) { BOOST_LEAF_ASSERT(mb.p != nullptr); char * z = std::strchr((LPSTR)mb.p,0); if( z[-1] == '\n' ) *--z = 0; if( z[-1] == '\r' ) *--z = 0; return os << type() << ": " << err.value << ", \"" << (LPCSTR)mb.p << '"'; } return os; } #endif }; } } } #endif ================================================ FILE: include/boost/leaf/config/tls.hpp ================================================ #ifndef BOOST_LEAF_CONFIG_TLS_HPP_INCLUDED #define BOOST_LEAF_CONFIG_TLS_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) #if defined(BOOST_LEAF_TLS_FREERTOS) # include #endif #ifndef BOOST_LEAF_USE_TLS_ARRAY # ifdef BOOST_LEAF_CFG_TLS_INDEX_TYPE # warning "BOOST_LEAF_CFG_TLS_INDEX_TYPE" is ignored if BOOST_LEAF_USE_TLS_ARRAY is not defined. # endif # ifdef BOOST_LEAF_CFG_TLS_ARRAY_SIZE # warning "BOOST_LEAF_CFG_TLS_ARRAY_SIZE" is ignored if BOOST_LEAF_USE_TLS_ARRAY is not defined. # endif # ifdef BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX # warning "BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX" is ignored if BOOST_LEAF_USE_TLS_ARRAY is not defined. # endif #endif #if defined BOOST_LEAF_USE_TLS_ARRAY # include #elif defined(BOOST_LEAF_NO_THREADS) # include #else # include #endif #endif ================================================ FILE: include/boost/leaf/config/tls_array.hpp ================================================ #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 // 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 unsigned int // values for platforms that support thread local pointers by index. namespace boost { namespace leaf { namespace tls { // The TLS support defined in this header requires the following two // functions to be defined elsewhere: void * read_void_ptr( int tls_index ) noexcept; void write_void_ptr( int tls_index, void * ) noexcept; } } } //////////////////////////////////////// #include #include #include #include #ifndef BOOST_LEAF_CFG_TLS_INDEX_TYPE # define BOOST_LEAF_CFG_TLS_INDEX_TYPE unsigned char #endif #ifndef BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX # define BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX 0 #endif static_assert((BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX) >= 0, "Bad BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX"); #ifdef BOOST_LEAF_CFG_TLS_ARRAY_SIZE static_assert((BOOST_LEAF_CFG_TLS_ARRAY_SIZE) > (BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX), "Bad BOOST_LEAF_CFG_TLS_ARRAY_SIZE"); static_assert((BOOST_LEAF_CFG_TLS_ARRAY_SIZE) - 1 <= std::numeric_limits::max(), "Bad BOOST_LEAF_CFG_TLS_ARRAY_SIZE"); #endif //////////////////////////////////////// namespace boost { namespace leaf { namespace leaf_detail { using atomic_unsigned_int = std::atomic; } namespace tls { template class BOOST_LEAF_SYMBOL_VISIBLE index_counter { static int c_; public: static BOOST_LEAF_CFG_TLS_INDEX_TYPE next() { 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; } }; template struct BOOST_LEAF_SYMBOL_VISIBLE tls_index { static BOOST_LEAF_CFG_TLS_INDEX_TYPE idx; }; template struct BOOST_LEAF_SYMBOL_VISIBLE alloc_tls_index { static BOOST_LEAF_CFG_TLS_INDEX_TYPE const idx; }; template int index_counter::c_ = BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX; template 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(); //////////////////////////////////////// template T * read_ptr() noexcept { int tls_idx = tls_index::idx; if( tls_idx == (BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX) ) return nullptr; --tls_idx; return reinterpret_cast(read_void_ptr(tls_idx)); } template void write_ptr( T * p ) noexcept { int tls_idx = alloc_tls_index::idx; --tls_idx; write_void_ptr(tls_idx, p); BOOST_LEAF_ASSERT(read_void_ptr(tls_idx) == p); } //////////////////////////////////////// template unsigned read_uint() noexcept { static_assert(sizeof(std::intptr_t) >= sizeof(unsigned), "Incompatible tls_array implementation"); return (unsigned) (std::intptr_t) (void *) read_ptr(); } template void write_uint( unsigned x ) noexcept { static_assert(sizeof(std::intptr_t) >= sizeof(unsigned), "Incompatible tls_array implementation"); write_ptr((Tag *) (void *) (std::intptr_t) x); } template void uint_increment() noexcept { write_uint(read_uint() + 1); } template void uint_decrement() noexcept { write_uint(read_uint() - 1); } } } } #endif ================================================ FILE: include/boost/leaf/config/tls_cpp11.hpp ================================================ #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. // 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 unsigned int // values using the C++11 built-in thread_local storage class specifier. #include #include namespace boost { namespace leaf { namespace leaf_detail { using atomic_unsigned_int = std::atomic; } namespace tls { template struct BOOST_LEAF_SYMBOL_VISIBLE ptr { static thread_local T * p; }; template thread_local T * ptr::p; template T * read_ptr() noexcept { return ptr::p; } template void write_ptr( T * p ) noexcept { ptr::p = p; } //////////////////////////////////////// template struct BOOST_LEAF_SYMBOL_VISIBLE tagged_uint { static thread_local unsigned x; }; template thread_local unsigned tagged_uint::x; template unsigned read_uint() noexcept { return tagged_uint::x; } template void write_uint( unsigned x ) noexcept { tagged_uint::x = x; } template void uint_increment() noexcept { ++tagged_uint::x; } template void uint_decrement() noexcept { --tagged_uint::x; } } } } #endif ================================================ FILE: include/boost/leaf/config/tls_freertos.hpp ================================================ #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 // 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 #ifndef BOOST_LEAF_USE_TLS_ARRAY # define BOOST_LEAF_USE_TLS_ARRAY #endif #ifndef BOOST_LEAF_CFG_TLS_ARRAY_SIZE # define BOOST_LEAF_CFG_TLS_ARRAY_SIZE configNUM_THREAD_LOCAL_STORAGE_POINTERS #endif static_assert((BOOST_LEAF_CFG_TLS_ARRAY_SIZE) <= configNUM_THREAD_LOCAL_STORAGE_POINTERS, "Bad BOOST_LEAF_CFG_TLS_ARRAY_SIZE"); namespace boost { namespace leaf { namespace tls { // See https://www.freertos.org/thread-local-storage-pointers.html. inline void * read_void_ptr( int tls_index ) noexcept { return pvTaskGetThreadLocalStoragePointer(0, tls_index); } inline void write_void_ptr( int tls_index, void * p ) noexcept { vTaskSetThreadLocalStoragePointer(0, tls_index, p); } } } } #endif ================================================ FILE: include/boost/leaf/config/tls_globals.hpp ================================================ #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. // 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 unsigned int // values using globals, which is suitable for single thread environments. #include namespace boost { namespace leaf { namespace leaf_detail { using atomic_unsigned_int = unsigned int; } namespace tls { template struct BOOST_LEAF_SYMBOL_VISIBLE ptr { static T * p; }; template T * ptr::p; template T * read_ptr() noexcept { return ptr::p; } template void write_ptr( T * p ) noexcept { ptr::p = p; } //////////////////////////////////////// template struct BOOST_LEAF_SYMBOL_VISIBLE tagged_uint { static unsigned x; }; template unsigned tagged_uint::x; template unsigned read_uint() noexcept { return tagged_uint::x; } template void write_uint( unsigned x ) noexcept { tagged_uint::x = x; } template void uint_increment() noexcept { ++tagged_uint::x; } template void uint_decrement() noexcept { --tagged_uint::x; } } } } #endif ================================================ FILE: include/boost/leaf/config.hpp ================================================ #ifndef BOOST_LEAF_CONFIG_HPP_INCLUDED #define BOOST_LEAF_CONFIG_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) // 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_CFG_DIAGNOSTICS # define BOOST_LEAF_CFG_DIAGNOSTICS 1 #endif #ifndef BOOST_LEAF_CFG_STD_SYSTEM_ERROR # define BOOST_LEAF_CFG_STD_SYSTEM_ERROR 1 #endif #ifndef BOOST_LEAF_CFG_STD_STRING # define BOOST_LEAF_CFG_STD_STRING 1 #endif #ifndef BOOST_LEAF_CFG_CAPTURE # define BOOST_LEAF_CFG_CAPTURE 1 #endif #ifndef BOOST_LEAF_CFG_WIN32 # define BOOST_LEAF_CFG_WIN32 0 #endif #ifndef BOOST_LEAF_CFG_GNUC_STMTEXPR # ifdef __GNUC__ # define BOOST_LEAF_CFG_GNUC_STMTEXPR 1 # else # define BOOST_LEAF_CFG_GNUC_STMTEXPR 0 # endif #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 # 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 # error BOOST_LEAF_CFG_STD_STRING must be 0 or 1. #endif #if BOOST_LEAF_CFG_CAPTURE!=0 && BOOST_LEAF_CFG_CAPTURE!=1 # error BOOST_LEAF_CFG_CAPTURE must be 0 or 1. #endif #if BOOST_LEAF_CFG_DIAGNOSTICS && !BOOST_LEAF_CFG_STD_STRING # error BOOST_LEAF_CFG_DIAGNOSTICS requires the use of std::string #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 //////////////////////////////////////// // Configure BOOST_LEAF_NO_EXCEPTIONS, unless already #defined #ifndef BOOST_LEAF_NO_EXCEPTIONS # if defined(__clang__) && !defined(__ibmxl__) // Clang C++ emulates GCC, so it has to appear early. # if !__has_feature(cxx_exceptions) # define BOOST_LEAF_NO_EXCEPTIONS # endif # elif defined(__DMC__) // Digital Mars C++ # if !defined(_CPPUNWIND) # define BOOST_LEAF_NO_EXCEPTIONS # endif # elif defined(__GNUC__) && !defined(__ibmxl__) // GNU C++: # if !defined(__EXCEPTIONS) # define BOOST_LEAF_NO_EXCEPTIONS # endif # elif defined(__KCC) // Kai C++ # if !defined(_EXCEPTIONS) # define BOOST_LEAF_NO_EXCEPTIONS # endif # elif defined(__CODEGEARC__) // CodeGear - must be checked for before Borland # if !defined(_CPPUNWIND) && !defined(__EXCEPTIONS) # define BOOST_LEAF_NO_EXCEPTIONS # endif # elif defined(__BORLANDC__) // Borland # if !defined(_CPPUNWIND) && !defined(__EXCEPTIONS) # define BOOST_LEAF_NO_EXCEPTIONS # endif # elif defined(__MWERKS__) // Metrowerks CodeWarrior # if !__option(exceptions) # define BOOST_LEAF_NO_EXCEPTIONS # endif # elif defined(__IBMCPP__) && defined(__COMPILER_VER__) && defined(__MVS__) // IBM z/OS XL C/C++ # if !defined(_CPPUNWIND) && !defined(__EXCEPTIONS) # define BOOST_LEAF_NO_EXCEPTIONS # endif # elif defined(__ibmxl__) // IBM XL C/C++ for Linux (Little Endian) # if !__has_feature(cxx_exceptions) # define BOOST_LEAF_NO_EXCEPTIONS # endif # elif defined(_MSC_VER) // Microsoft Visual C++ // // Must remain the last #elif since some other vendors (Metrowerks, for // example) also #define _MSC_VER # if !_CPPUNWIND # define BOOST_LEAF_NO_EXCEPTIONS # endif # endif #endif //////////////////////////////////////// #ifdef _MSC_VER # define BOOST_LEAF_ALWAYS_INLINE __forceinline #else # define BOOST_LEAF_ALWAYS_INLINE __attribute__((always_inline)) inline #endif //////////////////////////////////////// #ifndef BOOST_LEAF_NODISCARD # if __cplusplus >= 201703L # define BOOST_LEAF_NODISCARD [[nodiscard]] # else # define BOOST_LEAF_NODISCARD # endif #endif //////////////////////////////////////// #ifndef BOOST_LEAF_CONSTEXPR # if __cplusplus > 201402L # define BOOST_LEAF_CONSTEXPR constexpr # else # define BOOST_LEAF_CONSTEXPR # endif #endif //////////////////////////////////////// #ifndef BOOST_LEAF_NO_EXCEPTIONS # include # if (defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L) || (defined(_MSC_VER) && _MSC_VER >= 1900) # define BOOST_LEAF_STD_UNCAUGHT_EXCEPTIONS 1 # else # define BOOST_LEAF_STD_UNCAUGHT_EXCEPTIONS 0 # endif #endif //////////////////////////////////////// #ifdef __GNUC__ # define BOOST_LEAF_SYMBOL_VISIBLE __attribute__((__visibility__("default"))) #else # define BOOST_LEAF_SYMBOL_VISIBLE #endif //////////////////////////////////////// #if defined(__GNUC__) && !(defined(__clang__) || defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC)) && (__GNUC__ * 100 + __GNUC_MINOR__) < 409 # ifndef BOOST_LEAF_NO_CXX11_REF_QUALIFIERS # define BOOST_LEAF_NO_CXX11_REF_QUALIFIERS # endif #endif //////////////////////////////////////// // Configure TLS access #include //////////////////////////////////////// #endif ================================================ FILE: include/boost/leaf/context.hpp ================================================ #ifndef BOOST_LEAF_CONTEXT_HPP_INCLUDED #define BOOST_LEAF_CONTEXT_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 #if !defined(BOOST_LEAF_NO_THREADS) && !defined(NDEBUG) # include #endif namespace boost { namespace leaf { class error_info; class diagnostic_info; class verbose_diagnostic_info; template struct is_predicate: std::false_type { }; namespace leaf_detail { template struct is_exception: std::is_base_of::type> { }; template struct handler_argument_traits; template ::value> struct handler_argument_traits_defaults; template struct handler_argument_traits_defaults { using error_type = typename std::decay::type; constexpr static bool always_available = false; template BOOST_LEAF_CONSTEXPR static error_type const * check( Tup const &, error_info const & ) noexcept; template BOOST_LEAF_CONSTEXPR static error_type * check( Tup &, error_info const & ) noexcept; template BOOST_LEAF_CONSTEXPR static E get( Tup & tup, error_info const & ei ) noexcept { return *check(tup, ei); } 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 &"); }; template struct handler_argument_traits_defaults: handler_argument_traits { using base = handler_argument_traits; static_assert(!base::always_available, "Predicates can't use types that are always_available"); template BOOST_LEAF_CONSTEXPR static bool check( Tup const & tup, error_info const & ei ) noexcept { auto e = base::check(tup, ei); return e && Pred::evaluate(*e); } template BOOST_LEAF_CONSTEXPR static Pred get( Tup const & tup, error_info const & ei ) noexcept { return Pred{*base::check(tup, ei)}; } }; template struct handler_argument_always_available { using error_type = E; constexpr static bool always_available = true; template BOOST_LEAF_CONSTEXPR static bool check( Tup &, error_info const & ) noexcept { return true; } }; template struct handler_argument_traits: handler_argument_traits_defaults { }; template <> struct handler_argument_traits { using error_type = void; constexpr static bool always_available = false; template BOOST_LEAF_CONSTEXPR static std::exception const * check( Tup const &, error_info const & ) noexcept; }; template struct handler_argument_traits { static_assert(sizeof(E) == 0, "Error handlers may not take rvalue ref arguments"); }; template struct handler_argument_traits: handler_argument_always_available::type> { template BOOST_LEAF_CONSTEXPR static E * get( Tup & tup, error_info const & ei) noexcept { return handler_argument_traits_defaults::check(tup, ei); } }; template <> struct handler_argument_traits: handler_argument_always_available { template BOOST_LEAF_CONSTEXPR static error_info const & get( Tup const &, error_info const & ei ) noexcept { return ei; } }; template struct handler_argument_traits_require_by_value { static_assert(sizeof(E) == 0, "Error handlers must take this type by value"); }; } //////////////////////////////////////// namespace leaf_detail { template struct tuple_for_each { BOOST_LEAF_CONSTEXPR static void activate( Tuple & tup ) noexcept { static_assert(!std::is_same(tup))>::type>::value, "Bug in LEAF: context type deduction"); tuple_for_each::activate(tup); std::get(tup).activate(); } BOOST_LEAF_CONSTEXPR static void deactivate( Tuple & 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); } BOOST_LEAF_CONSTEXPR static void propagate_captured( Tuple & 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); } template static void print( std::basic_ostream & os, void const * tup, int key_to_print ) { BOOST_LEAF_ASSERT(tup != nullptr); tuple_for_each::print(os, tup, key_to_print); std::get(*static_cast(tup)).print(os, key_to_print); } }; template struct tuple_for_each<0, Tuple> { 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 { } template BOOST_LEAF_CONSTEXPR static void print( std::basic_ostream &, void const *, int ) { } }; } //////////////////////////////////////////// #if BOOST_LEAF_CFG_DIAGNOSTICS namespace leaf_detail { template struct requires_unexpected { constexpr static bool value = false; }; template struct requires_unexpected { constexpr static bool value = requires_unexpected::value; }; template struct requires_unexpected { constexpr static bool value = requires_unexpected::value; }; template struct requires_unexpected { constexpr static bool value = requires_unexpected::value; }; template <> struct requires_unexpected { constexpr static bool value = true; }; template <> struct requires_unexpected { constexpr static bool value = true; }; template struct unexpected_requested; template