Metaprogramming without templates

Stefan Koch uplink.coder at googlemail.com
Thu Jun 24 11:53:00 UTC 2021


On Sunday, 20 June 2021 at 22:51:06 UTC, Stefan Koch wrote:
> [snip]
> And I assume I'll first have to make advances on dealing with 
> complicated forward reference graphs before I can show anything 
> neat.

No more assumptions now I have proof :P

check the following example:
```D
import core.reflect.type;
import core.reflect.node;
import core.reflect.decl;

// reflection functions may ne annotated with @(core.reflect)
// to prevent code generation for them
// in this case the function itself does not call reflection 
functions
// such as nodeFromName. but if it did we would have to prevent 
codegen
// as nodeFromName does not have a function body
@(core.reflect) immutable(Type) getType(immutable Node node)
{
   if (immutable vd = cast(immutable VariableDeclaration)node)
   {
      return vd.type;
   }

   return null;
}

int[2] myArr;
static immutable arr_node = nodeFromName("myArr");

static immutable arr_type =
   cast(immutable TypeArray)
     (cast(immutable VariableDeclaration)arr_node).type;

static assert(arr_type.identifier == "int[2]"
   && arr_type.nextOf.identifier == "int"
   && arr_type.dim == 2
);

pragma(msg, "typeof(x).stringof before decl: '", 
nodeFromName("x").getType().identifier, "'");
typeof(myArr)* x;
pragma(msg, "typeof(x).stringof after decl: '", 
nodeFromName("x").getType().identifier, "'");
```
The output of this will be:
```D
typeof(x).stringof before decl: 'typeof(myArr)*'
typeof(x).stringof after decl: 'int[2]*'
```

as you can see the implicitly forward declared symbol `x` 
"changes" or rather "refines" and resolves it's type after it has 
been actually declared.
I hope I can find a way to compute a schedule that will leave a 
symbol in a stable state as reflection is not supposed to be able 
to modify anything.


More information about the Digitalmars-d mailing list