名称: 结构搜索
description: “使用ast-grep通过AST结构搜索代码。查找函数调用、导入、类定义等语义模式,而非文本模式。触发条件:查找所有对X的调用、搜索模式、重构用法、查找函数使用位置、结构搜索、ast-grep、sg。”
兼容性: “需要ast-grep (sg) CLI工具。安装:brew install ast-grep (macOS) 或 cargo install ast-grep (跨平台)。”
允许工具: “Bash”
结构搜索
通过抽象语法树(AST)结构搜索代码。查找正则表达式无法可靠匹配的语义模式。
工具
| 工具 |
命令 |
用途 |
| ast-grep |
sg -p '模式' |
AST感知的代码搜索 |
模式语法
| 模式 |
匹配内容 |
示例 |
$NAME |
命名标识符 |
function $NAME() {} |
$_ |
任意单个节点 |
console.log($_) |
$$$ |
零个或多个节点 |
function $_($$$) {} |
十大必备模式
# 1. 查找console.log调用
sg -p 'console.log($_)'
# 2. 查找React钩子
sg -p 'const [$_, $_] = useState($_)'
sg -p 'useEffect($_, [$$$])'
# 3. 查找函数定义
sg -p 'function $NAME($$$) { $$$ }'
sg -p 'def $NAME($$$): $$$' --lang python
# 4. 查找导入
sg -p 'import $_ from "$_"'
sg -p 'from $_ import $_' --lang python
# 5. 查找异步模式
sg -p 'await $_'
sg -p 'async function $NAME($$$) { $$$ }'
# 6. 查找错误处理
sg -p 'try { $$$ } catch ($_) { $$$ }'
sg -p 'if err != nil { $$$ }' --lang go
# 7. 查找潜在问题
sg -p '$_ == $_' # 使用==而非===
sg -p 'eval($_)' # 安全风险
sg -p '$_.innerHTML = $_' # XSS向量
# 8. 预览重构
sg -p 'console.log($_)' -r 'logger.info($_)'
# 9. 应用重构
sg -p 'var $NAME = $_' -r 'const $NAME = $_' --rewrite
# 10. 搜索特定语言
sg -p '模式' --lang typescript
快速参考
| 任务 |
命令 |
| 查找模式 |
sg -p '模式' |
| 特定语言 |
sg -p '模式' --lang python |
| 替换(预览) |
sg -p '旧模式' -r '新模式' |
| 替换(应用) |
sg -p '旧模式' -r '新模式' --rewrite |
| 显示上下文 |
sg -p '模式' -A 3 |
| JSON输出 |
sg -p '模式' --json |
| 仅文件列表 |
sg -p '模式' -l |
| 统计匹配数 |
sg -p '模式' --count |
| 运行YAML规则 |
sg scan |
使用场景
- 查找函数/方法的所有用法
- 定位特定代码模式(钩子、API调用)
- 准备大规模重构
- 当正则表达式会产生误报时
- 检测反模式和安全隐患
- 创建自定义代码检查规则
额外资源
完整模式请加载:
./references/js-ts-patterns.md - JavaScript/TypeScript模式
./references/python-patterns.md - Python模式
./references/go-rust-patterns.md - Go和Rust模式
./references/security-patterns.md - 安全漏洞检测
./references/advanced-usage.md - YAML规则和工具集成
./assets/rule-template.yaml - 自定义规则入门模板