Fake global associative array literals
Jonathan M Davis
jmdavisProg at gmx.com
Sat Oct 29 07:37:24 PDT 2011
On Saturday, October 29, 2011 05:20:35 bearophile wrote:
> Nick Sabalausky:
> > You generally need to be very careful about adding module/static ctors,
> > because they can easily lead to the dreaded circular ctor runtime error.
> > So as nice as it would be to use AA initializers at the module-level,
> > this carries a hidden danger which could be a royal PITA to debug
> > (especially for D newbies), so I don't think it's a good thing to do.
>
> Second try. What about the lowering of:
>
> int[int] aa = [1:2, 3:4];
> void main() {}
>
>
> To (now the static this generated for this initialization is enforced to be
> pure):
>
> int[int] aa;
> pure static this() {
> aa = [1:2, 3:4];
> }
> void main() {}
>
>
> Is this enough to avoid the problems you talk about?
No. The presence of any static constructors of any kind within a module means
that it runs the risk of a circular depencency. If it manages to import
another module - directly or indirectly - which imports it, then your program
will throw an exception and terminate at runtime when it starts up. The
compiler cannot find such circular dependencies at compile time (I believe
because it could depend on what's linked in), and the only way to fix the
problem is to remove all of the static constructors in one of the modules.
There are some modules in Phobos which have create C functions which do the
job of static constructors and created separate, helper modules which call
those functions in their module constructors in order to avoid a circular
dependency. And that solution can't be done in cases where any of the
variables being intialized are const or immutable. It's a problem which is all
too easy to get into and a pain to fix. The issues with static constructors and
circular dependencies is one of the roughest pieces of D IMHO. Unfortunately,
no one has been able to come up with an acceptable means of fixing the problem.
Doing _any_ kind of lowering to a static constructor is bad news.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list