AST macros
Don Clugston
dac at nospam.com.au
Tue Mar 20 04:18:44 PDT 2007
Walter Bright wrote:
> Don Clugston wrote:
>> Walter Bright wrote:
>>> You'll be able to do things like:
>>> >>
>>> >> macro print(arg)
>>> >> {
>>> >> writefln(__FILE__, __LINE__, arg);
>>> >> }
>>
>> This looks great already. However, I don't see any specific "abstract
>> syntax tree" syntax in this. Is that still a work-in-progress?
>
> The beauty of it is that (a+b), before semantic analysis, is an AST! So
> there's no funky new grammar to learn.
Fantastic! Does this mean that you just use arg.stringof to get the
expression? And 'arg' to evaluate it?
>> An observation:
>> My version of vector operation expression templates is mostly working
>> now, using the existing mixins. It deals with ASTs by constructing a
>> string representing the operations to be performed, and a tuple
>> containing all of the parameters. The operations string is of the form
>> "g+=((a+b)*c)+((d*e)+f)", where a, b, c... correspond to T[0], T[1],
>> T[2]... of the tuple T.
>>
>> A compile-time function converts the string into postfix, and then
>> another CFTE function converts that into optimised x87 asm, which is
>> mixed in.
>
> Wow! I think the macros can help by obviating the need for the user to
> do the mixin manually.
Actually usage is OK already. Here's an example:
------
auto p = Vec([1.0, 2, 18]);
auto q = Vec([3.5L, 1.1, 3.8]);
auto r = Vec([17.0f, 28.1, 1]);
q -= ((p+r)*18.0L*314.1L - (p-r))* 35;
real d = dot(r, p + 3.7*r);
------
And the only reason for Vec() is because otherwise you can't create
array operations. In the first stage, the Vector structs returned by
Vec() are removed, and only built-in real[], double[], and float[]
vectors are put into the tuple.
BTW the generated asm is really good quality; in each case, it generates
the best code I can write by hand.
>> Unexpectedly, I found that it's actually very nice to have flattened
>> tuples. If an AST could recognise that two parameters are the same, it
>> could avoid duplication in the tuple, something that a tree can't
>> easily do:
>> eg somevec+= othervec + somevec*3;
>> could become "T[1]+=T[0]+(T[1]*3)" which allows better code generation
>> in the final stage.
>
> There's a way to do this using specialization:
>
> macro foo(somevec : somevec+=othervec+somevec, othervec)
>
> which will only match for parameters of the form:
>
> foo( a += b + a);
>
> somevec => a
> othervec => b
>
> It works analogously to how you can match type patterns in templates
> using specializations.
Now that could be useful...
Are we going to able to write macros for member functions, and operator
overloads?
More information about the Digitalmars-d
mailing list