Order of static this() execution?

drathier forum.dlang.org at fi.fo
Sun Feb 23 09:59:45 UTC 2020


I'm having some trouble with the order in which `static this()` 
runs. This is the order defined in the source file, numbered for 
convenience:
```
logInfo("static this 1 initialModel");
logInfo("static this 1 initialModel done");
logInfo("static this 2 array branchfactor");
logInfo("static this 2 array branchfactor done");
logInfo("static this 3 array shiftstep");
logInfo("static this 3 array shiftstep done");
logInfo("static this 4 cmd none [template:%s]", typeid(msg));
logInfo("static this 4 cmd none [template:%s] done", typeid(msg));
logInfo("static this 5 main");
logInfo("static this 5 main done");
```
It's also the same order that `-vcg-ast` outputs. However, at 
runtime, I'm consistently seeing this order, where 5 and 4 are 
swapped:
```
[main(----) INF] static this 1 initialModel
[main(----) INF] static this 1 initialModel done
[main(----) INF] static this 2 array branchfactor
[main(----) INF] static this 2 array branchfactor done
[main(----) INF] static this 3 array shiftstep
[main(----) INF] static this 3 array shiftstep done
[main(----) INF] static this 5 main
[main(----) INF] static this 5 main done
[main(----) INF] static this 4 cmd none 
[template:delm.output.MsgT]
[main(----) INF] static this 4 cmd none 
[template:delm.output.MsgT] done
```
which leads to segfaults later on since static this 5 reads 
variables set up by static this 4.

The spec says that "The static constructors are run in lexical 
order" https://dlang.org/spec/module.html#staticorder . Is 
lexical order the same as the order things are defined in the 
source file?

I'm running `DMD64 D Compiler v2.090.1` on macos 10.14.6, in case 
that matters. I'm seeing the same issue with LDC `(1.19.0) based 
on DMD v2.089.1 and LLVM 9.0.0`


More information about the Digitalmars-d-learn mailing list