[phobos] expand for std.metastrings

kenji hara k.hara.pg at gmail.com
Tue Nov 2 09:32:54 PDT 2010


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.
----
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

2010/11/2 Robert Jacques <sandford at jhu.edu>:
> On Tue, 02 Nov 2010 10:03:23 -0400, Andrei Alexandrescu <andrei at erdani.com>
> wrote:
>
>> Thanks, Kenji. All - ideas for a better name? "interp"? Full
>> "interpolate"? Leave it as "expand"?
>>
>> Andrei
>
> Well, "interpolate" and "interp" have mathematical connotations to me, so
> vote-- for those. Note that functionality of this seems very similar to both
> format and text:
>
> enum int a = 10;
> enum string op = "+";
> static assert(mixin(expand!q{ ${a*2} ${op} 2 }) == q{ 20 + 2 });
> vs.
> static assert(Format!(" %s %s 2 ",a*2,op)) == q{ 20 + 2 });
> vs.
> static assert(text(" ",a*2," ",op," 2 ") == q{ 20 + 2 };
>
> So maybe some variant of format would be appropriate: MixinFormat, mFormat,
> mText, FormatInPlace, etc, though these all seem clunky. MixinFormat would
> make a lot of sense if you could declare a template that's always a mixin,
> and could simply write MixinFormat!q{ ${a*2} ${op} 2 } instead of
> mixin(MixinFormat!q{ ${a*2} ${op} 2 }). As this syntax comes from perl, we
> could use that as a prefix: perlFormat / pFormat / perlText / pText.
>
> Also, am I missing something with regard to the use cases of expand/inter?
> All the examples given in the documentation seem to be better served by
> either text or Format.
> _______________________________________________
> phobos mailing list
> phobos at puremagic.com
> http://lists.puremagic.com/mailman/listinfo/phobos
>


More information about the phobos mailing list