Fun determining the number of parameters using core reflect

Stefan Koch uplink.coder at googlemail.com
Sat Sep 11 08:48:34 UTC 2021


Hi there,

I've just been wanted to know if a particular local variable has 
is pointer taken inside a function.
i.e. whether it's aliased.

In order to reflect on that I would have to look at where it is 
defined i.e. reflect on the lexical parent which is possible but 
is currently disabled by default since it's expensive.

So I wondered if I could just get the parent function node inside 
my reflection function, which works since I can get the string of 
the function I am in.

After a bit of tinkering I arrived at the following code.

Enjoy!

And please feel free to ask questions and suggest improvements!

```
import core.reflect.reflect;
int f()
{
     int x;
     static assert(nParameters == 0);
     g(&x);
     return x;
}
int f2(int x, float y)
{
     static assert(nParameters == 2);
     return x;
}

void g(int* x) {}

@(core.reflect) uint nParameters(immutable string fName = 
__FUNCTION__, immutable Scope _scope = currentScope())
{
     auto F = cast(const FunctionDeclaration)
         nodeFromName(fName, ReflectFlags.NoParent | 
ReflectFlags.NoFunctionbody, _scope);
     uint params = cast(uint)F.type.parameterTypes.length;
     return params;
}
```


More information about the Digitalmars-d mailing list