Skip to content

Commit 4ff77b4

Browse files
author
Yusuke Oda
authored
Improve visit_BoolOp implementation (#62)
* improve visit_Compare * improve boolop * support multiple comparators
1 parent c881cce commit 4ff77b4

File tree

2 files changed

+31
-18
lines changed

2 files changed

+31
-18
lines changed

src/latexify/latexify_visitor.py

+10-18
Original file line numberDiff line numberDiff line change
@@ -268,24 +268,16 @@ def visit_Compare(self, node: ast.Compare, action): # pylint: disable=invalid-n
268268
ops_rhs = [f" {o} {r}" for o, r in zip(ops, rhs)]
269269
return "{" + lhs + "".join(ops_rhs) + "}"
270270

271-
def visit_BoolOp(self, node, action): # pylint: disable=invalid-name
272-
logic_operator = (
273-
r"\lor "
274-
if isinstance(node.op, ast.Or)
275-
else r"\land "
276-
if isinstance(node.op, ast.And)
277-
else r" \mathrm{unknown\_operator} "
278-
)
279-
# visit all the elements in the ast.If node recursively
280-
return (
281-
r"\left("
282-
+ self.visit(node.values[0])
283-
+ r"\right)"
284-
+ logic_operator
285-
+ r"\left("
286-
+ self.visit(node.values[1])
287-
+ r"\right)"
288-
)
271+
_bool_ops: ClassVar[dict[type[ast.boolop], str]] = {
272+
ast.And: r"\land",
273+
ast.Or: r"\lor",
274+
}
275+
276+
def visit_BoolOp(self, node: ast.BoolOp, action): # pylint: disable=invalid-name
277+
"""Visit a BoolOp node."""
278+
values = [rf"\left( {self.visit(x)} \right)" for x in node.values]
279+
op = f" {self._bool_ops[type(node.op)]} "
280+
return "{" + op.join(values) + "}"
289281

290282
def visit_If(self, node, action): # pylint: disable=invalid-name
291283
"""Visit an if node."""

src/latexify/latexify_visitor_test.py

+21
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,24 @@ def test_visit_compare(code: str, latex: str) -> None:
4444
tree = ast.parse(code).body[0].value
4545
assert isinstance(tree, ast.Compare)
4646
assert LatexifyVisitor().visit(tree) == latex
47+
48+
49+
@pytest.mark.parametrize(
50+
"code,latex",
51+
[
52+
("a and b", r"{\left( a \right) \land \left( b \right)}"),
53+
(
54+
"a and b and c",
55+
r"{\left( a \right) \land \left( b \right) \land \left( c \right)}",
56+
),
57+
("a or b", r"{\left( a \right) \lor \left( b \right)}"),
58+
(
59+
"a or b or c",
60+
r"{\left( a \right) \lor \left( b \right) \lor \left( c \right)}",
61+
),
62+
],
63+
)
64+
def test_visit_boolop(code: str, latex: str) -> None:
65+
tree = ast.parse(code).body[0].value
66+
assert isinstance(tree, ast.BoolOp)
67+
assert LatexifyVisitor().visit(tree) == latex

0 commit comments

Comments
 (0)