ast-grep
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseast-grep
ast-grep
Workflow
工作流
- Write a test snippet representing the target code
- Write the rule (start with , escalate to
pattern+kind/hasif needed)inside - Test with before searching the codebase
--stdin - Search the codebase once the rule matches
- 编写代表目标代码的测试片段
- 编写规则(从 开始,必要时升级为
pattern+kind/has组合)inside - 在搜索整个代码库前,先用 测试
--stdin - 规则匹配成功后,再对代码库进行全量搜索
Critical Gotchas
关键注意事项
Always use stopBy: end
on relational rules
stopBy: end关系型规则务必使用 stopBy: end
stopBy: endWithout it, / stop at the first non-matching node instead of traversing the full subtree:
hasinsideyaml
undefined若缺少该配置,/ 会在第一个不匹配的节点处停止,而不会遍历完整的子树:
hasinsideyaml
undefinedWRONG — will miss deeply nested matches
WRONG — will miss deeply nested matches
has:
pattern: await $EXPR
has:
pattern: await $EXPR
RIGHT
RIGHT
has:
pattern: await $EXPR
stopBy: end
undefinedhas:
pattern: await $EXPR
stopBy: end
undefinedEscape metavariables in shell
在 Shell 中转义元变量
$VARbash
undefined$VARbash
undefinedDouble-quoted: escape with backslash
Double-quoted: escape with backslash
ast-grep scan --inline-rules "id: test
language: javascript
rule:
pattern: await $EXPR" .
ast-grep scan --inline-rules "id: test
language: javascript
rule:
pattern: await $EXPR" .
Single-quoted: no escaping needed
Single-quoted: no escaping needed
ast-grep scan --inline-rules 'id: test
language: javascript
rule:
pattern: await $EXPR' .
undefinedast-grep scan --inline-rules 'id: test
language: javascript
rule:
pattern: await $EXPR' .
undefinedMetavariables must be the sole content of an AST node
元变量必须是 AST 节点的唯一内容
These don't work: , , ,
obj.on$EVENT"Hello $WORLD"a $OP b$jqUse for unnamed nodes (operators, punctuation). Use for zero-or-more nodes.
$$OP$$$ARGS以下写法无效:、、、
obj.on$EVENT"Hello $WORLD"a $OP b$jq对于未命名节点(运算符、标点符号),请使用 ;对于零个或多个节点,请使用 。
$$OP$$$ARGSTesting with --stdin
使用 --stdin 进行测试
bash
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' --stdinbash
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' --stdinDebugging with --debug-query
使用 --debug-query 调试
When rules don't match, inspect the AST to find correct values:
kindbash
ast-grep run --pattern 'your code here' --lang javascript --debug-query=cstFormats: (all nodes), (named only), (how ast-grep sees your pattern).
cstastpattern当规则无法匹配时,检查 AST 以找到正确的 值:
kindbash
ast-grep run --pattern 'your code here' --lang javascript --debug-query=cst格式选项:(所有节点)、(仅命名节点)、(ast-grep 解析后的模式结构)。
cstastpatternRule syntax
规则语法
See for the full rule reference (atomic, relational, composite rules, and metavariables).
references/rule_reference.md完整的规则参考(原子规则、关系规则、复合规则及元变量)请查看 。
references/rule_reference.md