关于 ast-grep
用于编写和调试 ast-grep 语法搜索规则的 Skill,介绍从测试片段构建规则、用 `--stdin` 验证,以及检查 AST 查询。
主要功能
- 01从测试片段构建规则
- 02使用 `--stdin` 测试规则
- 03用 `--debug-query` 检查查询
- 04处理关系规则的节点遍历
- 05正确转义 Shell 元变量
适用场景
- 01在代码库中查找语法模式
- 02全库搜索前验证规则
- 03调试未匹配嵌套节点的规则
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ poteto/ noodle --skill ast-grep安装后在 Claude Code 中输入/ast-grep确认已加载。
附带文件references/rule_reference.md
详细介绍
ast-grep
工作流
- 编写一个表示目标代码的测试片段
- 编写规则(从
pattern开始,必要时升级为kind+has/inside) - 搜索代码库前,先用
--stdin测试 - 规则匹配后,再搜索代码库
关键注意事项
关系规则务必使用 stopBy: end
如果不使用它,has/inside 会在遇到第一个不匹配的节点时停止,而不会遍历整个子树:
# WRONG — will miss deeply nested matches
has:
pattern: await $EXPR
# RIGHT
has:
pattern: await $EXPR
stopBy: end
在 Shell 中转义元变量
$VAR 会被 Shell 解释。请转义或使用单引号:
# Double-quoted: escape with backslash
ast-grep scan --inline-rules "id: test
language: javascript
rule:
pattern: await \$EXPR" .
# Single-quoted: no escaping needed
ast-grep scan --inline-rules 'id: test
language: javascript
rule:
pattern: await $EXPR' .
元变量必须是 AST 节点中唯一的内容
以下用法无效:obj.on$EVENT、"Hello $WORLD"、a $OP b、$jq
对于未命名节点(运算符、标点),请使用 $$OP。对于零个或多个节点,请使用 $$$ARGS。
使用 --stdin 测试
echo "async function test() { await fetch(); }" | ast-grep scan --inline-rules 'id: test
language: javascript
rule:
kind: function_declaration
has:
pattern: await $EXPR
stopBy: end' --stdin
使用 --debug-query 调试
规则不匹配时,请检查 AST,找到正确的 kind 值:
ast-grep run --pattern 'your code here' --lang javascript --debug-query=cst
格式:cst(所有节点)、ast(仅命名节点)、pattern(ast-grep 对模式的解析方式)。
规则语法
完整的规则参考(原子规则、关系规则、组合规则和元变量)请参阅 references/rule_reference.md。
评论
支持 Markdown