| |
| Posted by Jonathan M Davis in reply to Cecil Ward | PermalinkReply |
|
Jonathan M Davis
Posted in reply to Cecil Ward
| On Thursday, June 29, 2023 12:27:22 PM MDT Cecil Ward via Digitalmars-d-learn wrote:
> I’m trying to debug my D program with old-fashioned printfs stuck
> in various strategic places, actually using writefln(). My
> problem is that the addition of printf fights with the existing
> declarations for pure nothrow @nogc @safe and I have to adjust
> them, then put them back correctly when the writefln() trace
> statements are later removed.
>
> Is there something else I could be using, something that is allowed to violate the checking rules for purity, nothrow, @nogc? Would pragma( msg, "…" ) do the trick? Is that what I should be using?
pragma(msg, ...) and writeln are fundamentally different.
pragmas are run when code is compiled. When you calling a function during CTFE, you are calling that function. You are not compiling it. It has already been compiled at that point. That function may be being called as part of compiling another function, but function that you're calling has already been compiled. So, something like
string foo() { return "foo"; }
void bar(int i)
{
pragma(msg, foo());
}
will compile just fine, and it will print out "foo" at compile time, whereas
void bar(int i)
{
pragma(msg, i);
}
will not compile.
void bar(int i)
{
writeln(i);
}
will compile, but it won't print anything when it's compiled, and it cannot be called with CTFE. However, it will of course print out if called at runtime.
If you need to print out a message during testing, and the function in question has attributes that writeln does not satisfy, then you can use debug statements and compile the code with the -debug flag.
https://dlang.org/spec/version.html#debug
e.g.
void foo() pure @safe
{
debug
{
writeln("hello");
}
}
Of course, you have to be very careful when you do that, since you'll get undefined behavior if the debug statements have side effects which violate the guarantees that those attributes are supposed to make (e.g. mutating a global variable in a pure function or throwing an exception from a nothrow function), but simply printing out stuff shouldn't be a problem unless generating the strings to print has side effects.
- Jonathan M Davis
|