From 73be6afd3a25a4e2d91a70294e9d310971cc9ff5 Mon Sep 17 00:00:00 2001 From: "Paul R. Tagliamonte" Date: Tue, 9 Apr 2013 21:33:09 -0400 Subject: [PATCH] Initial cut of `eval' --- hy/compiler.py | 18 ++++++++++++++++-- hy/importer.py | 15 ++++++++++++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/hy/compiler.py b/hy/compiler.py index 0157142..3901c8b 100644 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -133,7 +133,8 @@ class HyASTCompiler(object): start_line=getattr(e, "start_line", 0), start_column=getattr(e, "start_column", 0)) - raise HyCompileError("Unknown type - `%s'" % (str(type(tree)))) + raise HyCompileError( + "Unknown type - `%s' - %s" % (str(type(tree)), tree)) def _mangle_branch(self, tree, start_line, start_column): # If tree is empty, just return a pass statement @@ -191,6 +192,14 @@ class HyASTCompiler(object): def compile_quote(self, entries): return self.compile(self._render_quoted_form(entries[1])) + @builds("eval") + @checkargs(exact=1) + def compile_eval(self, expr): + expr.pop(0) + return self.compile(HyExpression([ + HySymbol("hy_eval")] + expr + [HyExpression([HySymbol("globals")]) + ]).replace(expr)) + @builds("do") @builds("progn") def compile_do_expression(self, expr): @@ -925,5 +934,10 @@ def hy_compile(tree, root=None): tlo = root if root is None: tlo = ast.Module - ret = tlo(body=compiler._mangle_branch(compiler.compile(tree), 0, 0)) + + _ast = compiler.compile(tree) + if type(_ast) == list: + _ast = compiler._mangle_branch(_ast, 0, 0) + + ret = tlo(body=_ast) return ret diff --git a/hy/importer.py b/hy/importer.py index 587d536..94ed984 100644 --- a/hy/importer.py +++ b/hy/importer.py @@ -18,8 +18,9 @@ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from hy.compiler import hy_compile from py_compile import wr_long, MAGIC +from hy.compiler import hy_compile +from hy.models import HyObject from hy.core import process from hy.lex import tokenize @@ -28,6 +29,7 @@ from io import open import marshal import imp import sys +import ast import os @@ -67,6 +69,17 @@ def import_file_to_module(name, fpath): return mod +def hy_eval(hytree, namespace): + foo = HyObject() + foo.start_line = 0 + foo.end_line = 0 + foo.start_column = 0 + foo.end_column = 0 + hytree.replace(foo) + _ast = hy_compile(hytree, root=ast.Expression) + return eval(compile(_ast, "", "eval"), namespace) + + def write_hy_as_pyc(fname): with open(fname, 'U') as f: try: