adding ranges as expressions, they get expanded into the equivalent array

This commit is contained in:
Jeremy Ashkenas
2010-01-05 22:17:09 -05:00
parent c2bb93b5f8
commit 46f1977ea1
2 changed files with 11 additions and 2 deletions

View File

@@ -354,7 +354,7 @@ module CoffeeScript
def compile_node(o)
idx, step = o.delete(:index), o.delete(:step)
raise SyntaxError, "unexpected range literal" unless idx
return compile_array(o) unless idx
vars = "#{idx}=#{@from_var}"
step = step ? step.compile(o) : '1'
compare = "(#{@from_var} <= #{@to_var} ? #{idx} #{less_operator} #{@to_var} : #{idx} #{greater_operator} #{@to_var})"
@@ -362,6 +362,15 @@ module CoffeeScript
write("#{vars}; #{compare}; #{incr}")
end
# Expand the range into the equivalent array, if it's not being used as
# part of a comprehension, slice, or splice.
# TODO: This generates pretty ugly code ... shrink it.
def compile_array(o)
body = Expressions.wrap(LiteralNode.new(Value.new('i')))
arr = Expressions.wrap(ForNode.new(body, {:source => self}, Value.new('i')))
ParentheticalNode.new(CallNode.new(CodeNode.new([], arr))).compile(o)
end
end
# An array slice literal. Unlike JavaScript's Array#slice, the second parameter