Skip to content

Commit 08940fc

Browse files
authored
Support {% elsif %} when stringifying MacroIf nodes (#15928)
1 parent 20924bb commit 08940fc

File tree

2 files changed

+64
-13
lines changed

2 files changed

+64
-13
lines changed

spec/compiler/parser/to_s_spec.cr

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,44 @@ describe "ASTNode#to_s" do
284284
end
285285
CRYSTAL
286286

287+
expect_to_s <<-'CRYSTAL'
288+
{% if 1 %}
289+
2
290+
{% elsif 3 %}
291+
4
292+
{% elsif 5 %}
293+
{% elsif 6 %}
294+
{% else %}
295+
7
296+
{% end %}
297+
CRYSTAL
298+
299+
expect_to_s <<-'CRYSTAL', <<-'CRYSTAL'
300+
{% if 1 %}
301+
2
302+
{% else %}{% if 3 %}
303+
{% end %}{% end %}
304+
CRYSTAL
305+
{% if 1 %}
306+
2
307+
{% elsif 3 %}
308+
{% end %}
309+
CRYSTAL
310+
311+
expect_to_s <<-'CRYSTAL'
312+
{% if 1 %}
313+
2
314+
{% else %}{% unless 3 %}
315+
{% end %}{% end %}
316+
CRYSTAL
317+
318+
expect_to_s <<-'CRYSTAL'
319+
{% unless 1 %}
320+
2
321+
{% else %}{% if 3 %}
322+
{% end %}{% end %}
323+
CRYSTAL
324+
287325
expect_to_s %(foo do\n begin\n bar\n end\nend)
288326
expect_to_s %q("\e\0\""), %q("\e\u0000\"")
289327
expect_to_s %q("#{1}\0"), %q("#{1}\u0000")

src/compiler/crystal/syntax/to_s.cr

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -932,20 +932,33 @@ module Crystal
932932
end
933933

934934
def visit(node : MacroIf)
935-
if node.is_unless?
936-
@str << "{% unless "
937-
then_node = node.else
938-
else_node = node.then
939-
else
940-
@str << "{% if "
941-
then_node = node.then
942-
else_node = node.else
943-
end
944-
node.cond.accept self
945-
@str << " %}"
935+
else_node = nil
946936

947-
inside_macro do
948-
then_node.accept self
937+
while true
938+
if node.is_unless?
939+
@str << "{% unless "
940+
then_node = node.else
941+
else_node = node.then
942+
else
943+
@str << (else_node ? "{% elsif " : "{% if ")
944+
then_node = node.then
945+
else_node = node.else
946+
end
947+
node.cond.accept self
948+
@str << " %}"
949+
950+
inside_macro do
951+
then_node.accept self
952+
end
953+
954+
# combine `{% else %}{% if %}` into `{% elsif %}` (does not apply to
955+
# `{% unless %}`, nor when there is whitespace inbetween, as that would
956+
# show up as a `MacroLiteral`)
957+
if !node.is_unless? && else_node.is_a?(MacroIf) && !else_node.is_unless?
958+
node = else_node
959+
else
960+
break
961+
end
949962
end
950963

951964
unless else_node.nop?

0 commit comments

Comments
 (0)