My late christmas present for you: context-aware assertion error messages
Seb
seb at wilzba.ch
Sat Jan 12 15:34:02 UTC 2019
tl;dr: I was annoyed for years that D's assert are so non
informative AssertError, so here's my late Christmas present for
the D community. With 2.085 DMD will gain an experimental flag
for more informative assertion errors. Feedback on this
experimental feature is welcome, s.t. we eventually can enable it
by default.
Example:
---
void main()
{
int a = 1, b = 2;
assert(a == b); // ERROR: 1 != 2
}
---
```
> dmd -run onlineapp.d
core.exception.AssertError at onlineapp.d(4): 1 != 2
----------------
??:? _d_assert_msg [0xb150e350]
??:? _Dmain [0xb150d627]
```
Play online: https://run.dlang.io/is/GMfe9S
Full changelog: https://dlang.org/changelog/pending.html#assert
Where to start hacking:
-
https://github.com/dlang/dmd/blob/00299e3b6ca9dcd5a5dc8bd50280b63d0bdc51f9/src/dmd/expressionsem.d#L5559
-
https://github.com/dlang/druntime/blob/master/src/core/internal/dassert.d
- https://github.com/dlang/dmd/pull/8517
Q: Why not just introduce an `assertEqual` user function?
A:
- there's a lot of already written D code out there that uses
`assert` [1]
- `assertEqual` wouldn't cut, it because then we would need to
have an `assertLessThan` etc. too
Q: Why put this in the compiler and not in fluent-assert or
similar library?
A:
- there's a lot of already written D code out there that uses
`assert` [1]
- not everyone wants to use a library just to have somewhat
decent assert messages
- libraries can only do sth. like `testedValue.should.equal(42)`,
but the compiler can deal with `testedValue == 42`
[1] https://github.com/search?l=D&q=assert&type=Code
Error context
-------------
Also note that with 2.085 DMD will get -verrors=context
---
void foo()
{
a = 1;
}
---
```
> dmd -verrors=context onlineapp.d
onlineapp.d(3): Error: undefined identifier a
a = 1;
^
```
Full changelog:
https://dlang.org/changelog/pending.html#error-context
Play online: https://run.dlang.io/is/8gsye1
Thanks to all the people (Jacob Carlborg, Petar Kirov, Nicolas
Wilson, Rainer Schuetze, etc.) who helped me to get this feature
into DMD!
Merry Christmas!
More information about the Digitalmars-d
mailing list