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 <algernon@madhouse-project.org>
This commit is contained in:
Gergely Nagy 2015-08-10 15:55:11 +02:00
parent 2665b316cf
commit fee7d33184
No known key found for this signature in database
GPG Key ID: 0A083C5F06E0DD42
2 changed files with 15 additions and 0 deletions

View File

@ -1473,9 +1473,16 @@ class HyASTCompiler(object):
# (list-comp expr (target iter) cond?) # (list-comp expr (target iter) cond?)
expr.pop(0) expr.pop(0)
expression = 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) 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) compiled_expression = self.compile(expression)
ret = compiled_expression + gen_res ret = compiled_expression + gen_res
ret += ast.ListComp( ret += ast.ListComp(

View File

@ -519,3 +519,11 @@ def test_attribute_access():
def test_cons_correct(): def test_cons_correct():
"""Ensure cons gets compiled correctly""" """Ensure cons gets compiled correctly"""
can_compile("(cons a b)") 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)")