Get the code of any D-entity as string?

sighoya sighoya at gmail.com
Sun Dec 27 12:13:14 UTC 2020


On Saturday, 26 December 2020 at 21:45:41 UTC, Basile B. wrote:
> struct E {int a;}
> struct S
> {
>     ulong[] a;
>     @E(0) const int b;
>     void v() const {}
>     void v(int) const {}
> }
>
> string getDeclaration(T)()
> if (is(T == struct))
> {
>     import std.traits, std.meta;
>     string result = "struct " ~ T.stringof ~ " {\n";
>     static foreach (m; __traits(allMembers, T))
>     {{
>         static if (isCallable!(__traits(getMember, T, m)))
>             alias sym = __traits(getOverloads, T, m);
>         else
>             alias sym = AliasSeq!(__traits(getMember, T, m));
>         static foreach (s; sym)
>         {
>             result ~= "    ";
>             static foreach (a; __traits(getAttributes, s))
>                 result ~= "@" ~ a.stringof ~ " ";
>             static if (is(typeof(s)))
>                 result ~= typeof(s).stringof ~ " " ~ m ~ ";\n";
>         }
>     }}
>     result ~= "}";
>     return result;
> }
>
> pragma(msg, getDeclaration!S);
> ---

Thanks a lot, retrieving type declarations as string is better 
than nothing.
But it is still not enough, for instance retrieving the 
expressions of struct fields as string and also recursively 
resolving the expressions of the variables in the string 
expression as string.

This is also a limitation in Nim macros, I think, you can't 
capture values outside the input scope.


More information about the Digitalmars-d-learn mailing list