From 2491980b23ff252f6cb43c7f753d176c7cfafaee Mon Sep 17 00:00:00 2001 From: Chinmay Garde Date: Wed, 19 May 2021 10:53:55 -0700 Subject: [PATCH] Fix inclusion in translation units with exceptions disabled. (#196) If exceptions are disabled via `-fno-exceptions` or `INJA_NOEXCEPTION`, the use of try-catch is disallowed by the compiler. This patch makes does two things: * Gates the use of try-catch in one translation unit on the definition of `INJA_NOEXCEPTION`. * Make it such that translation units compiled with `-fno-exceptions` but no `INJA_NOEXCEPTION` implicitly sets `INJA_NOEXCEPTION`. In the specific case of `ifstream::open`, setting the exceptions bits without exceptions enabled should trip an assertion just like INJA_ABORT. The nice message will not be present however, but that is absent when using INJA_ABORT as well. After this patch, inja can be successfully included without issue. --- include/inja/inja.hpp | 3 +++ include/inja/utils.hpp | 4 ++++ single_include/inja/inja.hpp | 7 +++++++ 3 files changed, 14 insertions(+) diff --git a/include/inja/inja.hpp b/include/inja/inja.hpp index 86b8a0a..92b6345 100644 --- a/include/inja/inja.hpp +++ b/include/inja/inja.hpp @@ -10,6 +10,9 @@ #else #include #define INJA_THROW(exception) std::abort() + #ifndef INJA_NOEXCEPTION + #define INJA_NOEXCEPTION + #endif #endif #include "environment.hpp" diff --git a/include/inja/utils.hpp b/include/inja/utils.hpp index fb1736c..836425d 100644 --- a/include/inja/utils.hpp +++ b/include/inja/utils.hpp @@ -15,11 +15,15 @@ namespace inja { inline void open_file_or_throw(const std::string &path, std::ifstream &file) { file.exceptions(std::ifstream::failbit | std::ifstream::badbit); +#ifndef INJA_NOEXCEPTION try { file.open(path); } catch (const std::ios_base::failure & /*e*/) { INJA_THROW(FileError("failed accessing file at '" + path + "'")); } +#else + file.open(path); +#endif } namespace string_view { diff --git a/single_include/inja/inja.hpp b/single_include/inja/inja.hpp index cdca7e1..a69457b 100644 --- a/single_include/inja/inja.hpp +++ b/single_include/inja/inja.hpp @@ -10,6 +10,9 @@ #else #include #define INJA_THROW(exception) std::abort() + #ifndef INJA_NOEXCEPTION + #define INJA_NOEXCEPTION + #endif #endif // #include "environment.hpp" @@ -1842,11 +1845,15 @@ namespace inja { inline void open_file_or_throw(const std::string &path, std::ifstream &file) { file.exceptions(std::ifstream::failbit | std::ifstream::badbit); +#ifndef INJA_NOEXCEPTION try { file.open(path); } catch (const std::ios_base::failure & /*e*/) { INJA_THROW(FileError("failed accessing file at '" + path + "'")); } +#else + file.open(path); +#endif } namespace string_view {