parser: add helpful error for extra = in variable initializer

Closes #12768
This commit is contained in:
Veikka Tuominen 2022-10-28 21:01:12 +03:00
parent 5321afcf9c
commit 278c32976e
3 changed files with 24 additions and 1 deletions

View File

@ -359,6 +359,9 @@ pub fn renderError(tree: Ast, parse_error: Error, stream: anytype) !void {
.expected_var_const => {
return stream.writeAll("expected 'var' or 'const' before variable declaration");
},
.wrong_equal_var_decl => {
return stream.writeAll("variable initialized with '==' instead of '='");
},
.expected_token => {
const found_tag = token_tags[parse_error.token + @boolToInt(parse_error.token_is_prev)];
@ -2583,6 +2586,7 @@ pub const Error = struct {
invalid_ampersand_ampersand,
c_style_container,
expected_var_const,
wrong_equal_var_decl,
zig_style_container,
previous_field,

View File

@ -812,7 +812,18 @@ const Parser = struct {
const align_node = try p.parseByteAlign();
const addrspace_node = try p.parseAddrSpace();
const section_node = try p.parseLinkSection();
const init_node: Node.Index = if (p.eatToken(.equal) == null) 0 else try p.expectExpr();
const init_node: Node.Index = switch (p.token_tags[p.tok_i]) {
.equal_equal => blk: {
try p.warn(.wrong_equal_var_decl);
p.tok_i += 1;
break :blk try p.expectExpr();
},
.equal => blk: {
p.tok_i += 1;
break :blk try p.expectExpr();
},
else => 0,
};
if (section_node == 0 and addrspace_node == 0) {
if (align_node == 0) {
return p.addNode(.{

View File

@ -5145,6 +5145,14 @@ test "zig fmt: make single-line if no trailing comma" {
);
}
test "zig fmt: variable initialized with ==" {
try testError(
\\comptime {
\\ var z: u32 == 12 + 1;
\\}
, &.{.wrong_equal_var_decl});
}
test "zig fmt: missing const/var before local variable" {
try testError(
\\comptime {