Moving `for' to a "macro"

This commit is contained in:
Paul R. Tagliamonte 2013-03-13 20:41:53 -04:00
parent fded70e68c
commit 0bc2dd8d00
3 changed files with 34 additions and 1 deletions

View File

@ -380,7 +380,7 @@ class HyASTCompiler(object):
col_offset=expression.start_column,
targets=[name], value=what)
@builds("for")
@builds("foreach")
def compile_for_expression(self, expression):
ret_status = self.returnable
self.returnable = False

View File

@ -22,6 +22,7 @@
from hy.macros import macro
from hy.models.expression import HyExpression
from hy.models.symbol import HySymbol
from hy.models.list import HyList
@macro("defn")
@ -47,6 +48,37 @@ def cond_macro(tree):
return root
@macro("for")
def for_macro(tree):
tree.pop(0)
ret = None
# for [x iter y iter] ...
# ->
# foreach x iter
# foreach y iter
# ...
it = iter(tree.pop(0))
blocks = list(zip(it, it)) # List for Python 3.x degenerating.
key, val = blocks.pop(0)
ret = HyExpression([HySymbol("foreach"),
HyList([key, val])])
root = ret
ret.replace(tree)
for key, val in blocks:
# x, [1, 2, 3, 4]
nret = HyExpression([HySymbol("foreach"),
HyList([key, val])])
nret.replace(key)
ret.append(nret)
ret = nret
[ret.append(x) for x in tree] # we really need ~@
return root
@macro("_>")
def threading_macro(tree):
tree.pop(0)

View File

@ -37,6 +37,7 @@ def process(tree):
if isinstance(tree, HyExpression):
fn = tree[0]
ntree = HyExpression([fn] + [process(x) for x in tree[1:]])
ntree.replace(tree)
if isinstance(fn, HyString):
if fn in _hy_macros: