ast-grep
工作流程
- 寫一個代表目標程式碼的測試片段
- 撰寫規則(先從
pattern開始,必要時升級到kind+has/inside) - 在搜尋程式碼庫之前,先用
--stdin測試規則 - 規則符合後再搜尋整個程式碼庫
關鍵注意事項
在關係規則上務必使用 stopBy: end
如果不使用,has / inside 會在第一個不符合的節點處停止,而非遍歷整個子樹:
# 錯誤——會遺漏深層巢狀的匹配
has:
pattern: await $EXPR
# 正確
has:
pattern: await $EXPR
stopBy: end
在 shell 中跳脫元變數
$VAR 會被 shell 解譯。請使用跳脫或單引號:
# 雙引號:用反斜線跳脫
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' .
元變數必須是 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。