Token strings as "cheap" macros.

Reiner Pope some at address.com
Thu Sep 6 23:59:59 PDT 2007


Chris Nicholson-Sauls wrote:
> Looking at D/2.x Token Strings (q{...}) something came to mind.  If we 
> had a way of embedding expressions which evaluate to strings within this 
> syntax, it could be used to write rather clean mixins.  (The use of 
> which I assume to be a driver behind their introduction anyhow.)
> 
> What I'm thinking of, is this sort of thing:
> template Gettor (T, char[] name) {
>     const Gettor =
>         T.stringof~" get"~name~" () {
>             return _"~name~";
>         }
>     ";
> }
> 
> 
> Looking more like this:
> template Gettor (T, char[] name) {
>     const Gettor = q{
>         ${T.stringof} get${name} () {
>             return _${name};
>         }
>     };
> }
> 
> 
> Which benefits from being easier to visually parse (and therefore 
> develop and maintain), and being open to editor highlighting.  I use `` 
> strings right now, with `~...~` embeds, to similar effect only because 
> my main editor doesn't know about `` strings.  Its really just a 
> somewhat limited builtin compile-time-string-formatting capability.
> 
> The syntax doesn't matter, I just borrowed ${} from PHP.
> function Gettor ($name) {
>   return <<<EOI
>     function get${name} () {
>       return _${name};
>     }
> EOI;
> }
> 
> -- Chris Nicholson-Sauls


I made my own compile-time formatter. I made one based on Phobos 
formatting, and then I decided I preferred indexable style (like Tango), 
so I've got one of each: formatStringTango and formatStringPhobos. Just 
now, I added a wrapper function for formatStringTango which allows 
expressions instead of indexes. Here's the unittest:

unittest
{
     const x = 5;
     const y = 7;
     static assert(mixin(format("{x} = 5, {y} = 7")) == "5 = 5, 7 = 7");
}

I've attached the source code.  It's full of other templates I made to 
help work around problems with metaprogramming (__traits in particular), 
but it at least shows that it's pretty much achievable within the 
language. Of course, macros would be nice, to remove the mixin().

   -- Reiner
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: my_metastrings.d
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20070907/fefe5013/attachment.ksh>


More information about the Digitalmars-d mailing list