Will macros work with expressions?

Robert Fraser fraserofthenight at gmail.com
Tue Sep 4 11:59:01 PDT 2007


Jari-Matti Mäkelä Wrote:

> I would say they have less expressiveness than C counterparts unless all
> statements suddenly become expressions. 

You can add statements, as long as they're not used in an expression, as in the C pre-processor. You can even add declarations (what template mixins are used for now. I do hope template mixins don't go, though, since templates can be used either for the mixins or instantiated as needed interchangeably.)

> However, there is no real need to
> do this. Another way could be to introduce a new compile time
> metaexpression/statement type. Maybe the "D code string" does exactly this?
> After this another problem pops up: the reflection system isn't really
> designed for this low level operations. I'm not saying this is wrong
> direction though, quite opposite. It just shows how broken the C-based
> language core is for metaprogramming. 
> 
> One more problem I see in the new macro feature is that it's basically (or
> is it - the proposal is a bit short on details) a generic cut'n'paste
> function. Is it possible to control (i.e. is it a Turing complete compile
> time function call) the output of a macro ? Pseudo code example:
> 
> macro(foo) {
>   metaif (foo == bar) {

Static if - it's already part of the language.

>     metareturn runtimecode{ while(foo.next !is null) { print(foo.next); foo
> = foo.next; }
>   } metaelse 
>     runtimecode ret;
> 
>     metaforeach(a; foo) {
>       ret ~= runtimecode{ a.bar *= 2; }
>     }
> 
>     metareturn ret;
>   }
> }
> 
> ( this is basically CTFE+mixins, but on the AST level, not with strings. I
> could do this even today by implementing a D compiler with AST macros on
> top of D with metaprogramming :P )
> 
> If I understood it correctly, the macros only do a simple substitution using
> their parameters, hide symbols when necessary (hygiene) and then attach the
> generated code to the AST.

I think that's about right, but remember that their parameters can specialize on any pattern and extract parts of the expression, which I think is the most exciting feature.



More information about the Digitalmars-d mailing list