How to get to a class initializer through introspection?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Aug 4 03:47:44 UTC 2020


On 8/3/20 10:35 PM, Adam D. Ruppe wrote:
> On Tuesday, 4 August 2020 at 02:09:13 UTC, Andrei Alexandrescu wrote:
>> Oh, yes forgot about that important efficiency matter. Yes it does 
>> look like we need a __trait after all.
> 
> How do you think it should be exposed? An initialization function the 
> compiler generates? Some kind of range of ranges? (so like a 
> representation of "4 bytes of zero, 5000 bytes uninitialized, 4 bytes of 
> 4s". Though at that point a .tupleof may make more sense, just gotta 
> account for hidden fields too like the class vtable pointer.)
> 
> I'm thinking the function is probably the best though then tweaking it 
> becomes a compiler patch again. It would also want to be guaranteed to 
> be inlined probably.
> 
> I don't know though, it is kinda tricky to actually account for those 
> =void things.

I'm an introspection junkie so I just wish I got access to the initial 
value of every field. Come to think of it - a litmus test for 
introspection is that you can print out during compliation an exact 
definition of any data structure in the program. That is, you should be 
able to write a function:

printDefinition(T)

such that during compilation, given:

struct S {
     int a = 42;
     immutable double b;
     string c = "hi";
     char[100] c = void;
     void func(double);
     ...
}

then printDefinition!T would output S during compilation. (Without 
method bodies, but with all qualifiers and attributes and alignment 
directives and all.)

 From that perspective, clearly there's a need for 
__traits(initializerString, T, "c") or __traits(initializerString, T, 
2). It always returns a string containing the initializer value ("void" 
for void) so code can either print it or mixin it.

For S, __traits(initializerString, T, 0) returns "42", 
__traits(initializerString, T, 2) and __traits(initializerString, T, 
"c") return "\"hi\"", and so on.



More information about the Digitalmars-d mailing list