[phobos] expand for std.metastrings

Robert Jacques sandford at jhu.edu
Tue Nov 2 10:49:11 PDT 2010


On Tue, 02 Nov 2010 12:32:54 -0400, kenji hara <k.hara.pg at gmail.com> wrote:

> My first motivation is more easiness of writing meta-programming code.
> For formatting output, I usually use writefln.
> Quoted-string is very usuful, but interpolating variable is very  
> difficult.
> ----
> string count = "10";
> enum code = q{ enum msg = "I call you } ~ count ~ q{ times"; }
> // I want to generate q{ enum msg = "I call you 10 times"; }, but can't.

The main issue is that q{} string respect D syntax, so the } inside the ""  
is treated as text, not a terminator. There's lots of ways around this:

enum code = text(q{ enum msg = "I call you "}, count, q{" times"} );
enum code = text(` enum msg = "I call you `, count, ` times;` );
enum code = ` enum msg = "I call you ` ~ count ~ ` times;`
enum code = q{ enum msg = "I call you "} ~ count ~ q{" times"; }

> ----
> With expand!, I can write code generating very easy.
> Last, adaptTo contains following code:
> ----
> // generates function definition
> template generateFun(string n)
> {
>   enum generateFun = mixin(expand!q{
>     mixin DeclareFunction!(
>       CoTypes[${n}],  // covariant
>       NameOf!(TgtFuns[${n}]),
>       "return source." ~ NameOf!(TgtFuns[${n}]) ~ "(args);"
>     );
>   });
> }
> // mixin all generated function definitions here
> mixin mixinAll!(
>   staticMap!(
>     generateFun,
>     staticMap!(StringOf, staticIota!(0,
>       TgtFuns.length))));
> ----
> If expand! does not exist, it would be terribly ugly.
> Kenji

Really?
template generateFun(string n)
{
   enum generateFun = mixin(text(q{
     mixin DeclareFunction!(
       CoTypes[},n,q{],  // covariant
       NameOf!(TgtFuns[},n,q{]),
       "return source." ~ NameOf!(TgtFuns[},n,q{]) ~ "(args);"
     );
   });
}

I admit ${n} is slightly better than },n,q{, but it's by no means ugly.  
(And using `` instead of q{} makes it better: `,n,`)


More information about the phobos mailing list