Skip to content

Commit d25cbcf

Browse files
committed
✨ feat: add auto_simplify function
1 parent edc198b commit d25cbcf

File tree

4 files changed

+43
-2
lines changed

4 files changed

+43
-2
lines changed

README.md

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
### Quick start in CLI
1919

20-
We recommend using the tool `uv` to run the without manually installing the package:
20+
We recommend using the tool `uv` to try it without manually installing the package:
2121

2222
```console
2323
$ uvx expr_simplifier cse "a * 4 + (a * 4)"
@@ -32,7 +32,23 @@ a and b
3232

3333
### As a library
3434

35-
TODO...
35+
```console
36+
$ uv add expr-simplifier
37+
```
38+
39+
```python
40+
from __future__ import annotations
41+
42+
import ast
43+
44+
from expr_simplifier import auto_simplify
45+
46+
code = "a[1 + 1].b + a[3 - 1].b.c + (___x := 2) + (a[2].b and (___x == 2) and a[2].b)"
47+
tree = ast.parse(code, mode="eval")
48+
simplified_tree = auto_simplify(tree)
49+
print(ast.unparse(simplified_tree))
50+
# (___t_1 := a[2].b) + ___t_1.c + 2 + ___t_1
51+
```
3652

3753
## TODOs
3854

examples/auto_simplify.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from __future__ import annotations
2+
3+
import ast
4+
5+
from expr_simplifier import auto_simplify
6+
7+
code = "a[1 + 1].b + a[3 - 1].b.c + (___x := 2) + (a[2].b and (___x == 2) and a[2].b)"
8+
tree = ast.parse(code, mode="eval")
9+
simplified_tree = auto_simplify(tree)
10+
print(ast.unparse(simplified_tree))
11+
# (___t_1 := a[2].b) + ___t_1.c + 2 + ___t_1

src/expr_simplifier/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# Meta information for the project.
22
from __future__ import annotations
33

4+
from expr_simplifier.transforms.auto_simplify import auto_simplify as auto_simplify
5+
46
__version__ = "0.1.0"
57
__author__ = "Nyakku Shigure"
68
__year__ = "2023"
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from __future__ import annotations
2+
3+
import ast
4+
5+
from expr_simplifier.transforms.constant_folding import apply_constant_folding
6+
from expr_simplifier.transforms.cse import apply_cse
7+
from expr_simplifier.transforms.logical_simplification import apply_logical_simplification
8+
from expr_simplifier.utils import loop_until_stable
9+
10+
11+
def auto_simplify(expr: ast.AST) -> ast.AST:
12+
return loop_until_stable(expr, [apply_constant_folding, apply_logical_simplification, apply_cse], max_iter=100)

0 commit comments

Comments
 (0)