Getting the names of all the top-level functions in module
Stefan Koch
uplink.coder at googlemail.com
Tue Sep 21 15:18:01 UTC 2021
On Tuesday, 21 September 2021 at 15:07:35 UTC, Adam D Ruppe wrote:
> Here's one with param names:
>
> ----
>
> module qwe;
>
> struct FunctionInfo {
> string name;
> string[] paramNames;
> }
>
> enum FunctionInfo[] functionInfo(alias M) = ()
> {
> FunctionInfo[] res;
> foreach(memberName; __traits(derivedMembers, M))
> static if (is(typeof(__traits(getMember, M,
> memberName)) Params == __parameters)) {
> FunctionInfo fi = FunctionInfo(memberName);
> foreach(idx, param; Params)
> fi.paramNames ~= __traits(identifier,
> Params[idx .. idx + 1]);
> res ~= fi;
> }
> return res;
> }();
>
> void main() {
> import std.stdio;
> writeln(functionInfo!qwe);
> }
>
> void foo(int a, int b){}
>
```d
Here's the core.reflect version for that
struct FunctionInfo
{
string name;
string[] params;
}
@(core.reflect)
const(FunctionInfo)[] FunctionsInfoFromModule(string module_ =
__MODULE__,
ReflectFlags flags = ReflectFlags.NoMemberRecursion,
immutable Scope _scope = currentScope()
)
{
const(FunctionInfo)[] result;
auto mod_ = nodeFromName(module_, flags, _scope);
if (auto mod = cast(Module) mod_)
foreach(member;mod.members)
{
if (auto fd = cast(const FunctionDeclaration) member)
{
string[] paramNames;
foreach(p;fd.type.parameterTypes) //because that's
how dmd looks and I didn't smooth that part out yet. it's going
to be nicer in the future
{
paramNames ~= p.identfier; // TODO maybe rename
identifier to name?
}
result ~= FunctionInfo(fd.name, paramNames);
}
}
return result;
}
```
Alternatively you could of course just use the
`FunctionDeclaration` object ;)
As the information is already bundled.
More information about the Digitalmars-d
mailing list