String mixin syntax sugar
Tove
tove at fransson.se
Tue Mar 20 16:57:25 PDT 2012
On Tuesday, 20 March 2012 at 21:28:25 UTC, Jacob Carlborg wrote:
> On 2012-03-20 19:25, Mantis wrote:
>> Hello,
>>
>> since people discussed a lot about user-defined attributes
>> recently,
>> I've been thinking about a way to implement it with a string
>> mixins. The
>> problem with them is their syntax - it's far from what we want
>> to use in
>> everyday job. I understand, they should be easily
>> distinguished at use
>> site, but perhaps this may be accomplished in other ways as
>> well. My
>> idea is to translate this kind of statements:
>>
>> # identifier statement
>>
>> into this:
>>
>> mixin( identifier( q{ statement } ) );
>
>
> I don't like it. I want real user defined attributes.
I think the idea has merit, string mixins together with CTFE
parsing is the holy grail... because of the current syntax it's
not really feasible to use on a per-member basis... but it is
possible to use on a struct/class basis...
mixin(attr(q{struct Foo
{
@NonSerialized int x;
@NonSerialized int y;
int z;
}}));
Please disregard my broken parser(it's just a proof of concept)
However, consider what we could do with the latest CTFE parser
advances,
coupled with a tighter compiler/library callback interface.
====================================================================
import std.stdio;
import std.array;
import std.string;
import std.algorithm;
string attr(string complex_decl)
{
string org_struct;
string ser_struct;
auto lines = splitLines(complex_decl);
{
auto decl = split(stripLeft(lines[0]));
if(decl[0]=="struct")
{
org_struct = decl[0] ~ " " ~ decl[1];
ser_struct = decl[0] ~ " " ~ decl[1] ~ "_Serializable";
}
else
return complex_decl;
}
foreach(line; lines[1..$])
{
auto attr = findSplitAfter(stripLeft(line), "@NonSerialized
");
if(attr[0]=="@NonSerialized ")
org_struct ~= attr[1];
else
{
org_struct ~= attr[1];
ser_struct ~= attr[1];
}
}
return ser_struct ~ "\n" ~ org_struct;
}
mixin(attr(q{struct Foo
{
@NonSerialized int x;
@NonSerialized int y;
int z;
}}));
void main()
{
auto m = [ __traits(allMembers, Foo) ];
writeln("Normal members of Foo:", m);
auto n = [ __traits(allMembers, Foo_Serializable) ];
writeln("Serializable members of Foo:", n);
}
More information about the Digitalmars-d
mailing list