From 5336b2f71ace09ab3df9af56238eb16289f0aafa Mon Sep 17 00:00:00 2001 From: "Paul R. Tagliamonte" Date: Sun, 7 Apr 2013 19:29:45 -0400 Subject: [PATCH] Fix early returns. Close #83 --- hy/compiler.py | 20 +++++++++++++++++--- tests/native_tests/language.hy | 12 ++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/hy/compiler.py b/hy/compiler.py index 66f10bf..6851749 100644 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -762,12 +762,27 @@ class HyASTCompiler(object): expression.pop(0) # fn ret_status = self.returnable - self.returnable = True self.anon_fn_count += 1 name = "_hy_anon_fn_%d" % (self.anon_fn_count) sig = expression.pop(0) + body = [] + if expression != []: + self.returnable = True + tailop = self.compile(expression.pop(-1)) + self.returnable = False + for el in expression: + body.append(self.compile(el)) + body.append(tailop) + + if body == []: + body = [ast.Pass(lineno=expression.start_line, + col_offset=expression.start_column)] + + self.returnable = True + body = self._code_branch(body) + ret = ast.FunctionDef( name=name, lineno=expression.start_line, @@ -785,8 +800,7 @@ class HyASTCompiler(object): kwonlyargs=[], kw_defaults=[], defaults=[]), - body=self._code_branch([ - self.compile(x) for x in expression]), + body=body, decorator_list=[]) self.returnable = ret_status diff --git a/tests/native_tests/language.hy b/tests/native_tests/language.hy index e029480..6b00a3e 100644 --- a/tests/native_tests/language.hy +++ b/tests/native_tests/language.hy @@ -427,6 +427,7 @@ (assert (= and123 3)) (assert (= and-false False)))) + (defn test-or [] "NATIVE: test the or function" (let [[or-all-true (or 1 2 3 True "string")] @@ -436,6 +437,17 @@ (assert (= or-some-true "hello")) (assert (= or-none-true False)))) + +(defn test-if-return-branching [] + "NATIVE: test the if return branching" + ; thanks, algernon + (assert (= 1 (let [[x 1] + [y 2]] + (if true + 2) + 1)))) + + ; FEATURE: native hy-eval ; ; - related to bug #64