From 8e3922b6c6ce4201ec51620b542aa48f5a5fa215 Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Sat, 9 Jan 2010 13:25:44 -0500 Subject: [PATCH] allowing comments in the middle of switch statements --- lib/coffee_script/grammar.y | 2 +- lib/coffee_script/nodes.rb | 11 +++++++++-- test/fixtures/execution/test_switch.coffee | 6 +++++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/lib/coffee_script/grammar.y b/lib/coffee_script/grammar.y index 7c2ee5bb..5bacc2aa 100644 --- a/lib/coffee_script/grammar.y +++ b/lib/coffee_script/grammar.y @@ -385,7 +385,7 @@ rule LEADING_WHEN Expression Block { result = IfNode.new(val[1], val[2], nil, {:statement => true}) } | LEADING_WHEN Expression Block Terminator { result = IfNode.new(val[1], val[2], nil, {:statement => true}) } - | Comment + | Comment Terminator When { result = val[2].add_comment(val[0]) } ; # The most basic form of "if". diff --git a/lib/coffee_script/nodes.rb b/lib/coffee_script/nodes.rb index fd1d5b1c..ec209f1c 100644 --- a/lib/coffee_script/nodes.rb +++ b/lib/coffee_script/nodes.rb @@ -769,6 +769,11 @@ module CoffeeScript self end + def add_comment(comment) + @comment = comment + self + end + def force_statement @tags[:statement] = true self @@ -795,7 +800,7 @@ module CoffeeScript # The IfNode only compiles into a statement if either of the bodies needs # to be a statement. def statement? - @is_statement ||= !!(@tags[:statement] || @body.statement? || (@else_body && @else_body.statement?)) + @is_statement ||= !!(@comment || @tags[:statement] || @body.statement? || (@else_body && @else_body.statement?)) end def compile_node(o) @@ -811,7 +816,9 @@ module CoffeeScript o[:indent] = idt(1) o[:top] = true if_dent = child ? '' : idt - if_part = "#{if_dent}if (#{@condition.compile(cond_o)}) {\n#{Expressions.wrap(@body).compile(o)}\n#{idt}}" + com_dent = child ? idt : '' + prefix = @comment ? @comment.compile(cond_o) + "\n#{com_dent}" : '' + if_part = "#{prefix}#{if_dent}if (#{@condition.compile(cond_o)}) {\n#{Expressions.wrap(@body).compile(o)}\n#{idt}}" return if_part unless @else_body else_part = chain? ? " else #{@else_body.compile(o.merge(:indent => idt, :chain_child => true))}" : diff --git a/test/fixtures/execution/test_switch.coffee b/test/fixtures/execution/test_switch.coffee index dad43358..9bdbf0f0 100644 --- a/test/fixtures/execution/test_switch.coffee +++ b/test/fixtures/execution/test_switch.coffee @@ -7,7 +7,11 @@ result: switch num true false when 10 then true + + + # Mid-switch comment with whitespace + # and multi line when 11 then false else false - + print(result)