Raises TypeError on bad if statements

This relates to issue #6.

Signed-off-by: Julien Danjou <julien@danjou.info>
This commit is contained in:
Julien Danjou 2013-04-03 11:25:17 +02:00
parent 12106d3d37
commit 1c8d21e3de
2 changed files with 33 additions and 2 deletions

View File

@ -152,8 +152,16 @@ class HyASTCompiler(object):
@builds("if") @builds("if")
def compile_if_expression(self, expr): def compile_if_expression(self, expr):
expr.pop(0) expr.pop(0)
test = self.compile(expr.pop(0)) try:
body = self._code_branch(self.compile(expr.pop(0))) test = expr.pop(0)
except IndexError:
raise TypeError("if expects at least 2 arguments, got 0")
test = self.compile(test)
try:
body = expr.pop(0)
except IndexError:
raise TypeError("if expects at least 2 arguments, got 1")
body = self._code_branch(self.compile(body))
orel = [] orel = []
if len(expr) > 0: if len(expr) > 0:
orel = self._code_branch(self.compile(expr.pop(0))) orel = self._code_branch(self.compile(expr.pop(0)))

View File

@ -43,6 +43,29 @@ def test_ast_bad_type():
pass pass
def test_ast_bad_if_0_arg():
"Make sure AST can't compile invalid if"
try:
hy_compile(tokenize("(if)"))
assert False
except TypeError:
pass
def test_ast_bad_if_1_arg():
"Make sure AST can't compile invalid if"
try:
hy_compile(tokenize("(if foobar)"))
assert False
except TypeError:
pass
def test_ast_valid_if():
"Make sure AST can't compile invalid if"
hy_compile(tokenize("(if foo bar)"))
def test_ast_expression_basics(): def test_ast_expression_basics():
""" Ensure basic AST expression conversion works. """ """ Ensure basic AST expression conversion works. """
code = hy_compile(tokenize("(foo bar)")).body[0] code = hy_compile(tokenize("(foo bar)")).body[0]