From d44d2784e6a41ccd5549d4badea527a35169945d Mon Sep 17 00:00:00 2001 From: Raul Leal Date: Fri, 19 Apr 2019 20:27:42 +0100 Subject: [PATCH] zig-fmt: allow comptime blocks in containers (#2308) * zig-fmt: allow comptime blocks in containers * add test for comptime block in container --- std/zig/parse.zig | 29 +++++++++++++++++++++++++++++ std/zig/parser_test.zig | 15 +++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 96aec714a..42fa6d859 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -629,6 +629,35 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }); continue; }, + Token.Id.Keyword_comptime => { + const block = try arena.create(ast.Node.Block); + block.* = ast.Node.Block{ + .base = ast.Node{ .id = ast.Node.Id.Block }, + .label = null, + .lbrace = undefined, + .statements = ast.Node.Block.StatementList.init(arena), + .rbrace = undefined, + }; + + const node = try arena.create(ast.Node.Comptime); + node.* = ast.Node.Comptime{ + .base = ast.Node{ .id = ast.Node.Id.Comptime }, + .comptime_token = token_index, + .expr = &block.base, + .doc_comments = comments, + }; + try container_decl.fields_and_decls.push(&node.base); + + stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; + try stack.append(State{ .Block = block }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &block.lbrace, + }, + }); + continue; + }, Token.Id.RBrace => { if (comments != null) { ((try tree.errors.addOne())).* = Error{ .UnattachedDocComment = Error.UnattachedDocComment{ .token = token_index } }; diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 434969948..82607dbbe 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -2118,6 +2118,21 @@ test "zig fmt: error return" { ); } +test "zig fmt: comptime block in container" { + try testCanonical( + \\pub fn container() type { + \\ return struct { + \\ comptime { + \\ if (false) { + \\ unreachable; + \\ } + \\ } + \\ }; + \\} + \\ + ); +} + const std = @import("std"); const mem = std.mem; const warn = std.debug.warn;