static this sucks, we should deprecate it

Steven Schveighoffer schveiguy at
Thu May 28 19:18:32 PDT 2009

On Thu, 28 May 2009 21:41:01 -0400, Ary Borenszweig <ary at>  

> The thing is, I've been using Java for more than 7 years now and I never  
> got any error because of intialization dependency. It would be nice to  
> turn that check off in D and see the results. Maybe no one will complain  
> about it.
> (Or maybe it was added because someone complained about it, some years  
> ago? I don't know...)

You are probably right that most of the time static initializers do not  
depend on external variables.  But it might be best to start with the  
conservative option and move towards the compromise than the other way  
around.  I think a reasonable first step is to implement some better  
runtime checks.

For example, the compiler could put wrappers around static this calls:

   // mode is initted to 0 by the runtime.
   static int mode;
   if(mode == 0)
     mode = 1;
     static_this(); // calls the static initializers of the module
     mode = 2;
   else if(mode == 1) // a dependency of this module called this module's  
     assert(false, "circular dependency!");

And put calls to a dependent module's _wrapper function in other modules  
when they are about to access static variables in that other module.

for example:

import f2;

int x;
int n;
static this()
   n = 4;
   x = y;

import f1;

int y;
static this()
   y = 5;

f1.d's static this becomes:

static this()
   x = y;

and f2.d's static this remains the same because it doesn't have any  
dependencies.  Then the compiler can call the static initializers in any  
order, and they do the right thing.

This still wouldn't be perfect, because you may get incorrect assertions,  
but it's better than what we have now.


More information about the Digitalmars-d mailing list