From a17dcdbffbe7c7eb270ea669790b16faec3ce504 Mon Sep 17 00:00:00 2001 From: Nicolas Dandrimont Date: Fri, 19 Jul 2013 00:43:06 +0200 Subject: [PATCH 1/2] Make `with` return the last expression from its branch Thanks @rwtolbert for the bug report --- hy/compiler.py | 26 +++++++++++++++++++++----- tests/native_tests/language.hy | 7 +++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/hy/compiler.py b/hy/compiler.py index 70f329c..ba35791 100644 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -1200,11 +1200,18 @@ class HyASTCompiler(object): thing = self._storeize(self.compile(args.pop(0))) body = self._compile_branch(expr) - body += body.expr_as_stmt() - if not body.stmts: - body += ast.Pass(lineno=expr.start_line, - col_offset=expr.start_column) + var = self.get_anon_var() + name = ast.Name(id=ast_str(var), arg=ast_str(var), + ctx=ast.Store(), + lineno=expr.start_line, + col_offset=expr.start_column) + + # Store the result of the body in a tempvar + body += ast.Assign(targets=[name], + value=body.force_expr, + lineno=expr.start_line, + col_offset=expr.start_column) the_with = ast.With(context_expr=ctx.force_expr, lineno=expr.start_line, @@ -1216,7 +1223,16 @@ class HyASTCompiler(object): the_with.items = [ast.withitem(context_expr=ctx.force_expr, optional_vars=thing)] - return ctx + the_with + ret = ctx + the_with + # And make our expression context our temp variable + expr_name = ast.Name(id=ast_str(var), arg=ast_str(var), + ctx=ast.Load(), + lineno=expr.start_line, + col_offset=expr.start_column) + + ret += Result(expr=expr_name, temp_variables=[expr_name, name]) + + return ret @builds(",") def compile_tuple(self, expr): diff --git a/tests/native_tests/language.hy b/tests/native_tests/language.hy index 00815b1..6dd2986 100644 --- a/tests/native_tests/language.hy +++ b/tests/native_tests/language.hy @@ -411,6 +411,13 @@ (with [(open "README.md" "r")] (do))) +(defn test-with-return [] + "NATIVE: test that with returns stuff" + (defn read-file [filename] + (with [fd (open filename "r")] (.read fd))) + (assert (!= 0 (len (read-file "README.md"))))) + + (defn test-for-doodle [] "NATIVE: test for-do" (do (do (do (do (do (do (do (do (do (setv (, x y) (, 0 0))))))))))) From b761c7dc83ef9954af2e95ebef44696f372e9eef Mon Sep 17 00:00:00 2001 From: "Joe H. Rahme" Date: Sun, 21 Jul 2013 02:59:35 +0200 Subject: [PATCH 2/2] Fixes a mistake (most probably a typo) in the tutorial. --- docs/tutorial.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorial.rst b/docs/tutorial.rst index 0c3838b..5ce99f0 100644 --- a/docs/tutorial.rst +++ b/docs/tutorial.rst @@ -392,7 +392,7 @@ In python we might see:: The same thing in Hy:: - => (defn optional_arg [pos1 pos2 &optional keyword1 [keyword2 88]] + => (defn optional_arg [pos1 pos2 &optional keyword1 [keyword2 42]] ... [pos1 pos2 keyword1 keyword2]) => (optional_arg 1 2) [1 2 None 42]