From b1341db700dc280c0caa3cb5a652c110bdde08ee Mon Sep 17 00:00:00 2001 From: Corentin Wallez Date: Wed, 23 May 2018 16:56:55 -0400 Subject: [PATCH] Add a NXT_NO_DISCARD that is C++17 [[nodiscard]] where available --- CMakeLists.txt | 7 +++++++ src/common/Compiler.h | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 83bea7193e..af9b75eb95 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,6 +49,7 @@ option(NXT_ENABLE_NULL "Enable compilation of the Null backend" ON) option(NXT_ENABLE_OPENGL "Enable compilation of the OpenGL backend" ON) option(NXT_ENABLE_VULKAN "Enable compilation of the Vulkan backend" OFF) option(NXT_ALWAYS_ASSERT "Enable assertions on all build types" OFF) +option(NXT_USE_CPP17 "Use some optional C++17 features for compile-time checks" OFF) ################################################################################ # Precompute compile flags and defines, functions to set them @@ -64,6 +65,12 @@ set(NXT_ENABLE_ASSERTS $,$>) list(APPEND NXT_DEFS $<${NXT_ENABLE_ASSERTS}:NXT_ENABLE_ASSERTS>) +if (NXT_USE_CPP17) + list(APPEND NXT_INTERNAL_DEFS "NXT_CPP_VERSION=17") +else() + list(APPEND NXT_INTERNAL_DEFS "NXT_CPP_VERSION=14") +endif() + if (NXT_ENABLE_D3D12) list(APPEND NXT_INTERNAL_DEFS "NXT_ENABLE_BACKEND_D3D12") endif() diff --git a/src/common/Compiler.h b/src/common/Compiler.h index ba7aa48d9e..8b1cb333fe 100644 --- a/src/common/Compiler.h +++ b/src/common/Compiler.h @@ -19,6 +19,7 @@ // - NXT_COMPILER_[CLANG|GCC|MSVC]: Compiler detection // - NXT_BREAKPOINT(): Raises an exception and breaks in the debugger // - NXT_BUILTIN_UNREACHABLE(): Hints the compiler that a code path is unreachable +// - NXT_NO_DISCARD: An attribute that is C++17 [[nodiscard]] where available // Clang and GCC #if defined(__GNUC__) @@ -36,6 +37,19 @@ # define NXT_BUILTIN_UNREACHABLE() __builtin_unreachable() +# if !defined(__has_cpp_attribute) +# define __has_cpp_attribute(name) 0 +# endif + +// Use warn_unused_result on clang otherwise we can a c++1z extension warning in C++14 mode +// Also avoid warn_unused_result with GCC because it is only a function attribute and not a type +// attribute. +# if __has_cpp_attribute(warn_unused_result) && defined(__clang__) +# define NXT_NO_DISCARD __attribute__((warn_unused_result)) +# elif NXT_CPP_VERSION >= 17 && __has_cpp_attribute(nodiscard) +# define NXT_NO_DISCARD [[nodiscard]] +# endif + // MSVC #elif defined(_MSC_VER) # define NXT_COMPILER_MSVC @@ -45,8 +59,18 @@ extern void __cdecl __debugbreak(void); # define NXT_BUILTIN_UNREACHABLE() __assume(false) +// Visual Studio 2017 15.3 adds support for [[nodiscard]] +# if _MSC_VER >= 1911 && NXT_CPP_VERSION >= 17 +# define NXT_NO_DISCARD [[nodiscard]] +# endif + #else # error "Unsupported compiler" #endif +// Add noop replacements for macros for features that aren't supported by the compiler. +#if !defined(NXT_NO_DISCARD) +# define NXT_NO_DISCARD +#endif + #endif // COMMON_COMPILER_H_