From f095adc67efd91225419cec61da3ea0fd59f3b66 Mon Sep 17 00:00:00 2001 From: Ary Borenszweig Date: Tue, 29 Sep 2020 12:05:34 -0300 Subject: [PATCH] Formatter: handle comment before do in a separate line (#9762) --- spec/compiler/formatter/formatter_spec.cr | 13 ++++++++++++ src/compiler/crystal/tools/formatter.cr | 25 ++++++++++++++++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/spec/compiler/formatter/formatter_spec.cr b/spec/compiler/formatter/formatter_spec.cr index 176de863ef03..e9b98f9d17c4 100644 --- a/spec/compiler/formatter/formatter_spec.cr +++ b/spec/compiler/formatter/formatter_spec.cr @@ -1728,4 +1728,17 @@ describe Crystal::Formatter do def bar end CODE + + assert_format <<-CODE + foo 1, # comment + do + end + CODE + + assert_format <<-CODE + foo 1, # comment + # bar + do + end + CODE end diff --git a/src/compiler/crystal/tools/formatter.cr b/src/compiler/crystal/tools/formatter.cr index c3f77c2fb72d..1ee111617518 100644 --- a/src/compiler/crystal/tools/formatter.cr +++ b/src/compiler/crystal/tools/formatter.cr @@ -2906,18 +2906,37 @@ module Crystal old_inside_call_or_assign = @inside_call_or_assign @inside_call_or_assign = 0 + comma_before_comment = false + if @token.type == :"," - needs_comma = true - next_token_skip_space_or_newline + next_token + next_token if @token.type == :SPACE + if @token.type == :COMMENT + write "," + needs_comma = false + comma_before_comment = true + @indent += 2 + else + needs_comma = true + end + skip_space_or_newline + @indent -= 2 if comma_before_comment end if @token.keyword?(:do) - write " do" + if comma_before_comment + @indent += 2 + write_indent + else + write " " + end + write "do" next_token_skip_space body = format_block_args node.args, node old_implicit_exception_handler_indent, @implicit_exception_handler_indent = @implicit_exception_handler_indent, @indent format_nested_with_end body @implicit_exception_handler_indent = old_implicit_exception_handler_indent + @indent -= 2 elsif @token.type == :"{" write "," if needs_comma write " {"