Template context
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Sun Jan 7 14:01:19 PST 2007
Daniel Keep wrote:
>
> Ok, so I've just given up on finding any reasonable way to make this any
> easier:
>
> > trace("module.function_name", __FILE__, __LINE__, "fooing the bar");
>
> The problem is, as I'm sure you're aware, that __FILE__ and __LINE__ are
> expanded by the tokeniser, NOT the parser. Therefore, I propose the
> following:
>
> Templates all gain (either implicitly or via a specially named argument)
> an object called "context", which represents the context within which
> the template was instantiated. It should have the following
> compile-time properties:
>
> * context.line: line on which the template was instantiated.
> * context.file: file in which the template was instantiated.
> * context.symbol: the full name of the symbol in which etc.
>
> For example:
>
> > module foo;
> >
> > void trace(T_Args...)(T_Args args...)
> > {
> > writef("%s:%d (%s): ", context.file, context.line, context.symbol);
> > foreach( arg ; args )
> > writef(arg);
> > writefln();
> > }
> >
> > void main()
> > {
> > trace("Hi, ma!");
> > }
>
> Would produce the output:
>
> foo.d:13 (foo.main): Hi, ma!
>
> If any templates want to propogate their context to other templates,
> they can just pass it manually. Currently, passing this information
> around is painful (and we can't even get the symbol part AFAIK).
>
> Pretty please, Mr. Bright? *puppy dog eyes*
>
> -- Daniel
>
> P.S. We could also (with a *teensy* modification to Phobos) do this:
>
> > module bar;
> >
> > void raise(T_Exception, T_Args...)(T_Args args)
> > {
> > auto e = new T_Exception(args);
> > e.file = context.file;
> > e.line = context.line;
> > e.symbol = context.symbol;
> > throw e;
> > }
> >
> > // blah
> >
> > void main()
> > {
> > raise!(GasLeakException)("Houston, we have a problem...");
> > }
>
> Error: bar.d line 16 in bar.main: Houston, we have a problem...
Honestly, I didn't like the proposal at first... but when I started to respond, it rather
abruptly grew on me. At least some straightforward means of achieving this behavior would
be quite welcome. Perhaps 'context' should be '_context' in the vein of _arguments and
_args though. Getting the symbol, etc, wouldn't really be all that difficult. Just
define _context as a namespace of constants available during template instantiation.
-- Chris Nicholson-Sauls
More information about the Digitalmars-d
mailing list