assert with format considered harmful

ketmar via Digitalmars-d digitalmars-d at puremagic.com
Sun Feb 26 00:28:55 PST 2017


Seb wrote:

> On Sunday, 26 February 2017 at 06:34:07 UTC, Ali Çehreli wrote:
>> So, obviously, assert message generation is not lazy. This is a WAT! 
>> for me but perhaps there is a good reason for it.
>
> FWIW imho we shouldn't need to write such messages at all.
> It shouldn't be to difficult to lower `assert (a BINOP b)` into sth. like:
>
> (auto ref a, auto ref b) {
>      if (a BINOP b) return;
>      onAssertFailed!"BINOP"(a, b, __FILE__, __LINE__, __FUNCTION__, 
>      __MODULE__);
> } (e1, e2);
>
> with onAssertFailed being a nice pretty-printer in the direction of:
>
> assert([1,2,3] == [1,2,4]); // ERROR: ([1,2,3][2] is 3) != ([1,2,4][2] is 4)
> struct A { int x, y; }
> auto a = A(1,2);
> auto b = A(1,3);
> assert(a == b);  // ERROR: (a.y is 2) != (b.y is 3)
>
> This idea is formally known as DIP83:
>
> https://wiki.dlang.org/DIP83

or at least print the condition that failed, if there is no assert 
message. this patch alone saved me alot of brain cells. somehow it is 
way easier for me to look at stack trace and get "aha!" moment, than to 
look at the source line with assert. even if the info is exactly the 
same. ;-)

besides, assert with condition printed simply looks better.

note that your suggestion may require calling `toString()`, which may 
allocate, and it may be undesirable to allocate there (maybe programmer 
did't printed more detailed info exactly 'cause he wanted to avoid 
possible allocations?). and condition printing done by simply adding 
pretty-printed string in frontend.


More information about the Digitalmars-d mailing list