Commit 278c32976e

Veikka Tuominen <git@vexu.eu>
2022-10-28 20:01:12
parser: add helpful error for extra = in variable initializer
Closes #12768
1 parent 5321afc
Changed files (3)
lib/std/zig/Ast.zig
@@ -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,
lib/std/zig/parse.zig
@@ -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(.{
lib/std/zig/parser_test.zig
@@ -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 {