Fixing cyclic import static construction problems

Walter Bright newshound2 at digitalmars.com
Wed Nov 28 18:34:08 PST 2012


For discussion:

Cyclical Imports

Problem:

---- a.d ----
     module a;
     import b;
     static this () { ... }
---- b.d ----
     module b;
     import a;
     static this() { ... }
-------------

Static constructors for a module are only run after static constructors
for all its imports are run. Circular imports, such as the above, are
detected at run time and the program is aborted.

This can in general be solved by moving the static constructor(s) into
a third module, c.d, which does not import a or b. But, people find this
to be unnatural.

Proposed Solution:

Add a pragma,

     pragma(cyclic_imports);

This can appear anywhere in a module, and applies globally to that module.
It means that static constructors from imports that are not part of the 
cycle
are run first, and that the static constructor for this module may be 
run before
the static constructors of other modules that are part of the cycle.

If any static constructors in such a module with the pragma have
the @safe attribute, that is a compile time error.


More information about the Digitalmars-d mailing list