80sVectorz/ast_pattern_engine

GitHub: 80sVectorz/ast_pattern_engine

一个受正则表达式启发的 Python AST 模式匹配与变换库,通过内部 DSL 实现声明式的代码结构匹配和自动化重写。

Stars: 1 | Forks: 0

![PyPI - Version](https://img.shields.io/pypi/v/ast-pattern-engine) ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ast-pattern-engine) ![Pytest](https://img.shields.io/badge/pytest-tested-orange) ![MIT License](https://img.shields.io/badge/License-MIT-blue) ![Codecov](https://codecov.io/gh/80sVectorz/ast_pattern_engine/branch/main/graph/badge.svg) ![GitHub Workflow Status](https://static.pigsec.cn/wp-content/uploads/repos/cas/ad/ad5834178f7599af9fdda11629d49cae07f2997beec49821b2920eff5bfd50e7.svg) # AST Pattern Engine 一个强大的、可编程的、受 regex 启发的,用于 Python 的 AST 模式匹配与操作库。 ## 理念:“渐进式 Pipeline” `ast_pattern_engine` 不再依赖于对源代码使用脆弱的 regex,或是神奇的字符串到 AST 解析器,而是提供了一个内部 DSL 来构建显式的、结构化的模式。 它的设计遵循“渐进式 Pipeline”理念:与其编写一个庞大的、单体模式表达式来一次性完成所有工作,不如将小的、专注的模式和访问器链接起来。就像撒下一张大网,然后分阶段逐步过滤。 ## 安装 ``` pip install ast_pattern_engine ``` ``` uv add ast_pattern_engine ``` *(要求 Python 3.10+)* ## 快速开始 这是一个简单的 pipeline,它将 `dict.get("key")` 调用重写为直接的下标访问 `dict["key"]`: ``` from typing import Any import ast from ast_pattern_engine import BottomUpPatternTransformer, Bind, NodePattern source = "value = my_dict.get(other_dict.get('foo'))" tree = ast.parse(source) # 1. 构建显式结构化 pattern # Matches: .get() pattern = [ NodePattern( ast.Call, func=NodePattern(ast.Attribute, attr="get", value=Bind("obj")), args=Bind("key"), ) ] # 2. 定义 rewrite 逻辑 def rewrite_dict_get(bindings: dict[str, Any]) -> list[ast.AST]: obj = bindings["obj"] key = bindings["key"][0] # args is a list # Return the new node to replace the matched node new_node = ast.Subscript(value=obj, slice=key, ctx=ast.Load()) return [new_node] # 3. 应用 transformer # 我们使用 BottomUpPatternTransformer,以便嵌套的 `.get()` 调用 # 能够安全地从内到外进行转换。 transformer = BottomUpPatternTransformer(pattern, {"key": rewrite_dict_get}) transformer.visit(tree) print(ast.unparse(tree)) # Output: value = my_dict[other_dict['foo']] ``` *(完整可运行代码请参见 `examples/` 目录)。* ## 基本组件 该引擎提供了几种基本组件来构建稳健的序列: - `NodePattern`:匹配特定的 AST 节点类型并断言其字段。 - `Collect` / `Bind`:从匹配的模式中提取子树,以便在您的处理程序中使用。 - `OneOf`:匹配多个可能模式中的一个(类似于 regex 的 `|`)。 - `Repetition`:按顺序匹配某个模式 1 次或多次(类似于 regex 的 `*` 和 `+`)。 - `Optional`:匹配某个模式 0 次或 1 次(类似于 regex 的 `?`)。 - `Filter`:在匹配过程中应用任意的 Python lambda 表达式来检查节点状态。 ## 模板 为了减少构建模式时的样板代码,该库包含一个 `templates` 模块,其中提供了用于常见操作的辅助函数: - `match_call(func_name, **kwargs)` - `match_assign(target_name, value)` - `match_in_expr(pattern)`
标签:Python, SOC Prime, 代码分析, 代码重构, 凭证管理, 安全规则引擎, 开发工具, 无后门, 模式匹配, 自动化资产收集, 逆向工具