www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 12667] New: Enforce static constructors lexical order in a

https://issues.dlang.org/show_bug.cgi?id=12667

          Issue ID: 12667
           Summary: Enforce static constructors lexical order in a module
                    to respect their use order
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Keywords: accepts-invalid, diagnostic
          Severity: enhancement
          Priority: P1
         Component: DMD
          Assignee: nobody puremagic.com
          Reporter: bearophile_hugs eml.cc

This was inspired by a problem found by "spec" in D.learn:
http://forum.dlang.org/thread/gjbhmzkohtmlthnoggzr forum.dlang.org


This reduced program:


struct Foo {
    static this() {
        Bar b;
        int x = b.data[0]; // RangeError
    }
}
struct Bar {
    static int[] data;
    static this() {
        data.length++;
    }
}
void main() {}


Gives with DMD 2.066alpha:

core.exception.RangeError test(4): Range violation


If you swap the position of the Foo and Bar classes in the module you receive
no errors.

As explained here: >Static constructors within a module are executed in the
lexical order in which they appear.<

http://dlang.org/class.html#StaticConstructor

So, if Foo depends on Bar then Bar static this must appear before Foo one.

A similar example:

struct Foo {
    static this() {
        Bar b;
        int x = b.data[0];
    }
}
struct Bar {
    immutable static int[] data;
    static this() {
        data.length++;
    }
}
void main() {}


So I suggest to introduce a little D breaking change (that probably is not
going to break a lot of code. In the shown case it just turns a run-time error
in a compile-time one): is it possible and a good idea to raise a compilation
error in such cases where code tries to use Bar static fields before bar static
this() has run? (Perhaps a more fine-grained error is useful, that tracks
single fields, to allow more flexible code of mutually initializing
constructors, or perhaps it's not necessary).

--
Apr 27 2014