Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add while loops to the compiler

  • Loading branch information...
commit d070d3d484f063ab240de978eed6028a59ad1a89 1 parent c627fad
Nicolas Dandrimont olasd authored
3  TODO
View
@@ -9,9 +9,6 @@
+ Use (def) to imply global foo
- - New Builtins:
- + While
-
- New macros:
+ loop
20 hy/compiler.py
View
@@ -545,6 +545,26 @@ def compile_for_expression(self, expression):
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(
23 tests/compilers/test_ast.py
View
@@ -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]
11 tests/native_tests/language.hy
View
@@ -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"]))
Please sign in to comment.
Something went wrong with that request. Please try again.