On Thursday, 29 November 2012 at 02:34:11 UTC, Walter Bright wrote:
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.

While more complex, would it be possible to declare which imported modules can be constructed after the current one? That allows catching any other unintended cyclic imports. For example:

static this {
  pragma(cyclic_import, b);
  // code that does not depend on
  // static constructor(s) in module b
}

Reply via email to