Do you want to help me fix static AA initialization?

RazvanN razvan.nitu1305 at gmail.com
Thu Jul 27 14:06:16 UTC 2023


On Tuesday, 25 July 2023 at 13:24:32 UTC, Steven Schveighoffer 
wrote:
> On 7/25/23 4:45 AM, RazvanN wrote:
>> 
>> Maybe this has been addressed in previous discussions, but why 
>> not rewrite:
>> 
>> ```d
>> int[string] b = ["mimi" : 2];
>> ```
>> 
>> to
>> 
>> ```d
>> int[string] b;
>> 
>>      static this()
>>      {
>>          b = ["mimi" : 2];
>>      }
>>      ```
>> 
>> I know that we have problems with cycle detection in module 
>> constructors, but assuming this will be fixed by Adam's 
>> proposal, this seems like a lot easier to implement and does 
>> not stress compilation time.
>> 
>
> Yes, this can be done. We can even mark the static ctor as 
> standalone, so it doesn't participate in cycles.
>
> And then in the future if we can find a way to do it during 
> CTFE, then it can be seamlessly changed.
>
> There are some hairy aspects -- like what you do if the 
> initialized value is done in a function call or the AA is a 
> member of a type instead of the thing being initialized, but 
> those are surmountable.
>
> Great idea!
>
> -Steve

There are some issues with this proposal though:

- accepting the static initializer leaves the impression that the 
initializer code is CTFEable when actually it could be not.
- immutable AAs should be usable at compile time, whereas with 
this proposal they would not be because they are initialized at 
runtime (we could just say you can slap `enum` instead of 
`immutable` to make it work, but that's not how language design 
should be fone.)
- there is no way that I know where static variables inside 
function scopes can be accessed from the outside.

Overall, this starts to look like a hack.


More information about the Digitalmars-d mailing list