diff --git a/releasenotes.md b/releasenotes.md index a104edf7f..cfed0afe6 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -17,6 +17,7 @@ - Improve error message when using ',' in struct declarations. #1920 - Compile time array assign ops, e.g. `$c[1] += 3` #1890. - Add `inline` to enums #1819. +- Cleaner error message when missing comma in struct initializer #1941. ### Fixes - Fix issue requiring prefix on a generic interface declaration. diff --git a/src/compiler/parse_expr.c b/src/compiler/parse_expr.c index 6c593c0cf..cc49aba88 100644 --- a/src/compiler/parse_expr.c +++ b/src/compiler/parse_expr.c @@ -138,6 +138,10 @@ inline Expr *parse_precedence_with_left_side(ParseContext *c, Expr *left_side, P if (precedence > token_precedence) break; // LHS may be poison. if (!expr_ok(left_side)) return left_side; + + // Special rule to prevent = {}. + if (tok == TOKEN_DOT && left_side->expr_kind == EXPR_INITIALIZER_LIST) break; + // See if there is a rule for infix. ParseFn infix_rule = rules[tok].infix; // Otherwise we ran into a symbol that can't appear in this position. @@ -912,7 +916,11 @@ Expr *parse_initializer_list(ParseContext *c, Expr *left) } designated = 0; } - CONSUME_OR_RET(TOKEN_RBRACE, poisoned_expr); + if (!try_consume(c, TOKEN_RBRACE)) + { + PRINT_ERROR_HERE("A comma or '}' was expected here."); + return poisoned_expr; + } RANGE_EXTEND_PREV(initializer_list); if (designated == 1) { diff --git a/src/compiler/parse_global.c b/src/compiler/parse_global.c index cc99e0d75..4739059b1 100644 --- a/src/compiler/parse_global.c +++ b/src/compiler/parse_global.c @@ -2393,6 +2393,11 @@ static inline Decl *parse_enum_declaration(ParseContext *c) // Allow trailing ',' if (!try_consume(c, TOKEN_COMMA)) { + if (tok_is(c, TOKEN_CONST_IDENT)) + { + PRINT_ERROR_HERE("It looks like you forgot a comma before this identifier."); + return poisoned_decl; + } EXPECT_OR_RET(TOKEN_RBRACE, poisoned_decl); } } diff --git a/test/test_suite/enumerations/enum_missing_comma.c3 b/test/test_suite/enumerations/enum_missing_comma.c3 new file mode 100644 index 000000000..d03e3e7cc --- /dev/null +++ b/test/test_suite/enumerations/enum_missing_comma.c3 @@ -0,0 +1,5 @@ +enum Abc +{ + FOO + BAR // #error: It looks like you forgot a comma +} diff --git a/test/test_suite/initialize/initializer_access.c3 b/test/test_suite/initialize/initializer_access.c3 new file mode 100644 index 000000000..f59bf36f1 --- /dev/null +++ b/test/test_suite/initialize/initializer_access.c3 @@ -0,0 +1,10 @@ +module test; +struct Abc +{ + int[2] a; + int b; +} +fn int main() +{ + Abc a = { .a = {} .b = 3 }; // #error: A comma or '}' was expected here. +}