One step out of the TypeInfo stalemate

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Jul 28 03:26:01 UTC 2020


On 7/26/20 11:31 PM, Andrei Alexandrescu wrote:
> On 7/25/20 12:34 PM, Andrei Alexandrescu wrote:
>> I think this has been attempted before. The TypeInfo* classes in 
>> object.d are one gnarly thing after another:
>>
>> https://github.com/dlang/druntime/blob/master/src/object.d
>>
>> Very poor usefulness to real estate ratio, ugly and inefficient 
>> implementation, etc. etc.
>>
>> One simple step out of this would be to replace TypeInfo_Struct with a 
>> template TypeInfo(T) if (is(T == struct)). Then expressions such as 
>> `typeid(MyStruct)` would be lowered to 
>> `.object.__getTypeInfo!MyStruct()`. That function uses a singleton 
>> with lazy allocation.
>>
>> That means for all structs the compiler does not need to generate 
>> TypeInfo_Struct objects, and the implementation of the primitives is 
>> simpler and more efficient.
>>
>> We can't do exactly this for classes because typeid(obj) is dynamic, 
>> so it requires a virtual call. But there are other ideas we can use 
>> there as well.
> 
> Progress on this:
> 
> https://github.com/dlang/dmd/pull/11459/
> https://github.com/dlang/druntime/pull/3172
> 
> Next step is to templatize the associative array primitives, which 
> resort to horrendous tricks exactly because they lack static type 
> information.

Walter and I figured starting with Typeinfo_Struct is difficult, so we 
scaled down to the simplest: typeid(int). Take a look at:

https://github.com/dlang/druntime/pull/3174

The idea is to lower typeid(int) to __typeid!(int) and it all works 
nicely. We can then start generalizing from there. The code generation, 
putting the object in storage with static duration, all is done with 
standard language mechanisms.

One unexpected perk is that some functions now work during compilation. 
For example, with the old implementation this doesn't work:

static assert(typeid(int).toString == "int");

However, this does work:

static assert(__typeid!int.toString == "int");

which is pretty awesome. Others do, too - take a look at the unittest.


More information about the Digitalmars-d mailing list