Skip to content

Commit

Permalink
Add zero- and one-argument versions of 'and' and 'or' (ref. #824)
Browse files Browse the repository at this point in the history
  • Loading branch information
refi64 committed Jul 2, 2015
1 parent 3a24979 commit 9200305
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
17 changes: 12 additions & 5 deletions hy/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1631,15 +1631,22 @@ def compile_require(self, expression):

@builds("and")
@builds("or")
@checkargs(min=2)
def compile_logical_or_and_and_operator(self, expression):
ops = {"and": ast.And,
"or": ast.Or}
ops = {"and": (ast.And, "True"),
"or": (ast.Or, "False")}
operator = expression.pop(0)
opnode, default = ops[operator]
root_line, root_column = operator.start_line, operator.start_column
if len(expression) == 0:
return ast.Name(id=default,
ctx=ast.Load(),
lineno=root_line,
col_offset=root_column)
elif len(expression) == 1:
return self.compile(expression[0])
ret = Result()
values = list(map(self.compile, expression))
has_stmt = any(value.stmts for value in values)
root_line, root_column = operator.start_line, operator.start_column
if has_stmt:
# Compile it to an if...else sequence
var = self.get_anon_var()
Expand Down Expand Up @@ -1692,7 +1699,7 @@ def make_assign(value, node=None):
ret = sum(root, ret)
ret += Result(expr=expr_name, temp_variables=[expr_name, name])
else:
ret += ast.BoolOp(op=ops[operator](),
ret += ast.BoolOp(op=opnode(),
lineno=root_line,
col_offset=root_column,
values=[value.force_expr for value in values])
Expand Down
16 changes: 12 additions & 4 deletions tests/native_tests/language.hy
Original file line number Diff line number Diff line change
Expand Up @@ -759,9 +759,13 @@
(defn test-and []
"NATIVE: test the and function"
(let [[and123 (and 1 2 3)]
[and-false (and 1 False 3)]]
[and-false (and 1 False 3)]
[and-true (and)]
[and-single (and 1)]]
(assert (= and123 3))
(assert (= and-false False)))
(assert (= and-false False))
(assert (= and-true True))
(assert (= and-single 1)))
; short circuiting
(setv a 1)
(and 0 (setv a 2))
Expand All @@ -772,10 +776,14 @@
"NATIVE: test the or function"
(let [[or-all-true (or 1 2 3 True "string")]
[or-some-true (or False "hello")]
[or-none-true (or False False)]]
[or-none-true (or False False)]
[or-false (or)]
[or-single (or 1)]]
(assert (= or-all-true 1))
(assert (= or-some-true "hello"))
(assert (= or-none-true False)))
(assert (= or-none-true False))
(assert (= or-false False))
(assert (= or-single 1)))
; short circuiting
(setv a 1)
(or 1 (setv a 2))
Expand Down

0 comments on commit 9200305

Please sign in to comment.