Way to override/overload D’s runtime assertions to use custom handlers?

Jonathan Marler johnnymarler at gmail.com
Wed Jul 25 16:17:47 UTC 2018


On Wednesday, 25 July 2018 at 15:24:50 UTC, Alexander Nicholi 
wrote:
> Hello,
>
> A project I’m helping develop mixes D code along with C and 
> C++, and in the latter two languages we have custom macros that 
> print things the way we need to, along with app-specific 
> cleanup tasks before halting the program. Because it uses 
> multiple languages, two of which have spotty or nonexistent 
> exception support, and because we only depend on the D runtime 
> sans libphobos, we have opted to avoid the use of exceptions in 
> our codebase. Assertions still give us the ability to do 
> contract programming to some extent, while C++ and D provide 
> static assertions at compile-time to supplement.
>
> With runtime assertions, C and C++ handle things amicably, but 
> D’s `assert` builtin seems to fall back to C99’s assert.h 
> handlers and there doesn’t seem to be a way around this. Is 
> there a way to change this to use our own handlers with the D 
> runtime? How does this change without the runtime, e.g. via 
> `-betterC` code? If not, is this something that can be 
> implemented in the language as a feature request? Our use case 
> is a bit odd but still a possibility when using D as a 
> systems-level language like this.
>
> Thanks,
> Alex

As far as I know, D's "assert" falls back to __assert.  I have a 
pet/educational project (github.com/marler8997/maros) where I 
don't use the D runtime or the C runtime and my definition looks 
like this:

extern (C) void __assert(bool cond, const(char)[] msg)
{
     // TODO: would be nice to get a stack trace
     if (!cond)
     {
         version (linux)
         {
             import stdm.linux.file : stderr, write;
             import stdm.linux.process : exit;
         }
         else static assert(0, __FUNCTION__ ~ " not implemented on 
this platform");
         write(stderr, "assert failed: ");
         write(stderr, msg);
         write(stderr, "\n");
         exit(1);
     }
}

I just put this in my "object.d".




More information about the Digitalmars-d mailing list