Skip to content

Instantly share code, notes, and snippets.

@ozra
Last active August 29, 2015 14:24
Show Gist options
  • Save ozra/4eee1a8c7f298405fc00 to your computer and use it in GitHub Desktop.
Save ozra/4eee1a8c7f298405fc00 to your computer and use it in GitHub Desktop.
for -> each transformation
def transform(node : For)
block_args = [] of Var
method_name :: String
node.vars.each do |v|
block_args << v.clone # tries cloning if there are any weird node to node ties
end
if node.vars.length == 1
method_name = "each"
elsif node.vars.length == 2
method_name = "each_with_index"
else # *TODO* moot - is catched in the parsing stage
node.raise "Wrong number of iteration variables for 'for .. in ..'!"
end
foo = Call.new(
node.expr,
method_name,
[] of ASTNode,
Block.new(
block_args,
node.body.transform(self).at(node.body) #clone # tried all kinds of things in case there are already node to node ties
)
).at(node)
p foo.to_s
dump foo.to_s
foo
end
list = [1,2,3]
list.each do |val|
p val
end
for val, ix in list
p "#{val}, #{ix}"
end
for val in list
p val
end
# Possibly implement and try alternative syntax:
#for val[ix] in list
# p val, ix
#end
#for [ix] in list
# p ix
#end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment