From fee7d33184dd40f9e754c2253d5ef2376f66e8c2 Mon Sep 17 00:00:00 2001 From: Gergely Nagy Date: Mon, 10 Aug 2015 15:55:11 +0200 Subject: [PATCH] Guard against a few invalid list comprehension cases Some valid-looking list comprehensions, such as (genexpr x []) can crash Python 2.7. The AST we generate from these cannot be expressed in Python, but were valid in Hy. Added two guards to guard against this, so we raise an error instead of crashing Python. Closes #572, #591 and #634. Signed-off-by: Gergely Nagy --- hy/compiler.py | 7 +++++++ tests/compilers/test_ast.py | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/hy/compiler.py b/hy/compiler.py index 8e9893c..f9aeac4 100644 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -1473,9 +1473,16 @@ class HyASTCompiler(object): # (list-comp expr (target iter) cond?) expr.pop(0) expression = expr.pop(0) + gen_gen = expr[0] + + if not isinstance(gen_gen, HyList): + raise HyTypeError(gen_gen, "Generator expression must be a list.") gen_res, gen = self._compile_generator_iterables(expr) + if len(gen) == 0: + raise HyTypeError(gen_gen, "Generator expression cannot be empty.") + compiled_expression = self.compile(expression) ret = compiled_expression + gen_res ret += ast.ListComp( diff --git a/tests/compilers/test_ast.py b/tests/compilers/test_ast.py index 4491f83..69e5e15 100644 --- a/tests/compilers/test_ast.py +++ b/tests/compilers/test_ast.py @@ -519,3 +519,11 @@ def test_attribute_access(): def test_cons_correct(): """Ensure cons gets compiled correctly""" can_compile("(cons a b)") + + +def test_invalid_list_comprehension(): + """Ensure that invalid list comprehensions do not break the compiler""" + cant_compile("(genexpr x [])") + cant_compile("(genexpr [x [1 2 3 4]] x)") + cant_compile("(list-comp None [])") + cant_compile("(list-comp [x [1 2 3]] x)")