ast-pattern-engine 0.1.0__tar.gz → 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ast_pattern_engine-1.0.0/.github/workflows/ci.yml +44 -0
- ast_pattern_engine-1.0.0/.gitignore +218 -0
- ast_pattern_engine-1.0.0/LICENSE +7 -0
- ast_pattern_engine-1.0.0/PKG-INFO +103 -0
- ast_pattern_engine-1.0.0/README.md +80 -0
- ast_pattern_engine-1.0.0/examples/dict_get_rewrite.py +49 -0
- ast_pattern_engine-1.0.0/pyproject.toml +43 -0
- ast_pattern_engine-1.0.0/src/ast_pattern_engine/__init__.py +63 -0
- ast_pattern_engine-1.0.0/src/ast_pattern_engine/core.py +29 -0
- ast_pattern_engine-1.0.0/src/ast_pattern_engine/engine.py +127 -0
- ast_pattern_engine-1.0.0/src/ast_pattern_engine/nodes/basic.py +291 -0
- ast_pattern_engine-1.0.0/src/ast_pattern_engine/nodes/sequences.py +116 -0
- ast_pattern_engine-1.0.0/src/ast_pattern_engine/plumbing.py +2 -0
- ast_pattern_engine-1.0.0/src/ast_pattern_engine/py.typed +1 -0
- ast_pattern_engine-1.0.0/src/ast_pattern_engine/templates.py +56 -0
- {ast_pattern_engine-0.1.0 → ast_pattern_engine-1.0.0}/src/ast_pattern_engine/visitors.py +125 -142
- ast_pattern_engine-1.0.0/tests/patterns/test_all_of.py +26 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_any_of.py +32 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_bind.py +32 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_collect.py +15 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_contains.py +27 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_filter.py +36 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_not.py +22 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_one_of.py +84 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_optional.py +14 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_pattern_group.py +67 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_repetition.py +23 -0
- ast_pattern_engine-1.0.0/tests/patterns/test_templates.py +43 -0
- ast_pattern_engine-1.0.0/tests/test_engine.py +13 -0
- ast_pattern_engine-1.0.0/tests/visitors/test_bottom_up_pattern_transformer.py +76 -0
- ast_pattern_engine-1.0.0/tests/visitors/test_pattern_finder.py +25 -0
- ast_pattern_engine-1.0.0/tests/visitors/test_pattern_transformer.py +208 -0
- ast_pattern_engine-1.0.0/tests/visitors/test_single_occurrence_finder.py +36 -0
- ast_pattern_engine-0.1.0/.python-version +0 -1
- ast_pattern_engine-0.1.0/PKG-INFO +0 -8
- ast_pattern_engine-0.1.0/pyproject.toml +0 -21
- ast_pattern_engine-0.1.0/src/ast_pattern_engine/core.py +0 -51
- ast_pattern_engine-0.1.0/src/ast_pattern_engine/engine.py +0 -59
- ast_pattern_engine-0.1.0/src/ast_pattern_engine/nodes/basic.py +0 -172
- ast_pattern_engine-0.1.0/src/ast_pattern_engine/nodes/sequences.py +0 -68
- ast_pattern_engine-0.1.0/src/ast_pattern_engine/plumbing.py +0 -16
- ast_pattern_engine-0.1.0/tests/test_matching.py +0 -58
- ast_pattern_engine-0.1.0/uv.lock +0 -78
- {ast_pattern_engine-0.1.0/src/ast_pattern_engine → ast_pattern_engine-1.0.0/src/ast_pattern_engine/nodes}/__init__.py +0 -0
- /ast_pattern_engine-0.1.0/README.md → /ast_pattern_engine-1.0.0/tests/__init__.py +0 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [ "main" ]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [ "main" ]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
strategy:
|
|
13
|
+
matrix:
|
|
14
|
+
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
|
|
15
|
+
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v4
|
|
18
|
+
|
|
19
|
+
- name: Set up Python ${{ matrix.python-version }}
|
|
20
|
+
uses: actions/setup-python@v5
|
|
21
|
+
with:
|
|
22
|
+
python-version: ${{ matrix.python-version }}
|
|
23
|
+
|
|
24
|
+
- name: Install uv
|
|
25
|
+
uses: astral-sh/setup-uv@v5
|
|
26
|
+
with:
|
|
27
|
+
enable-cache: true
|
|
28
|
+
|
|
29
|
+
- name: Install dependencies
|
|
30
|
+
run: uv sync --all-extras
|
|
31
|
+
|
|
32
|
+
- name: Check formatting with Ruff
|
|
33
|
+
run: uv run ruff format --check
|
|
34
|
+
|
|
35
|
+
- name: Lint with Ruff
|
|
36
|
+
run: uv run ruff check
|
|
37
|
+
|
|
38
|
+
- name: Run tests with pytest
|
|
39
|
+
run: uv run pytest --cov=src --cov-report=xml
|
|
40
|
+
|
|
41
|
+
- name: Upload coverage reports to Codecov
|
|
42
|
+
uses: codecov/codecov-action@v4
|
|
43
|
+
env:
|
|
44
|
+
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
.python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
# Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
# poetry.lock
|
|
109
|
+
# poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
# pdm.lock
|
|
116
|
+
# pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
# pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# Redis
|
|
135
|
+
*.rdb
|
|
136
|
+
*.aof
|
|
137
|
+
*.pid
|
|
138
|
+
|
|
139
|
+
# RabbitMQ
|
|
140
|
+
mnesia/
|
|
141
|
+
rabbitmq/
|
|
142
|
+
rabbitmq-data/
|
|
143
|
+
|
|
144
|
+
# ActiveMQ
|
|
145
|
+
activemq-data/
|
|
146
|
+
|
|
147
|
+
# SageMath parsed files
|
|
148
|
+
*.sage.py
|
|
149
|
+
|
|
150
|
+
# Environments
|
|
151
|
+
.env
|
|
152
|
+
.envrc
|
|
153
|
+
.venv
|
|
154
|
+
env/
|
|
155
|
+
venv/
|
|
156
|
+
ENV/
|
|
157
|
+
env.bak/
|
|
158
|
+
venv.bak/
|
|
159
|
+
|
|
160
|
+
# Spyder project settings
|
|
161
|
+
.spyderproject
|
|
162
|
+
.spyproject
|
|
163
|
+
|
|
164
|
+
# Rope project settings
|
|
165
|
+
.ropeproject
|
|
166
|
+
|
|
167
|
+
# mkdocs documentation
|
|
168
|
+
/site
|
|
169
|
+
|
|
170
|
+
# mypy
|
|
171
|
+
.mypy_cache/
|
|
172
|
+
.dmypy.json
|
|
173
|
+
dmypy.json
|
|
174
|
+
|
|
175
|
+
# Pyre type checker
|
|
176
|
+
.pyre/
|
|
177
|
+
|
|
178
|
+
# pytype static type analyzer
|
|
179
|
+
.pytype/
|
|
180
|
+
|
|
181
|
+
# Cython debug symbols
|
|
182
|
+
cython_debug/
|
|
183
|
+
|
|
184
|
+
# PyCharm
|
|
185
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
186
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
188
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
189
|
+
# .idea/
|
|
190
|
+
|
|
191
|
+
# Abstra
|
|
192
|
+
# Abstra is an AI-powered process automation framework.
|
|
193
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
194
|
+
# Learn more at https://abstra.io/docs
|
|
195
|
+
.abstra/
|
|
196
|
+
|
|
197
|
+
# Visual Studio Code
|
|
198
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
199
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
200
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
201
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
202
|
+
.vscode/
|
|
203
|
+
|
|
204
|
+
# Ruff stuff:
|
|
205
|
+
.ruff_cache/
|
|
206
|
+
|
|
207
|
+
# PyPI configuration file
|
|
208
|
+
.pypirc
|
|
209
|
+
|
|
210
|
+
# Marimo
|
|
211
|
+
marimo/_static/
|
|
212
|
+
marimo/_lsp/
|
|
213
|
+
__marimo__/
|
|
214
|
+
|
|
215
|
+
# Streamlit
|
|
216
|
+
.streamlit/secrets.toml
|
|
217
|
+
|
|
218
|
+
scratch/
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2026 80sVectorz
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ast-pattern-engine
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A library for regex-inspired fine-grained AST pattern matching and replacing
|
|
5
|
+
Project-URL: Homepage, https://github.com/80sVectorz/ast_pattern_engine
|
|
6
|
+
Project-URL: Repository, https://github.com/80sVectorz/ast_pattern_engine
|
|
7
|
+
Author-email: 80sVectorz <66908776+80sVectorz@users.noreply.github.com>
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: ast,codemod,dsl,pattern-matching,refactoring
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Topic :: Software Development :: Code Generators
|
|
18
|
+
Classifier: Topic :: Software Development :: Compilers
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# AST Pattern Engine
|
|
25
|
+
|
|
26
|
+
A powerful, programmatic, regex-inspired AST pattern matching and manipulation library for Python.
|
|
27
|
+
|
|
28
|
+
## Philosophy: The "Gradual Pipeline"
|
|
29
|
+
|
|
30
|
+
Instead of relying on fragile regex on source code or magic string-to-AST parsers, `ast_pattern_engine` provides an internal DSL for building explicit, structural patterns.
|
|
31
|
+
|
|
32
|
+
It is designed with a "Gradual Pipeline" philosophy: instead of writing one massive, monolithic pattern expression to do everything at once, you chain small, focused patterns and visitors. Like casting a wide net and progressively filtering down in stages.
|
|
33
|
+
|
|
34
|
+
## Installation
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install ast_pattern_engine
|
|
38
|
+
```
|
|
39
|
+
```bash
|
|
40
|
+
uv add ast_pattern_engine
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
*(Requires Python 3.10+)*
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
Here is a simple pipeline that rewrites `dict.get("key")` calls into direct subscript access `dict["key"]`:
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from typing import Any
|
|
51
|
+
import ast
|
|
52
|
+
from ast_pattern_engine import BottomUpPatternTransformer, Bind, NodePattern
|
|
53
|
+
|
|
54
|
+
source = "value = my_dict.get(other_dict.get('foo'))"
|
|
55
|
+
tree = ast.parse(source)
|
|
56
|
+
|
|
57
|
+
# 1. Build the explicit structural pattern
|
|
58
|
+
# Matches: <obj>.get(<key>)
|
|
59
|
+
pattern = [
|
|
60
|
+
NodePattern(
|
|
61
|
+
ast.Call,
|
|
62
|
+
func=NodePattern(ast.Attribute, attr="get", value=Bind("obj")),
|
|
63
|
+
args=Bind("key"),
|
|
64
|
+
)
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
# 2. Define the rewrite logic
|
|
68
|
+
def rewrite_dict_get(bindings: dict[str, Any]) -> list[ast.AST]:
|
|
69
|
+
obj = bindings["obj"]
|
|
70
|
+
key = bindings["key"][0] # args is a list
|
|
71
|
+
|
|
72
|
+
# Return the new node to replace the matched node
|
|
73
|
+
new_node = ast.Subscript(value=obj, slice=key, ctx=ast.Load())
|
|
74
|
+
return [new_node]
|
|
75
|
+
|
|
76
|
+
# 3. Apply the transformer
|
|
77
|
+
# We use BottomUpPatternTransformer so nested `.get()` calls
|
|
78
|
+
# are safely transformed from the inside-out.
|
|
79
|
+
transformer = BottomUpPatternTransformer(pattern, {"key": rewrite_dict_get})
|
|
80
|
+
transformer.visit(tree)
|
|
81
|
+
|
|
82
|
+
print(ast.unparse(tree))
|
|
83
|
+
# Output: value = my_dict[other_dict['foo']]
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
*(See the `examples/` directory for full runnable code).*
|
|
87
|
+
|
|
88
|
+
## Primitives
|
|
89
|
+
|
|
90
|
+
The engine provides several primitives to build robust sequences:
|
|
91
|
+
- `NodePattern`: Match specific AST node types and assert on their fields.
|
|
92
|
+
- `Collect` / `Bind`: Extract sub-trees out of a matched pattern to use in your handlers.
|
|
93
|
+
- `OneOf`: Match one of several possible patterns (similar to regex `|`).
|
|
94
|
+
- `Repetition`: Match a pattern sequentially 1 or more times (similar to regex `*` and `+`).
|
|
95
|
+
- `Optional`: Match a pattern 0 or 1 times (similar to regex `?`).
|
|
96
|
+
- `Filter`: Apply arbitrary Python lambdas to check node states during matching.
|
|
97
|
+
|
|
98
|
+
## Templates
|
|
99
|
+
|
|
100
|
+
To reduce boilerplate when building patterns, the library includes a `templates` module with helpers for common operations:
|
|
101
|
+
- `match_call(func_name, **kwargs)`
|
|
102
|
+
- `match_assign(target_name, value)`
|
|
103
|
+
- `match_in_expr(pattern)`
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# AST Pattern Engine
|
|
2
|
+
|
|
3
|
+
A powerful, programmatic, regex-inspired AST pattern matching and manipulation library for Python.
|
|
4
|
+
|
|
5
|
+
## Philosophy: The "Gradual Pipeline"
|
|
6
|
+
|
|
7
|
+
Instead of relying on fragile regex on source code or magic string-to-AST parsers, `ast_pattern_engine` provides an internal DSL for building explicit, structural patterns.
|
|
8
|
+
|
|
9
|
+
It is designed with a "Gradual Pipeline" philosophy: instead of writing one massive, monolithic pattern expression to do everything at once, you chain small, focused patterns and visitors. Like casting a wide net and progressively filtering down in stages.
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install ast_pattern_engine
|
|
15
|
+
```
|
|
16
|
+
```bash
|
|
17
|
+
uv add ast_pattern_engine
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
*(Requires Python 3.10+)*
|
|
21
|
+
|
|
22
|
+
## Quick Start
|
|
23
|
+
|
|
24
|
+
Here is a simple pipeline that rewrites `dict.get("key")` calls into direct subscript access `dict["key"]`:
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from typing import Any
|
|
28
|
+
import ast
|
|
29
|
+
from ast_pattern_engine import BottomUpPatternTransformer, Bind, NodePattern
|
|
30
|
+
|
|
31
|
+
source = "value = my_dict.get(other_dict.get('foo'))"
|
|
32
|
+
tree = ast.parse(source)
|
|
33
|
+
|
|
34
|
+
# 1. Build the explicit structural pattern
|
|
35
|
+
# Matches: <obj>.get(<key>)
|
|
36
|
+
pattern = [
|
|
37
|
+
NodePattern(
|
|
38
|
+
ast.Call,
|
|
39
|
+
func=NodePattern(ast.Attribute, attr="get", value=Bind("obj")),
|
|
40
|
+
args=Bind("key"),
|
|
41
|
+
)
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
# 2. Define the rewrite logic
|
|
45
|
+
def rewrite_dict_get(bindings: dict[str, Any]) -> list[ast.AST]:
|
|
46
|
+
obj = bindings["obj"]
|
|
47
|
+
key = bindings["key"][0] # args is a list
|
|
48
|
+
|
|
49
|
+
# Return the new node to replace the matched node
|
|
50
|
+
new_node = ast.Subscript(value=obj, slice=key, ctx=ast.Load())
|
|
51
|
+
return [new_node]
|
|
52
|
+
|
|
53
|
+
# 3. Apply the transformer
|
|
54
|
+
# We use BottomUpPatternTransformer so nested `.get()` calls
|
|
55
|
+
# are safely transformed from the inside-out.
|
|
56
|
+
transformer = BottomUpPatternTransformer(pattern, {"key": rewrite_dict_get})
|
|
57
|
+
transformer.visit(tree)
|
|
58
|
+
|
|
59
|
+
print(ast.unparse(tree))
|
|
60
|
+
# Output: value = my_dict[other_dict['foo']]
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
*(See the `examples/` directory for full runnable code).*
|
|
64
|
+
|
|
65
|
+
## Primitives
|
|
66
|
+
|
|
67
|
+
The engine provides several primitives to build robust sequences:
|
|
68
|
+
- `NodePattern`: Match specific AST node types and assert on their fields.
|
|
69
|
+
- `Collect` / `Bind`: Extract sub-trees out of a matched pattern to use in your handlers.
|
|
70
|
+
- `OneOf`: Match one of several possible patterns (similar to regex `|`).
|
|
71
|
+
- `Repetition`: Match a pattern sequentially 1 or more times (similar to regex `*` and `+`).
|
|
72
|
+
- `Optional`: Match a pattern 0 or 1 times (similar to regex `?`).
|
|
73
|
+
- `Filter`: Apply arbitrary Python lambdas to check node states during matching.
|
|
74
|
+
|
|
75
|
+
## Templates
|
|
76
|
+
|
|
77
|
+
To reduce boilerplate when building patterns, the library includes a `templates` module with helpers for common operations:
|
|
78
|
+
- `match_call(func_name, **kwargs)`
|
|
79
|
+
- `match_assign(target_name, value)`
|
|
80
|
+
- `match_in_expr(pattern)`
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Dictionary get method rewrite example.
|
|
2
|
+
|
|
3
|
+
This example shows how to use the AST Pattern Engine to rewrite all `dict.get("key")` calls
|
|
4
|
+
into direct dictionary subscript access `dict["key"]`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any
|
|
8
|
+
import ast
|
|
9
|
+
from ast_pattern_engine import BottomUpPatternTransformer, Bind, NodePattern
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_dict_get_rewrite() -> None:
|
|
13
|
+
source = "value = my_dict.get(other_dict.get('foo'))"
|
|
14
|
+
tree = ast.parse(source)
|
|
15
|
+
|
|
16
|
+
# 1. Build the explicit structural pattern
|
|
17
|
+
# Matches: <obj>.get(<key>)
|
|
18
|
+
pattern = [
|
|
19
|
+
NodePattern(
|
|
20
|
+
ast.Call,
|
|
21
|
+
func=NodePattern(ast.Attribute, attr="get", value=Bind("obj")),
|
|
22
|
+
args=Bind("key"),
|
|
23
|
+
)
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
# 2. Define the rewrite logic
|
|
27
|
+
def rewrite_dict_get(bindings: dict[str, Any]) -> list[ast.AST]:
|
|
28
|
+
obj = bindings["obj"]
|
|
29
|
+
key = bindings["key"][0] # args is a list
|
|
30
|
+
|
|
31
|
+
# Return the new node to replace the matched node
|
|
32
|
+
new_node = ast.Subscript(value=obj, slice=key, ctx=ast.Load())
|
|
33
|
+
return [new_node]
|
|
34
|
+
|
|
35
|
+
# 3. Apply the transformer
|
|
36
|
+
# We use BottomUpPatternTransformer so that nested `.get()` calls
|
|
37
|
+
# are transformed from the inside-out successfully.
|
|
38
|
+
transformer = BottomUpPatternTransformer(pattern, {"key": rewrite_dict_get})
|
|
39
|
+
transformer.visit(tree)
|
|
40
|
+
|
|
41
|
+
new_source = ast.unparse(tree)
|
|
42
|
+
print("Rewritten source:\n", new_source)
|
|
43
|
+
|
|
44
|
+
# Assert for validation
|
|
45
|
+
assert new_source == "value = my_dict[other_dict['foo']]"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
if __name__ == "__main__":
|
|
49
|
+
test_dict_get_rewrite()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ast-pattern-engine"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "A library for regex-inspired fine-grained AST pattern matching and replacing"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "80sVectorz", email = "66908776+80sVectorz@users.noreply.github.com" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
keywords = ["ast", "pattern-matching", "refactoring", "codemod", "dsl"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"Topic :: Software Development :: Code Generators",
|
|
14
|
+
"Topic :: Software Development :: Compilers",
|
|
15
|
+
"Programming Language :: Python :: 3.10",
|
|
16
|
+
"Programming Language :: Python :: 3.11",
|
|
17
|
+
"Programming Language :: Python :: 3.12",
|
|
18
|
+
"Programming Language :: Python :: 3.13",
|
|
19
|
+
"Programming Language :: Python :: 3.14",
|
|
20
|
+
"License :: OSI Approved :: MIT License",
|
|
21
|
+
]
|
|
22
|
+
dependencies = []
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/80sVectorz/ast_pattern_engine"
|
|
26
|
+
Repository = "https://github.com/80sVectorz/ast_pattern_engine"
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
dev = ["pytest"]
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["hatchling"]
|
|
33
|
+
build-backend = "hatchling.build"
|
|
34
|
+
|
|
35
|
+
[tool.pytest.ini_options]
|
|
36
|
+
addopts = "-q"
|
|
37
|
+
filterwarnings = "error"
|
|
38
|
+
pythonpath = ["src"]
|
|
39
|
+
|
|
40
|
+
[dependency-groups]
|
|
41
|
+
dev = [
|
|
42
|
+
"pytest-cov>=7.1.0",
|
|
43
|
+
]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""AST Pattern Engine - A programmatic, regex-inspired AST pattern matching and manipulation library."""
|
|
2
|
+
|
|
3
|
+
from .core import Pattern, SequencePattern
|
|
4
|
+
from .engine import match_sequence
|
|
5
|
+
from .nodes.basic import (
|
|
6
|
+
NodePattern,
|
|
7
|
+
WildCard,
|
|
8
|
+
Collect,
|
|
9
|
+
Filter,
|
|
10
|
+
Not,
|
|
11
|
+
Contains,
|
|
12
|
+
AllOf,
|
|
13
|
+
AnyOf,
|
|
14
|
+
Bind,
|
|
15
|
+
)
|
|
16
|
+
from .nodes.sequences import (
|
|
17
|
+
Repetition,
|
|
18
|
+
PatternGroup,
|
|
19
|
+
OneOf,
|
|
20
|
+
Optional,
|
|
21
|
+
)
|
|
22
|
+
from .visitors import (
|
|
23
|
+
PatternTransformer,
|
|
24
|
+
BottomUpPatternTransformer,
|
|
25
|
+
PatternFinder,
|
|
26
|
+
SingleOccurrenceFinder,
|
|
27
|
+
)
|
|
28
|
+
from .templates import (
|
|
29
|
+
match_in_expr,
|
|
30
|
+
match_call,
|
|
31
|
+
match_assign,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
# Core
|
|
36
|
+
"Pattern",
|
|
37
|
+
"SequencePattern",
|
|
38
|
+
"match_sequence",
|
|
39
|
+
# Basic Nodes
|
|
40
|
+
"NodePattern",
|
|
41
|
+
"WildCard",
|
|
42
|
+
"Collect",
|
|
43
|
+
"Filter",
|
|
44
|
+
"Not",
|
|
45
|
+
"Contains",
|
|
46
|
+
"AllOf",
|
|
47
|
+
"AnyOf",
|
|
48
|
+
"Bind",
|
|
49
|
+
# Sequences
|
|
50
|
+
"Repetition",
|
|
51
|
+
"PatternGroup",
|
|
52
|
+
"OneOf",
|
|
53
|
+
"Optional",
|
|
54
|
+
# Visitors
|
|
55
|
+
"PatternTransformer",
|
|
56
|
+
"BottomUpPatternTransformer",
|
|
57
|
+
"PatternFinder",
|
|
58
|
+
"SingleOccurrenceFinder",
|
|
59
|
+
# Templates
|
|
60
|
+
"match_in_expr",
|
|
61
|
+
"match_call",
|
|
62
|
+
"match_assign",
|
|
63
|
+
]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import ast
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Pattern(ast.AST):
|
|
7
|
+
"""Base class for AST matching patterns."""
|
|
8
|
+
|
|
9
|
+
# public API
|
|
10
|
+
def match_node(
|
|
11
|
+
self, node: object, bindings: dict[str, object] | None = None, *, _force_list: bool = False
|
|
12
|
+
):
|
|
13
|
+
"""Match *node* and return updated *bindings* or *None*."""
|
|
14
|
+
raise NotImplementedError
|
|
15
|
+
|
|
16
|
+
# helpers
|
|
17
|
+
@staticmethod
|
|
18
|
+
def _to_list(val: Any) -> list[Any]:
|
|
19
|
+
return val if isinstance(val, list) else [val]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SequencePattern(Pattern):
|
|
23
|
+
def match_node(
|
|
24
|
+
self, node: object, bindings: dict[str, object] | None = None, *, _force_list: bool = False
|
|
25
|
+
):
|
|
26
|
+
# Matching is handled by engine._match_sequence
|
|
27
|
+
raise NotImplementedError(
|
|
28
|
+
f"{self.__class__.__name__} node does not support matching single AST node."
|
|
29
|
+
)
|