From 0bc2dd8d006faa09a5ad1ff9d0b673d4037b66cf Mon Sep 17 00:00:00 2001 From: "Paul R. Tagliamonte" Date: Wed, 13 Mar 2013 20:41:53 -0400 Subject: [PATCH] Moving `for' to a "macro" --- hy/compiler.py | 2 +- hy/core/bootstrap.py | 32 ++++++++++++++++++++++++++++++++ hy/macros.py | 1 + 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/hy/compiler.py b/hy/compiler.py index 9bcbd37..dfb9985 100644 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -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 diff --git a/hy/core/bootstrap.py b/hy/core/bootstrap.py index 2b9f458..e453de1 100644 --- a/hy/core/bootstrap.py +++ b/hy/core/bootstrap.py @@ -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) diff --git a/hy/macros.py b/hy/macros.py index 4430c48..7f5a8e5 100644 --- a/hy/macros.py +++ b/hy/macros.py @@ -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: