Error about constructor calls in loops/labels, but there are no loops and labels?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun May 20 00:05:39 UTC 2018


On Saturday, May 19, 2018 22:54:16 Yuxuan Shui via Digitalmars-d wrote:
> On Thursday, 17 May 2018 at 20:32:23 UTC, Steven Schveighoffer
>
> wrote:
> > On 5/17/18 4:25 PM, DarkHole wrote:
> >> On Thursday, 17 May 2018 at 20:02:19 UTC, Steven Schveighoffer
> >>
> >> wrote:
> >>> On 5/17/18 3:55 PM, DarkHole wrote:
> >>>> This strange code - https://run.dlang.io/is/BKgv49 - fails
> >>>> with error "Error: constructor calls not allowed in loops or
> >>>> after labels", but there is no loops or labels.
> >>>
> >>> Switch cases are labels.
> >>
> >> But why?
> >
> > You mean why is it an error? Probably because the compiler
> > needs to guarantee you are calling the super constructor, and
> > it can't figure out the flow when it sees labels/loops. Not
> > that it's always impossible, but it's likely a complication the
> > compiler devs don't want to deal with.
> >
> > -Steve
>
> Why isn't the compiler doing proper flow analysis? Is it that
> just no one bothered to implement it?

As I understand it, in general, Walter is against doing much in the way of
flow analysis, because it tends to become very difficult to get right in all
cases and results in situations where the programmer is forced to do
something in order to make the compiler shut up - e.g. in Java, you're
forced to initialize all variables, and it's not uncommon that you have to
initialize variables when you can clearly see that it shouldn't be
necessary, but the compiler isn't smart enough to see that. Also, if D
started use more flow analysis, then the exact rules of the flow analysis
would have to be in the spec and set in stone, or you end up with code
compiling on one compiler but not another. So, given issues like these
Walter has taken the approach of trying to avoid doing much where flow
analysis would be required by the spec.

In the case of initialization, D's approach is to default-initialize
evertything and then let the optimizer optimize out unnessary
initializations where it can, which avoids the problem that Java has and
eliminated the need to embed the flow analysis rules in the spec. And in
general, the places that D does much in the way of flow analysis is in the
optimization step where the compiler is free to change an improve how it
does flow analysis. There are a few places wheree it's forced to do basic
flow analysis (e.g. in constructors in cases like you ran into here), but in
such cases, it pretty much always sticks to simple rules so that the flow
analysis does not have to be complicated.

- Jonathan M Davis



More information about the Digitalmars-d mailing list