UDA + Pegged AST Hack
Daniel N
ufo at orbiting.us
Wed Nov 28 13:40:34 PST 2012
Thanks to the wonderful UDA implementation in 2.061, I thought of
a little hack, which may interest at least someone.
I'm using it for prototyping ctfe ast transformations together
with: https://github.com/PhilippeSigaud/Pegged
Yes, it was possible to do similar stuff before and
"examples/dgrammar.d" from Pegged is quite impressive, but not
bug free.
This UDA-line-hack-way is actually significantly cleaner, because
when using __LINE__ you are certain that there will be at least
one [__LINE__] which is not inside a string or comment on the
attributed line... this allows one to make a very limited
grammar/parser which doesn't have to know/parse/understand the
entire file.
I know my proof-of-concept doesn't handle multi-line, but it can
be added, and doesn't matter for the sake of prototyping AST
manipulations.
If anyone else have fun UDA hacks, considering that it's a new
feature, please share.
import std.string;
import std.range;
struct magic
{
[__LINE__] int var1;
[__LINE__] int var2;
[__LINE__] int var3;
}
enum dsrc = import(__FILE__).splitLines(KeepTerminator.yes);
string parse()
{
string result = "";
foreach(m; __traits(allMembers, magic))
result ~= dsrc.drop(__traits(getAttributes, mixin("magic." ~
m))[0]-1).takeOne().front;
// insert pegged parsing / transformations here.
return result;
}
mixin("struct magic2\n{\n" ~ parse() ~"}");
More information about the Digitalmars-d
mailing list