Skip to content

assert macro expand as expression #138

@ahgamut

Description

@ahgamut

In cosmopolitan.h, assert is defined as a macro using __ASSERT_FAIL:

#define assert(EXPR)                            \
  do {                                          \
    if (!(EXPR)) {                              \
      __ASSERT_FAIL(#EXPR, __FILE__, __LINE__); \
      unreachable;                              \
    }                                           \
  } while (0)

This works fine when calling assert individually, but triggers an error when assert is part of another macro.

Example compiler output when enabling C API tests in Lua source:

././libcosmo/cosmopolitan.h:3371:3: error: expected expression before ‘do’
   do {                                          \
   ^~
llimits.h:93:33: note: in expansion of macro ‘assert’
 #define lua_assert(c)           assert(c)
                                 ^~~~~~
llimits.h:110:38: note: in expansion of macro ‘lua_assert’
 #define luai_apicheck(l,e) ((void)l, lua_assert(e))
                                      ^~~~~~~~~~
llimits.h:113:28: note: in expansion of macro ‘luai_apicheck’
 #define api_check(l,e,msg) luai_apicheck(l,(e) && msg)
                            ^~~~~~~~~~~~~
lapi.c:87:5: note: in expansion of macro ‘api_check’
     api_check(L, o < L->top, "unacceptable index");

Changing the assert macro to the below expression (Reference: assert in musl) prevents the error:

#ifdef NDEBUG
#define assert(EXPR) ((void) 0)
#else
#define assert(EXPR) ((void)((EXPR) || (__assert_fail(#EXPR, __FILE__, __LINE__),0)))
#endif

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions