From be35b09e5d477c4ba3f8b30bec7b27829de7f09e Mon Sep 17 00:00:00 2001 From: Rob Day Date: Thu, 14 Sep 2017 08:37:32 +0100 Subject: [PATCH] Allow multiple statements in the else branch of a for loop --- NEWS | 2 ++ hy/compiler.py | 8 ++------ tests/compilers/test_ast.py | 5 ----- tests/native_tests/language.hy | 11 +++++++++++ 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/NEWS b/NEWS index 3e23f66..1d2211e 100644 --- a/NEWS +++ b/NEWS @@ -38,6 +38,8 @@ Changes from 0.13.0 * `assoc` now evaluates its arguments only once each * `break` and `continue` now raise an error when given arguments instead of silently ignoring them + * Multiple expressions are now allowed in the else clause of + a for loop [ Misc. Improvements ] * `read`, `read_str`, and `eval` are exposed and documented as top-level diff --git a/hy/compiler.py b/hy/compiler.py index ca478ed..7b2f4f2 100755 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -2116,12 +2116,8 @@ class HyASTCompiler(object): # (for* [] body (else …)) if expression and expression[-1][0] == HySymbol("else"): else_expr = expression.pop() - if len(else_expr) > 2: - raise HyTypeError( - else_expr, - "`else' statement in `for' is too long") - elif len(else_expr) == 2: - orel += self.compile(else_expr[1]) + for else_body in else_expr[1:]: + orel += self.compile(else_body) orel += orel.expr_as_stmt() ret += self.compile(iterable) diff --git a/tests/compilers/test_ast.py b/tests/compilers/test_ast.py index 4e0e00b..850c695 100644 --- a/tests/compilers/test_ast.py +++ b/tests/compilers/test_ast.py @@ -331,11 +331,6 @@ def test_ast_valid_for(): can_compile("(for [a 2] (print a))") -def test_ast_invalid_for(): - "Make sure AST can't compile invalid for" - cant_compile("(for* [a 1] (else 1 2))") - - def test_nullary_break_continue(): can_compile("(while 1 (break))") cant_compile("(while 1 (break 1))") diff --git a/tests/native_tests/language.hy b/tests/native_tests/language.hy index 1f069af..b41cf81 100644 --- a/tests/native_tests/language.hy +++ b/tests/native_tests/language.hy @@ -210,6 +210,17 @@ (else (+= count 1))) (assert (= count 151)) + + (setv count 0) + ; multiple statements in the else branch should work + (for [x [1 2 3 4 5] + y [1 2 3 4 5]] + (setv count (+ count x y)) + (else + (+= count 1) + (+= count 10))) + + (assert (= count 161)) (assert (= (list ((fn [] (for [x [[1] [2 3]] y x] (yield y))))) (list-comp y [x [[1] [2 3]] y x]))) (assert (= (list ((fn [] (for [x [[1] [2 3]] y x z (range 5)] (yield z)))))