How can I dump an expression into log and execute it

Idan Arye via Digitalmars-d digitalmars-d at puremagic.com
Fri Jul 11 16:46:42 PDT 2014


On Friday, 11 July 2014 at 22:59:10 UTC, Dicebot wrote:
> On Friday, 11 July 2014 at 22:38:36 UTC, Idan Arye wrote:
>> On Friday, 11 July 2014 at 17:00:32 UTC, Dicebot wrote:
>>> Full macro system is not needed to implement it, just AST 
>>> reflection can do the trick (and has better fit with existing 
>>> features).
>>
>> Wouldn't AST reflection be more complex to implement&use than 
>> a macro system? I mean, a macro system is quite functional in 
>> nature - the macro takes AST arguments and return an AST that 
>> the compiler embeds into the code. With AST reflection, you 
>> need to mutate an existing AST, which is more complex because 
>> order of execution matters.
>
> I mean read-only reflection akin to existing __traits

I assume "read-only" reflection means that functions produce ASTs 
that are directly embedded into the code(rather than modifying 
the AST of existing code) which is the same as with macros. So, 
if the method of output is the same, I assume the difference is 
the method of input. Macros take raw code(either as text like C 
macros as or AST like Lisp macros) and return modified code of 
the same format. Reflection is about looking at code from 
elsewhere, which would make the OP's request impractical, as `x + 
10` will have to be defined elsewhere and the reflection code 
will have to be referred to that place.

I would like to see an AST based macro system, where `mixin` can 
accept ASTs and the `macro` keyword is an attribute for function 
arguments that turns them into ASTs. With this, we don't need 
special syntax to create ASTs on the fly - we can have a simple 
`toAST` library function:

     AST(T) toAST(T)(macro(T) expr){
         return expr;
     }

Note that `expr` is of type `AST(T)` - `macro` converts arguments 
of type `T` to `AST(T)` just like `lazy` converts arguments of 
type `T` to `T delegate()`.


The OP's function macro will look like this:

     AST(void) debugLog(T)(macro(T) expr){
         auto printStatement=toAST(writeln(expr.toString()));
         return new AST!(void)(printStatement,expr);
     }

     mixin(debugLog(x+10));


More information about the Digitalmars-d mailing list