order of static constructor execution
Robert Clipsham
robert at octarineparrot.com
Fri Mar 12 08:44:44 PST 2010
On 12/03/10 02:42, Walter Bright wrote:
> Currently, it is performed as a strictly "depth-first" traversal of the
> graph defined by the import statements. As we've been discussing here,
> this works great until one has circular imports, meaning the depth-first
> graph has a loop in it.
>
> The current behavior on detecting a loop is to quit with an error message.
>
> The problems are:
>
> 1. The cycles are not easily gotten rid of when they are the result of
> template mixins.
>
> 2. Trying to analyze the static constructors to see what the
> dependencies actually are is fraught with unsolvable problems.
>
>
> So, I propose the following:
>
> 1. Attempt the depth-first traversal of the static constructors.
>
> 2. If a loop is detected, rather than issuing an error message, simply
> arbitrarily pick one order and continue constructing.
>
>
> The mitigating rationale is that modules that import each other are
> presumably written by the same person or team, and so that person is in
> the best place to explicitly control dependencies themselves.
>
>
> I'm not happy with this solution, but it seems to be the best compromise
> I can come up with.
>
> What do you think?
I don't know the full situation, or even if this will help, but maybe
something like the following could help?
a.d:
----
module a;
import b;
Foo fooA;
static this()
{
fooA = bar();
}
----
b.d:
----
module b;
import a;
class Foo { }
Foo bar()
{
return new Foo;
}
Foo fooB;
pure static this()
{
fooB = bar();
}
----
Here the pure notates that the static constructor doesn't not depend on
any other modules (it's pure at module scope rather than function
scope). If a module's static ctor is pure it doesn't matter what order
it is executed in, so can be decided arbitrarily by the compiler. Doing
this means you can have cyclic dependencies both with static
constructors, without worrying about cyclic dependencies. It does
however mean that you wouldn't be able to use functions from module C,
it's better than the current situation though.
More information about the Digitalmars-d
mailing list