We need something like source_location in D

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed Jul 31 01:39:05 UTC 2019


 From C++20: 
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf

Instead of having to constantly declare "file = __FILE__, line = 
__LINE__" everywhere, it would be so much more useful to just 
have a single built-in type which we can default initialize . For 
example:

-----
import std.algorithm;

void checkAndThrow (lazy bool expression, Loc loc = __LOCATION__)
{
     if (!expression)
         throw new Exception("Failed", loc.file, loc.line);
}

void main ()
{
     auto arr = [1, 1, 1, 1];
     checkAndThrow(arr.sum == 4);

     // should throw with file+line of this statement
     checkAndThrow(arr.sum == 5);
}
-----

This also makes it very easy to extend in the future, because we 
don't have to pollute the namespace with a lot of "__"-style 
symbols.

The actual naming of the location symbol is something we can 
bikeshed over, that's fine.

If you grep for `string file = __FILE__, size_t line = __LINE__` 
or `string file = __FILE__, int line = __LINE__`, it is 
everywhere in Druntime and Phobos. I think it's time we got rid 
of this repetition.

I know __traits(getLocation) got implemented recently, but it's 
not very useful in this context because it returns a tuple 
(https://github.com/dlang/dmd/pull/10013). I don't see an easy 
way to use it in function parameters.

Should I write a DIP for this?


More information about the Digitalmars-d mailing list