sta-core/include/sta/assert.hpp
2023-02-02 22:22:14 +01:00

144 lines
3.1 KiB
C++

/**
* @file
* @brief Assertion handling.
*
* Configuration:
* * STA_ASSERT_FORCE: Ignore debug defines and always enable assertions
* * DEBUG: Enables assertions when defined
* * NDEBUG: Disables assertions when defined (overrides DEBUG)
*/
#ifndef STA_CORE_ASSERT_HPP
#define STA_CORE_ASSERT_HPP
/**
* @defgroup sta_core Core
* @brief STA Core library
*/
/**
* @defgroup sta_core_platforms Platforms
* @ingroup sta_core
* @brief Platform specific implementations.
*/
#include <sta/config.hpp>
// Determine if module should be enabled
// Condition:
// STA_ASSERT_FORCE is defined
// or
// DEBUG is defined but not NDEBUG
#ifdef STA_ASSERT_FORCE
# define STA_ASSERT_ENABLED
#else // !STA_ASSERT_FORCE
# if defined(DEBUG) && !defined(NDEBUG)
# define STA_ASSERT_ENABLED
# endif // DEBUG && !NDEBUG
#endif // !STA_ASSERT_FORCE
#if defined(STA_ASSERT_ENABLED) || defined(DOXYGEN)
#include <cstdint>
/**
* @defgroup sta_core_assert Assert
* @ingroup sta_core
* @brief Assertion handling.
*/
namespace sta
{
/**
* @ingroup sta_core_assert
* @{
*/
/**
* @brief Handle failed assertions.
*
* The default implementation uses **STA_DEBUG_PRINT** and will not
* generate any output if the **DEBUG_SERIAL** module is disabled.
*
* Weak implementation can be overridden.
*
* @param expr Asserted expression or message
* @param file File name
* @param line Line number
*/
void assert_failed(const char * expr, const char * file, uint32_t line);
/**
* @brief Stop execution.
*
* Weak implementation can be overridden.
*/
void assert_halt();
/** @} */
} // namespace sta
/**
* @ingroup sta_core_assert
* @{
*/
/**
* @brief Assert expression.
*
* @param expr Expression
*/
# define STA_ASSERT(expr) ( (void)( !(expr) && ( sta::assert_failed(#expr, __FILE__, __LINE__), 1 ) && ( sta::assert_halt(), 1 ) ) )
/**
* @brief Assert expression.
*
* @param expr Expression
* @param msg Message shown on failure
*/
# define STA_ASSERT_MSG(expr, msg) ( (void)( !(expr) && ( sta::assert_failed(msg, __FILE__, __LINE__), 1 ) && ( sta::assert_halt(), 1 ) ) )
/**
* @brief Assert expression if condition is true.
*
* @param cond Condition
* @param expr Expression
*/
# define STA_ASSERT_COND(cond, expr) ( (void)( (cond) ? STA_ASSERT(expr) : 1 ) )
/**
* @brief Assert expression if condition is true.
*
* @param cond Condition
* @param expr Expression
* @param msg Message shown on failure
*/
# define STA_ASSERT_COND_MSG(cond, expr, msg) ( (void)( (cond) ? STA_ASSERT_MSG(expr, msg) ) )
/**
* @brief Expression only evaluated when assertions are enabled.
*
* @param expr Expression
*/
# define STA_ASSERT_EXTRA(expr) expr
/** @} */
#else // !STA_ASSERT_ENABLED
# define STA_ASSERT(expr) ((void)0)
# define STA_ASSERT_MSG(expr, msg) ((void)0)
# define STA_ASSERT_COND(cond, expr) ((void)0)
# define STA_ASSERT_COND_MSG(cond, expr, msg) ((void)0)
# define STA_ASSERT_EXTRA(expr) ((void)0)
#endif // !STA_ASSERT_ENABLED
#endif // STA_CORE_ASSERT_HPP