debug()

Bill Baxter dnewsgroup at billbaxter.com
Tue Feb 26 16:54:35 PST 2008


Orion- wrote:
> Hello people,
> 
> I'm just starting D programming. I'd like to make a printf like function to print some debuging informations. The synopsis could be dprintf(char[] format, ...) and as an example:
> dprintf("creating object at %a", self);
> It would print something like:
> debug: class1.d(13): creating object at 0XFFB8
> where class1.d is the __FILE__ name and 13 is the __LINE__ where it was called.
> 
> So, here are my 2 questions:
> 
>   * How do you know 'self' inside a class member function in D?
>   * How would you do to have __LINE__ being the line where dprintf was called not the line where it is implemented ?
> 
> Here is my dprintf function so far:
> void dprintf(...) {
>         TypeInfo[] infos;
>         void *data;
> 
>         void putc(dchar c) { fputc(c, stderr); }
> 
>         Box[] box1 = boxArray("debug: ");
>         Box[] box2 = boxArray(_arguments, cast(void *)_argptr);
>         boxArrayToArguments(box1 ~ box2, infos, data);
>         std.format.doFormat(&putc, infos, cast(char *)data);
> }

There is a way to get the __LINE__ thing to work automatically, without 
typing __LINE__, but the cure is almost worse than the disease.  For 
simplicity I'll just use a non-formatted string to demonstrate.

string dprintf(string msg) {
    return `writefln("%s(%s): ", __FILE__,__LINE__, msg);`;
}
...
mixin( dprintf("Hey you!"));


At least I think that works.  I don't use it because I'm not about to go 
around typing mixin everywhere to do debug output.  That's the kind of 
thing that should some day be doable with macros, though.  Then you'll 
be able to call it without the "mixin" part.

What I actually use is more like what Jason said.  debug(ver) {}.  I 
don't bother with __FILE__ and __LINE__ stuff.

-----
module MyModule;
import std.stdio;
private{
debug(MyModule)
{
     alias writefln debugfln;
     alias writef   debugf;
}
else {
     void debugfln(...) {}
     void debugf(...) {}
}
}

And I hope that the compiler is smart enough to inline an empty 
function.  If it's not, I'm getting on the next plane to Seattle to 
whack Walter 50 times with a wet noodle.

--bb



More information about the Digitalmars-d mailing list