Skip to content

Commit 07af861

Browse files
authored
Add multi-line formatting support to Generic formatter visitor (#16430)
1 parent 9af0735 commit 07af861

File tree

2 files changed

+12
-17
lines changed

2 files changed

+12
-17
lines changed

spec/compiler/formatter/formatter_spec.cr

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,13 @@ describe Crystal::Formatter do
143143
assert_format "NamedTuple(\n a: Int32,)", "NamedTuple(\n a: Int32,\n)"
144144
assert_format "class Foo\n NamedTuple(\n a: Int32,\n )\nend"
145145

146+
# Multi-line generic type with inline comments (issue #11328)
147+
assert_format "Tuple(\n Int32, # first\n String, # second\n)", "Tuple(\n Int32, # first\n String, # second\n)"
148+
assert_format "Tuple(\n Int32, # first\n String, # second\n Bool,\n)", "Tuple(\n Int32, # first\n String, # second\n Bool,\n)"
149+
assert_format "Tuple(\n Int32, # first\n String # adds trailing comma\n)", "Tuple(\n Int32, # first\n String, # adds trailing comma\n)"
150+
assert_format "Hash(\n String, # key\n Int32, # value\n)", "Hash(\n String, # key\n Int32, # value\n)"
151+
assert_format "Tuple(\n Int32,\n String\n)", "Tuple(\n Int32,\n String,\n)"
152+
146153
assert_format "::Tuple(T)"
147154
assert_format "::NamedTuple(T)"
148155
assert_format "::Pointer(T)"

src/compiler/crystal/tools/formatter.cr

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1205,15 +1205,14 @@ module Crystal
12051205
accept name
12061206
skip_space_or_newline
12071207

1208-
write_token :OP_LPAREN
1209-
skip_space
1210-
12111208
# Given that generic type arguments are always inside parentheses
12121209
# we can start counting them from 0 inside them.
12131210
old_paren_count = @paren_count
12141211
@paren_count = 0
12151212

12161213
if named_args = node.named_args
1214+
write_token :OP_LPAREN
1215+
skip_space
12171216
has_newlines, _, _ = format_named_args([] of ASTNode, named_args, @indent + 2)
12181217
# `format_named_args` doesn't skip trailing comma
12191218
if @paren_count == 0 && @token.type.op_comma?
@@ -1224,23 +1223,12 @@ module Crystal
12241223
write_indent
12251224
end
12261225
end
1226+
skip_space_or_newline if @paren_count == 0
1227+
write_token :OP_RPAREN
12271228
else
1228-
skip_space_or_newline
1229-
node.type_vars.each_with_index do |type_var, i|
1230-
accept type_var
1231-
if @paren_count == 0
1232-
skip_space_or_newline
1233-
if @token.type.op_comma?
1234-
write ", " unless last?(i, node.type_vars)
1235-
next_token_skip_space_or_newline
1236-
end
1237-
end
1238-
end
1229+
format_literal_elements(node.type_vars, :OP_LPAREN, :OP_RPAREN)
12391230
end
12401231

1241-
skip_space_or_newline if @paren_count == 0
1242-
write_token :OP_RPAREN
1243-
12441232
# Restore the old parentheses count
12451233
@paren_count = old_paren_count
12461234

0 commit comments

Comments
 (0)