Skip to content

Commit 142bc32

Browse files
authored
Add support for ast.IfExp (#111)
* Add support for ast.IfExp * Add support for recursive statement * Unit tests * Fix formatting issues
1 parent 8ca2b3a commit 142bc32

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/latexify/codegen/function_codegen.py

+12
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,18 @@ def visit_If(self, node: ast.If) -> str:
524524
latex += self.visit(node)
525525
return latex + r", & \mathrm{otherwise} \end{array} \right."
526526

527+
def visit_IfExp(self, node: ast.IfExp) -> str:
528+
"""Visit an ifexp node"""
529+
latex = r"\left\{ \begin{array}{ll} "
530+
while isinstance(node, ast.IfExp):
531+
cond_latex = self.visit(node.test)
532+
true_latex = self.visit(node.body)
533+
latex += true_latex + r", & \mathrm{if} \ " + cond_latex + r" \\ "
534+
node = node.orelse
535+
536+
latex += self.visit(node)
537+
return latex + r", & \mathrm{otherwise} \end{array} \right."
538+
527539
def _get_sum_prod_range(self, node: ast.comprehension) -> tuple[str, str] | None:
528540
"""Helper to process range(...) for sum and prod functions.
529541

src/latexify/codegen/function_codegen_test.py

+32
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,38 @@ def test_visit_call_sum_prod_with_if(src_suffix: str, dest_suffix: str) -> None:
253253
assert FunctionCodegen().visit(node) == dest_fn + dest_suffix
254254

255255

256+
@pytest.mark.parametrize(
257+
"code,latex",
258+
[
259+
(
260+
"x if x < y else y",
261+
r"\left\{ \begin{array}{ll} x,"
262+
r" & \mathrm{if} \ {x < y} \\ y,"
263+
r" & \mathrm{otherwise} \end{array} \right.",
264+
),
265+
(
266+
"x if x < y else (y if y < z else z)",
267+
r"\left\{ \begin{array}{ll} x,"
268+
r" & \mathrm{if} \ {x < y} \\ y,"
269+
r" & \mathrm{if} \ {y < z} \\ z,"
270+
r" & \mathrm{otherwise} \end{array} \right.",
271+
),
272+
(
273+
"x if x < y else (y if y < z else (z if z < w else w))",
274+
r"\left\{ \begin{array}{ll} x,"
275+
r" & \mathrm{if} \ {x < y} \\ y,"
276+
r" & \mathrm{if} \ {y < z} \\ z,"
277+
r" & \mathrm{if} \ {z < w} \\ w,"
278+
r" & \mathrm{otherwise} \end{array} \right.",
279+
),
280+
],
281+
)
282+
def test_if_then_else(code: str, latex: str) -> None:
283+
node = ast.parse(code).body[0].value
284+
assert isinstance(node, ast.IfExp)
285+
assert FunctionCodegen().visit(node) == latex
286+
287+
256288
@pytest.mark.parametrize(
257289
"code,latex",
258290
[

0 commit comments

Comments
 (0)