Thread overview
Re: Issuing compile-time warnings with line numbers?
Sep 21, 2011
Jonathan M Davis
Sep 21, 2011
Andrej Mitrovic
Sep 21, 2011
Andrej Mitrovic
September 21, 2011
On Tuesday, September 20, 2011 17:18 Andrej Mitrovic wrote:
> Won't compile for obvious reasons:
> 
> struct Bar { }
> struct Foo
> {
> this(Bar bar, int line = __LINE__)
> {
> pragma(msg, "Warning: Constructing Foo with Bar incurs
> precision loss. Line: " ~ line);
> }
> }
> 
> void main()
> {
> auto foo = Foo(Bar());
> }
> 
> That's just an example, but I want to issue a compile-time warning when a specific ctor is called because it might incur precision loss. I want to give the user the line number of the call, but I can't call to!string since it's not ctfe-able, so do I have any other options?

Not really. That's why the "scheduled for deprecation" messages don't ever use line numbers. They can only give the line that pragma is on. If the function were templated and took the line number as a template (resulting in a new instantiation each time that the function was called), then you could use the line number in the template, but that would be the closest that you could get to having a message per call.

- Jonathan M Davis
September 21, 2011
Ah, you're right. It should have been a compile-time argument, conv.to actually works in CTFE:

import std.conv;

struct Bar { }
struct Foo
{
   this(int line = __LINE__)(Bar bar)
   {
       pragma(msg, "Warning: Constructing Foo with Bar incurs
precision loss. Line: " ~ to!string(line));
   }
}

void main()
{
   auto foo = Foo(Bar());
}

Unfortunately this is nearly impossible to use this way without making *every* ctor templated. This is due to that bug where templated functions can't overload against non-templated functions.

I guess I'll have to do without line numbers for now. But thanks for the tip.
September 21, 2011
On 9/21/11, Adam D. Ruppe <destructionator@gmail.com> wrote:
> I'd suggest having a version(warnings_suck) { static assert(0); }
> so people who want more info can just stick a -version= on the build
> and get the compiler's help.

Yeah that was already planned, no worries. :)