compiling if-else chains into nice flat ones

This commit is contained in:
Jeremy Ashkenas
2009-12-17 23:34:52 -05:00
parent 1395b05d36
commit 67bb49ed04

View File

@@ -453,10 +453,13 @@ module CoffeeScript
self self
end end
# If the else_body is an IfNode itself, then we've got an if-else chain.
def chain? def chain?
@chain ||= @else_body && @else_body.is_a?(IfNode) @chain ||= @else_body && @else_body.is_a?(IfNode)
end end
# The IfNode only compiles into a statement if either of the bodies needs
# to be a statement.
def statement? def statement?
@is_statement ||= (@body.statement? || (@else_body && @else_body.statement?)) @is_statement ||= (@body.statement? || (@else_body && @else_body.statement?))
end end
@@ -469,12 +472,17 @@ module CoffeeScript
statement? ? compile_statement(indent, scope, opts) : compile_ternary(indent, scope) statement? ? compile_statement(indent, scope, opts) : compile_ternary(indent, scope)
end end
# Compile the IfNode as a regular if-else statement.
def compile_statement(indent, scope, opts) def compile_statement(indent, scope, opts)
if_part = "if (#{@condition.compile(indent, scope, :no_paren => true)}) {\n#{Expressions.wrap(@body).compile(indent + TAB, scope, opts)}\n#{indent}}" if_part = "if (#{@condition.compile(indent, scope, :no_paren => true)}) {\n#{Expressions.wrap(@body).compile(indent + TAB, scope, opts)}\n#{indent}}"
else_part = @else_body ? " else {\n#{Expressions.wrap(@else_body).compile(indent + TAB, scope, opts)}\n#{indent}}" : '' return if_part unless @else_body
else_part = chain? ?
" else #{@else_body.compile(indent, scope, opts)}" :
" else {\n#{Expressions.wrap(@else_body).compile(indent + TAB, scope, opts)}\n#{indent}}"
if_part + else_part if_part + else_part
end end
# Compile the IfNode into a ternary operator.
def compile_ternary(indent, scope) def compile_ternary(indent, scope)
if_part = "#{@condition.compile(indent, scope)} ? #{@body.compile(indent, scope)}" if_part = "#{@condition.compile(indent, scope)} ? #{@body.compile(indent, scope)}"
else_part = @else_body ? "#{@else_body.compile(indent, scope)}" : 'null' else_part = @else_body ? "#{@else_body.compile(indent, scope)}" : 'null'