Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve visit_BoolOp implementation #62

Merged
merged 5 commits into from
Oct 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 10 additions & 18 deletions src/latexify/latexify_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,24 +268,16 @@ def visit_Compare(self, node: ast.Compare, action): # pylint: disable=invalid-n
ops_rhs = [f" {o} {r}" for o, r in zip(ops, rhs)]
return "{" + lhs + "".join(ops_rhs) + "}"

def visit_BoolOp(self, node, action): # pylint: disable=invalid-name
logic_operator = (
r"\lor "
if isinstance(node.op, ast.Or)
else r"\land "
if isinstance(node.op, ast.And)
else r" \mathrm{unknown\_operator} "
)
# visit all the elements in the ast.If node recursively
return (
r"\left("
+ self.visit(node.values[0])
+ r"\right)"
+ logic_operator
+ r"\left("
+ self.visit(node.values[1])
+ r"\right)"
)
_bool_ops: ClassVar[dict[type[ast.boolop], str]] = {
ast.And: r"\land",
ast.Or: r"\lor",
}

def visit_BoolOp(self, node: ast.BoolOp, action): # pylint: disable=invalid-name
"""Visit a BoolOp node."""
values = [rf"\left( {self.visit(x)} \right)" for x in node.values]
op = f" {self._bool_ops[type(node.op)]} "
return "{" + op.join(values) + "}"

def visit_If(self, node, action): # pylint: disable=invalid-name
"""Visit an if node."""
Expand Down
21 changes: 21 additions & 0 deletions src/latexify/latexify_visitor_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,24 @@ def test_visit_compare(code: str, latex: str) -> None:
tree = ast.parse(code).body[0].value
assert isinstance(tree, ast.Compare)
assert LatexifyVisitor().visit(tree) == latex


@pytest.mark.parametrize(
"code,latex",
[
("a and b", r"{\left( a \right) \land \left( b \right)}"),
(
"a and b and c",
r"{\left( a \right) \land \left( b \right) \land \left( c \right)}",
),
("a or b", r"{\left( a \right) \lor \left( b \right)}"),
(
"a or b or c",
r"{\left( a \right) \lor \left( b \right) \lor \left( c \right)}",
),
],
)
def test_visit_boolop(code: str, latex: str) -> None:
tree = ast.parse(code).body[0].value
assert isinstance(tree, ast.BoolOp)
assert LatexifyVisitor().visit(tree) == latex