Skip to content

Commit

Permalink
Format multi-line braces blocks using do/end
Browse files Browse the repository at this point in the history
  • Loading branch information
RX14 committed Jun 5, 2017
1 parent 5af6fb7 commit a8c88b8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
5 changes: 4 additions & 1 deletion spec/compiler/formatter/formatter_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ describe Crystal::Formatter do
assert_format "foo do # hello\nend", "foo do # hello\nend"
assert_format "foo{}", "foo { }"
assert_format "foo{|x| x}", "foo { |x| x }"
assert_format "foo{|x|\n x}", "foo { |x|\n x\n}"
assert_format "foo{|x|\n x}", "foo do |x|\n x\nend"
assert_format "foo &.bar", "foo &.bar"
assert_format "foo &.bar( 1 , 2 )", "foo &.bar(1, 2)"
assert_format "foo.bar &.baz( 1 , 2 )", "foo.bar &.baz(1, 2)"
Expand Down Expand Up @@ -947,6 +947,9 @@ describe Crystal::Formatter do
assert_format "foo { | a, ( b , c, ), | a + b + c }", "foo { |a, (b, c)| a + b + c }"
assert_format "foo { | a, ( _ , c ) | a + c }", "foo { |a, (_, c)| a + c }"

assert_format "foo do |a| 2 end", "foo do |a|\n 2\nend"
assert_format "foo { |a|\n 2\n}", "foo do |a|\n 2\nend"

assert_format "def foo\n {{@type}}\nend"

assert_format "[\n 1, # foo\n 3,\n]"
Expand Down
16 changes: 9 additions & 7 deletions src/compiler/crystal/tools/formatter.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1243,13 +1243,13 @@ module Crystal
end
end

def format_nested_with_end(node, column = @indent, write_end_line = true)
def format_nested_with_end(node, column = @indent, write_end_line = true, force_end = false)
skip_space(column + 2)

if @token.type == :";"
if node.is_a?(Nop)
skip_semicolon_or_space_or_newline
check_end
check_end unless force_end
write "; end"
next_token
return false
Expand All @@ -1259,12 +1259,12 @@ module Crystal
end

format_nested node, column, write_end_line: write_end_line
format_end(column)
format_end(column, force_end: force_end)
end

def format_end(column)
def format_end(column, force_end = false)
skip_space_or_newline(column + 2, last: true)
check_end
check_end unless force_end
write_indent(column)
write "end"
next_token
Expand Down Expand Up @@ -2480,11 +2480,13 @@ module Crystal
next_token_skip_space_or_newline
end

if @token.keyword?(:do)
needs_do_block = node.location.try(&.line_number) != node.end_location.try(&.line_number)

if @token.keyword?(:do) || (@token.type == :"{" && needs_do_block)
write " do"
next_token_skip_space
body = format_block_args node.args, node
format_nested_with_end body
format_nested_with_end body, force_end: needs_do_block
elsif @token.type == :"{"
write "," if needs_comma
write " {"
Expand Down

0 comments on commit a8c88b8

Please sign in to comment.