Blenlib: Add BLI_assert_msg() for printing an extra string if the assert fails

It always bothered me that we'd do the `BLI_assert(... || !"message")` trick to
print a message alongside the assert, while it should be trivial to have a way
to pass an extra string as additional argument.

This adds `BLI_assert_msg()` with a second argument for a message. E.g.:
```
BLI_assert_msg(
    params->rename_id == NULL,
    "File rename handling should immediately clear rename_id when done, because otherwise it will keep taking precedence over renamefile.");
```

On failure this will print like this:
```
0   Blender                             0x00000001140647a3 BLI_system_backtrace + 291
[...]
13  Blender                             0x00000001092647a6 main + 3814
14  libdyld.dylib                       0x00007fff203d8f5d start + 1
BLI_assert failed: source/blender/editors/space_file/file_ops.c:2352, file_directory_new_exec(), at 'params->rename_id == ((void*)0)'
  File rename handling should immediately clear rename_id when done, because otherwise it will keep taking precedence over renamefile.
```

Reviewed by: Sybren Stüvel, Jacques Lucke, Sergey Sharybin, Campbell Barton

Differential Revision: https://developer.blender.org/D11827
This commit is contained in:
Julian Eisel 2021-07-12 11:46:24 +02:00
parent c4f9bfcf5e
commit 280dac323c
2 changed files with 15 additions and 0 deletions

View File

@ -31,6 +31,7 @@ extern "C" {
/* Utility functions. */
void _BLI_assert_print_pos(const char *file, const int line, const char *function, const char *id);
void _BLI_assert_print_extra(const char *str);
void _BLI_assert_print_backtrace(void);
void _BLI_assert_abort(void);
void _BLI_assert_unreachable_print(const char *file, const int line, const char *function);
@ -61,8 +62,17 @@ void _BLI_assert_unreachable_print(const char *file, const int line, const char
_BLI_ASSERT_ABORT(), \
NULL)) : \
NULL)
/** A version of #BLI_assert() to pass an additional message to be printed on failure. */
# define BLI_assert_msg(a, msg) \
(void)((!(a)) ? ((_BLI_assert_print_backtrace(), \
_BLI_ASSERT_PRINT_POS(a), \
_BLI_assert_print_extra(msg), \
_BLI_ASSERT_ABORT(), \
NULL)) : \
NULL)
#else
# define BLI_assert(a) ((void)0)
# define BLI_assert_msg(a, msg) ((void)0)
#endif
#if defined(__cplusplus)

View File

@ -31,6 +31,11 @@ void _BLI_assert_print_pos(const char *file, const int line, const char *functio
fprintf(stderr, "BLI_assert failed: %s:%d, %s(), at \'%s\'\n", file, line, function, id);
}
void _BLI_assert_print_extra(const char *str)
{
fprintf(stderr, " %s\n", str);
}
void _BLI_assert_unreachable_print(const char *file, const int line, const char *function)
{
fprintf(stderr, "Code marked as unreachable has been executed. Please report this as a bug.\n");