The spec states under "Constructors" that "It is illegal for constructors to mutually call each other", providing a code snippet similar to the following as a showcase: class Foo { this() { this(1); } this(int i) { this(); } // illegal, cyclic constructor calls } void main() { Foo foo = new Foo(); } Yet, this code compiles fine, failing at runtime due to a stack overflow. If the compiler is not meant to detect this, the restriction seems redundant - such calls will obviously fail at runtime just as though the constructors were normal functions, which do not suffer from such a restriction. If the compiler should, however, detect this, then it is a bug that it currently does not.
There is no way, in the general case, for the compiler to detect this.
Why not? Java does it. And "this" is bound at static time, not and runtime, and at static time you have all the information needed to detect cycles.
Because this may be declared as: this(); meaning it's body appears elsewhere. Also, things that appear to be cycles in static analysis may not be at runtime, like recursive functions.
If it's not possible just remove it from the spec. Why was it there in the first place?
1. Java doesn't allow separate compilation of constructors. 2. Java doesn't allow any flow control before other constructors are called.
(In reply to comment #4) > If it's not possible just remove it from the spec. Why was it there in the > first place? > Some parts of the spec can be read as "The language is not required to work correctly if you do ____. If you do and "things" happen, it's your error."
Therein lies half the problem. The spec should make a clear distinction between things that are actually illegal, things that cause undefined behaviour and things that the compiler may decide are errors if it's clever enough. Moreover, I'd read "mutually calling" as meaning that a loop exists in which constructors call which others, regardless of whether the calls can actually loop at runtime.
I disagree. I think it is valid to say that something is both illegal and that it result in undefined behavior. I think that somewhere it is said, for example, that it is /illegal/ to have code depend on order of evaluation (this can't be checked, the halting problem can be found in there). Maybe the distinction should be made between things that are illegal and the compiler is required to reject and things that are still illegal but that it needn't detect.
https://github.com/D-Programming-Language/d-programming-language.org/commit/d26103e11b8af546e4bfac71c412a0ecf02aac5d
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル