Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enforce static constructors lexical order in a module to respect their use order #18822

Open
dlangBugzillaToGithub opened this issue Apr 27, 2014 · 0 comments

Comments

@dlangBugzillaToGithub
Copy link

bearophile_hugs reported this on 2014-04-27T22:04:48Z

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

Description

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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant