diff options
| author | LemonBoy <LemonBoy@users.noreply.github.com> | 2021-03-16 09:22:16 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-03-16 09:22:16 +0100 |
| commit | 5ecf8bddaeebf26ac6cd174f5f79e02ca243e501 (patch) | |
| tree | d4243fd724718867680c6b98e2731bb5257760f9 /lib/std | |
| parent | f16f25047c511cc5f468da57292a968555c4b791 (diff) | |
| download | zig-5ecf8bddaeebf26ac6cd174f5f79e02ca243e501.tar.gz zig-5ecf8bddaeebf26ac6cd174f5f79e02ca243e501.zip | |
zig fmt: Respect line breaks in struct default value decls
Bring this in line with how variable declarations are handled.
Open a new indentation level for the initialization expression to handle
nested expressions like blocks.
Closes #7618
Diffstat (limited to 'lib/std')
| -rw-r--r-- | lib/std/zig/parser_test.zig | 25 | ||||
| -rw-r--r-- | lib/std/zig/render.zig | 25 |
2 files changed, 48 insertions, 2 deletions
diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index a83e95e431..bc01fa3324 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -4,6 +4,31 @@ // The MIT license requires this copyright notice to be included in all copies // and substantial portions of the software. +test "zig fmt: respect line breaks in struct field value declaration" { + try testCanonical( + \\const Foo = struct { + \\ bar: u32 = + \\ 42, + \\ bar: u32 = + \\ // a comment + \\ 42, + \\ bar: u32 = + \\ 42, + \\ // a comment + \\ bar: []const u8 = + \\ \\ foo + \\ \\ bar + \\ \\ baz + \\ , + \\ bar: u32 = + \\ blk: { + \\ break :blk 42; + \\ }, + \\}; + \\ + ); +} + // TODO Remove this after zig 0.9.0 is released. test "zig fmt: rewrite inline functions as callconv(.Inline)" { try testTransform( diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 9fe9b96f00..3b38091994 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -1159,8 +1159,29 @@ fn renderContainerField( try renderToken(ais, tree, rparen_token, .space); // ) } const eq_token = tree.firstToken(field.ast.value_expr) - 1; - try renderToken(ais, tree, eq_token, .space); // = - return renderExpressionComma(gpa, ais, tree, field.ast.value_expr, space); // value + const eq_space: Space = if (tree.tokensOnSameLine(eq_token, eq_token + 1)) .space else .newline; + { + ais.pushIndent(); + try renderToken(ais, tree, eq_token, eq_space); // = + ais.popIndent(); + } + + if (eq_space == .space) + return renderExpressionComma(gpa, ais, tree, field.ast.value_expr, space); // value + + const token_tags = tree.tokens.items(.tag); + const maybe_comma = tree.lastToken(field.ast.value_expr) + 1; + + if (token_tags[maybe_comma] == .comma) { + ais.pushIndent(); + try renderExpression(gpa, ais, tree, field.ast.value_expr, .none); // value + ais.popIndent(); + try renderToken(ais, tree, maybe_comma, space); + } else { + ais.pushIndent(); + try renderExpression(gpa, ais, tree, field.ast.value_expr, space); // value + ais.popIndent(); + } } fn renderBuiltinCall( |
