[Issue 23983] Better error message when brace missing after `else`

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Jun 13 07:33:00 UTC 2023


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

RazvanN <razvan.nitu1305 at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |razvan.nitu1305 at gmail.com

--- Comment #6 from RazvanN <razvan.nitu1305 at gmail.com> ---
(In reply to ryuukk_ from comment #5)
> > A human could guess the problem is at line 8, but formally, the else branch is not required to have braces, and the } after the else branch could close the main function. 
> 
> You don't understand, let me bring you my project and the problem that led
> me to create this issue
> 
> https://gist.github.com/ryuukk/a4580ef154bf7801670e02a13f760858
> 
> 
> ```
> projects/game/context.d(566,1): Error: unmatched closing brace
> ```
> 
> 
> Try to find where the problem is
> 
> 
> 
> > I understand and agree, I'm just wondering how the compiler could algorithmically find out the problem is likely at line 8. Perhaps it could take note of the mismatched indentation of the closing brace after else, and report that once it encounters a missing brace error.
> 
> I don't know, i am not a compiler developer, my role is to report issues i
> encounter

You are right for complaining about this. However, what Dennis is pointing out
is that this code is perfectly fine:

void main()
{
    int stuff = 0;
    version (Posix)
    {
        stuff++;
    }
    else
        stuff++;
}

So, the compiler parses this and has no complaints. Next, you add another
brace:

void main()
{
    int stuff = 0;
    version (Posix)
    {
        stuff++;
    }
    else
        stuff++;
}
}

The compiler sees this code as being valid up until the last brace. Then it
tries to consume the next token which is another curly brace so it just errors
and says that you have an unmatched closing brace. In this scenario, it is
impossible for the compiler to go back and rescan previous tokens to try and
better understand how the braces were meant to be used. Even if it did, your
code up to the problematic last brace is perfectly valid. Moreover, look at C:

void main()
{
    int a;
    if (1) 
    {}  
    else
        a = 2;                                                                  
}
}    // line 9

This code yields:
gcc: test.c:9:1: error: expected identifier or ‘(’ before ‘}’ token
clang: test.c:9:1: error: extraneous closing brace ('}')

Which is the same thing the D compiler is complaining about.

So, although I understand your point, as Dennis pointed out there is no
algorithmic way in which what you are asking for can be done.

--


More information about the Digitalmars-d-bugs mailing list