Add while loops to the compiler

This commit is contained in:
Nicolas Dandrimont 2013-04-03 19:55:09 +02:00
parent c627fad5e2
commit d070d3d484
4 changed files with 54 additions and 3 deletions

3
TODO
View File

@ -9,9 +9,6 @@
+ Use (def) to imply global foo
- New Builtins:
+ While
- New macros:
+ loop

View File

@ -545,6 +545,26 @@ class HyASTCompiler(object):
self.returnable = ret_status
return ret
@builds("while")
def compile_while_expression(self, expr):
expr.pop(0) # "while"
try:
test = expr.pop(0)
except IndexError:
raise TypeError("while expects at least 2 arguments, got 0")
test = self.compile(test)
if not expr:
raise TypeError("while expects a body")
return ast.While(test=test,
body=self._mangle_branch([
self.compile(x) for x in expr]),
orelse=[],
lineno=expr.start_line,
col_offset=expr.start_column)
@builds(HyList)
def compile_list(self, expr):
return ast.List(

View File

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

View File

@ -32,6 +32,17 @@
(assert (= count 150)))
(defn test-while-loop []
"NATIVE: test while loops?"
(setv count 5)
(setv fact 1)
(while (> count 0)
(setv fact (* fact count))
(setv count (- count 1)))
(assert (= count 0))
(assert (= fact 120)))
(defn test-in []
"NATIVE: test in"
(assert (in "a" ["a" "b" "c" "d"]))