Skip to content

Commit

Permalink
Handle emitting significant whitespace as well
Browse files Browse the repository at this point in the history
  • Loading branch information
Blacksmoke16 committed Dec 23, 2024
1 parent ad601d0 commit 79641c7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
15 changes: 9 additions & 6 deletions spec/compiler/parser/to_s_spec.cr
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
require "../../support/syntax"

private def expect_to_s(original, expected = original, emit_doc = false, file = __FILE__, line = __LINE__)
it "does to_s of #{original.inspect}", file, line do
private def expect_to_s(original, expected = original, emit_doc = false, file = __FILE__, line = __LINE__, focus = false)
it "does to_s of #{original.inspect}", file, line, focus: focus do
str = IO::Memory.new expected.bytesize

source = original
Expand Down Expand Up @@ -262,8 +262,7 @@ describe "ASTNode#to_s" do
expect_to_s "{%\n a = 1 %}", "{%\n a = 1\n%}"
expect_to_s "{% a = 1\n%}", "{% a = 1 %}"

# FIXME: Should respect significant whitespace
expect_to_s <<-'CR', <<-'CR'
expect_to_s <<-'CR', <<-CR
macro finished
{% verbatim do %}
{%
Expand All @@ -280,14 +279,16 @@ describe "ASTNode#to_s" do
{% verbatim do %}
{%
10



20
%}
{% end %}
end
CR

# FIXME: Should respect significant whitespace
expect_to_s <<-'CR', <<-'CR'
expect_to_s <<-'CR', <<-CR
macro finished
{% verbatim do %}
{%
Expand All @@ -303,6 +304,8 @@ describe "ASTNode#to_s" do
{% verbatim do %}
{%
10


20
%}
{% end %}
Expand Down
27 changes: 24 additions & 3 deletions src/compiler/crystal/syntax/to_s.cr
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,21 @@ module Crystal
true
end

private def add_whitespace_around(first_node_location : Location?, second_node_location : Location?, &) : Nil
# If any location information is missing, don't add any extra newlines.
if !first_node_location || !second_node_location
yield
return
end

# Only emit extra newlines. I.e. those more than the first handled via the Expressions visitor.
((second_node_location.line_number - 1) - first_node_location.line_number).times do
newline
end

yield
end

def visit(node : Nop)
false
end
Expand Down Expand Up @@ -221,11 +236,17 @@ module Crystal
if @inside_macro > 0
node.expressions.each &.accept self
else
last_node = node.expressions.first

node.expressions.each_with_index do |exp, i|
unless exp.nop?
append_indent unless node.keyword.paren? && i == 0
exp.accept self
newline unless node.keyword.paren? && i == node.expressions.size - 1
self.add_whitespace_around last_node.end_location, exp.location do
append_indent unless node.keyword.paren? && i == 0
exp.accept self
newline unless node.keyword.paren? && i == node.expressions.size - 1
end

last_node = exp
end
end
end
Expand Down

0 comments on commit 79641c7

Please sign in to comment.