// vim:fileencoding=utf-8:foldmethod=marker

#ifndef WAPP_ASSERT_H
#define WAPP_ASSERT_H

#include "../aliases/aliases.h"
#include "../platform/platform.h"
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

#ifdef WP_PLATFORM_CPP
BEGIN_C_LINKAGE
#endif // !WP_PLATFORM_CPP

#define wpStaticAssert(EXPR, MSG) wp_extern char ASSERTION_FAILED[EXPR ? 1 : -1]

#ifndef WP_NO_RUNTIME_ASSERT
	#define wpRuntimeAssert(EXPR, MSG) _runtimeAssert(EXPR, MSG)
#else
	#define wpRuntimeAssert(EXPR, MSG)
#endif

#ifdef WP_DEBUG_ASSERT
	#define wpDebugAssert(EXPR, MSG) wpRuntimeAssert(EXPR, MSG)
#else
	#define wpDebugAssert(EXPR, MSG)
#endif

#ifdef WP_PLATFORM_WINDOWS
#define _runtimeAssert(EXPR, MSG) do {                                              \
	__pragma(warning(push))                                                           \
	__pragma(warning(disable:4127))                                                   \
	if (!(EXPR)) {                                                                    \
	__pragma(warning(pop))                                                            \
		_runtimeAssertFailed(EXPR, MSG);                                                \
	}                                                                                 \
} while(false)
#else
#define _runtimeAssert(EXPR, MSG) do {                                              \
	if (!(EXPR)) {                                                                    \
		_runtimeAssertFailed(EXPR, MSG);                                                \
	}                                                                                 \
} while(false)
#endif // !WP_PLATFORM_WINDOWS

#define _runtimeAssertFailed(EXPR, MSG) do {                                        \
	fprintf(                                                                          \
		stderr,                                                                         \
		"%s:%d (In function `%s`): Assertion failed (%" PRIu32 ")\nDiagnostic: %s\n\n", \
		__FILE__, __LINE__, __func__,                                                   \
		EXPR, MSG                                                                       \
	);                                                                                \
	abort();                                                                          \
} while(false)

#ifdef WP_PLATFORM_CPP
END_C_LINKAGE
#endif // !WP_PLATFORM_CPP

#endif // !WAPP_ASSERT_H
