better assertions and __FILE__ (call stack reflection)

Bruce Adams ifyoudontknowmebynow at searchdaweb.com
Thu Aug 16 18:00:49 PDT 2007


I have given in and raised this as an issue:

http://d.puremagic.com/issues/show_bug.cgi?id=1425

duplicated below for discussion purposes:

For improved support for assertions, logging code and stack traces it would be
useful to have means of identifying the calling frame of reference. This would
also have the advantage of rendering __LINE__ and its ilk redundant.
For example it is not currently possible to implement a cppunit like
assertEqual function.
The best I can achieve is:

void assertEqual(Type)(Type actual_, Type expected_, 
                       char[] file_, 
                       uint line_) {
   if (actual_ != expected_) {
      writefln("Equality assertion failed");
      writefln("actual:   '", actual_, "'");
      writefln("expected: '", expected_, "'");
   }
   _d_assert(file_,line_);
}

Which has to be used as:

assertEqual!(string)("foo","bar",cast(char[])(__FILE__),__LINE__);

It should be possible to achieve a more natural syntax like:

assertEqual("foo","bar");

Several proposals seem have been made on the newsgroups but none has been
raised as a request here.
I personally think the best approach is to have a library function

stackFrame[] callStack = std.trace();

By default the calling frame would be something like:

class stackFrame {
   stackFrame* parent;
   object[]    arguments;
}

When functions request source identification the compiler would have to
include mapping information so its not a pure library issue.
E.g

class SourceStackFrame: public StackFrame {
// inherited
//   stackFrame* parent;
//   object[]    arguments;
   uint        parentLine;
   string*     parentFile;
   string*     parentFunction;   
}

I imagine two ways of creating such a structure.
Use of an analogue to __FILE__ e.g. the so called "context" keyword
would tell the compiler to use the special stack frame for a specific call
only.
A command line switch could tell the compiler to always use the source stack
frame format - with resulting code bloat.


More information about the Digitalmars-d-learn mailing list