ast-grep-search

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ast-grep Structural Code Search & Refactoring

ast-grep 结构化代码搜索与重构

Structural code search and refactoring using
ast-grep
— matches code by its AST (abstract syntax tree) rather than text patterns.
使用
ast-grep
实现结构化代码搜索与重构——它基于 AST(抽象语法树)而非文本模式匹配代码。

When to Use ast-grep vs Grep/ripgrep

何时选择 ast-grep 还是 Grep/ripgrep

Use ast-grep when...Use grep/rg when...
Pattern depends on code structureSimple text or regex match
Need to match any number of argumentsSearching logs, docs, config
Refactoring across many filesOne-off literal string search
Finding anti-patterns (empty catch, etc.)Language doesn't matter
Replacing while preserving variablesQuick filename/line check
Decision rule: If your search pattern contains wildcards for "any expression," "any arguments," or "any function name," use ast-grep.
适合使用 ast-grep 的场景适合使用 grep/rg 的场景
匹配模式依赖代码结构简单的文本或正则匹配
需要匹配任意数量的参数搜索日志、文档、配置文件
跨多文件执行重构一次性字面量字符串搜索
查找代码反模式(如空 catch 块等)不限制搜索内容的语言类型
替换内容同时保留变量快速检查文件名/行号
决策规则:如果你的搜索模式包含「任意表达式」、「任意参数」或「任意函数名」这类通配需求,请使用 ast-grep。

Pattern Syntax

模式语法

PatternMatchesExample
$VAR
Single AST node
console.log($MSG)
$$$ARGS
Zero or more nodes
func($$$ARGS)
$_
Single node (no capture)
$_ == $_
$A == $A
Same node repeatedFinds
x == x
(not
x == y
)
模式匹配规则示例
$VAR
单个 AST 节点
console.log($MSG)
$$$ARGS
零个或多个节点
func($$$ARGS)
$_
单个节点(不捕获)
$_ == $_
$A == $A
重复出现的相同节点可匹配
x == x
(不会匹配
x == y

Essential Commands

核心命令

Search for Patterns

搜索模式

bash
undefined
bash
undefined

Find structural patterns

查找结构化模式

ast-grep -p 'console.log($$$)' --lang js ast-grep -p 'def $FUNC($$$): $$$' --lang py ast-grep -p 'fn $NAME($$$) -> $RET { $$$ }' --lang rs
ast-grep -p 'console.log($$$)' --lang js ast-grep -p 'def $FUNC($$$): $$$' --lang py ast-grep -p 'fn $NAME($$$) -> $RET { $$$ }' --lang rs

Search in specific directory

在指定目录下搜索

ast-grep -p 'import $PKG' --lang js src/
ast-grep -p 'import $PKG' --lang js src/

JSON output for parsing

输出JSON格式结果用于后续解析

ast-grep -p 'pattern' --lang js --json=compact
undefined
ast-grep -p 'pattern' --lang js --json=compact
undefined

Search and Replace

搜索并替换

bash
undefined
bash
undefined

Preview changes (default - shows matches)

预览变更(默认行为,仅展示匹配结果)

ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js
ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js

Apply changes to all files

对所有文件应用变更

ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js -U
ast-grep -p 'var $V = $X' -r 'const $V = $X' --lang js -U

Interactive review

交互式审核变更

ast-grep -p 'oldAPI($$$ARGS)' -r 'newAPI($$$ARGS)' --lang py -i
ast-grep -p 'oldAPI($$$ARGS)' -r 'newAPI($$$ARGS)' --lang py -i

Convert function syntax

转换函数语法

ast-grep -p 'function($$$ARGS) { return $EXPR }'
-r '($$$ARGS) => $EXPR' --lang js -U
ast-grep -p 'function($$$ARGS) { return $EXPR }'
-r '($$$ARGS) => $EXPR' --lang js -U

Update import paths

更新导入路径

ast-grep -p "import $NAME from '@old/$PATH'"
-r "import $NAME from '@new/$PATH'" --lang ts -U
undefined
ast-grep -p "import $NAME from '@old/$PATH'"
-r "import $NAME from '@new/$PATH'" --lang ts -U
undefined

Language Codes

语言代码对照表

CodeLanguageCodeLanguage
js
JavaScript
py
Python
ts
TypeScript
rs
Rust
jsx
JSX
go
Go
tsx
TSX
java
Java
cpp
C++
rb
Ruby
c
C
php
PHP
代码编程语言代码编程语言
js
JavaScript
py
Python
ts
TypeScript
rs
Rust
jsx
JSX
go
Go
tsx
TSX
java
Java
cpp
C++
rb
Ruby
c
C
php
PHP

Common Patterns by Language

各语言常用模式

JavaScript/TypeScript

JavaScript/TypeScript

bash
undefined
bash
undefined

Find React hooks

查找 React hooks

ast-grep -p 'const [$STATE, $SETTER] = useState($INIT)' --lang jsx
ast-grep -p 'const [$STATE, $SETTER] = useState($INIT)' --lang jsx

Find async functions

查找 async 函数

ast-grep -p 'async function $NAME($$$) { $$$ }' --lang js
ast-grep -p 'async function $NAME($$$) { $$$ }' --lang js

Find type assertions

查找类型断言

ast-grep -p '$EXPR as $TYPE' --lang ts
ast-grep -p '$EXPR as $TYPE' --lang ts

Find empty catch blocks

查找空 catch 块

ast-grep -p 'try { $$$ } catch ($E) { }' --lang js
ast-grep -p 'try { $$$ } catch ($E) { }' --lang js

Find eval usage (security)

查找 eval 用法(安全风险)

ast-grep -p 'eval($$$)' --lang js
ast-grep -p 'eval($$$)' --lang js

Find innerHTML (XSS risk)

查找 innerHTML 用法(XSS 风险)

ast-grep -p '$ELEM.innerHTML = $$$' --lang js
ast-grep -p '$ELEM.innerHTML = $$$' --lang js

Find specific imports

查找指定导入

ast-grep -p "import { $$$IMPORTS } from '$PKG'" --lang js
undefined
ast-grep -p "import { $$$IMPORTS } from '$PKG'" --lang js
undefined

Python

Python

bash
undefined
bash
undefined

Find class definitions

查找类定义

ast-grep -p 'class $NAME($$$BASES): $$$' --lang py
ast-grep -p 'class $NAME($$$BASES): $$$' --lang py

Find decorated functions

查找带装饰器的函数

ast-grep -p '@$DECORATOR\ndef $FUNC($$$): $$$' --lang py
ast-grep -p '@$DECORATOR\ndef $FUNC($$$): $$$' --lang py

Find dangerous shell calls

查找危险的 shell 调用

ast-grep -p 'os.system($$$)' --lang py
ast-grep -p 'os.system($$$)' --lang py

Find SQL concatenation (injection risk)

查找 SQL 拼接(注入风险)

ast-grep -p '"SELECT * FROM " + $VAR' --lang py
undefined
ast-grep -p '"SELECT * FROM " + $VAR' --lang py
undefined

Rust

Rust

bash
undefined
bash
undefined

Find unsafe blocks

查找 unsafe 块

ast-grep -p 'unsafe { $$$ }' --lang rs
ast-grep -p 'unsafe { $$$ }' --lang rs

Find impl blocks

查找 impl 块

ast-grep -p 'impl $TRAIT for $TYPE { $$$ }' --lang rs
ast-grep -p 'impl $TRAIT for $TYPE { $$$ }' --lang rs

Find public functions

查找公共函数

ast-grep -p 'pub fn $NAME($$$) { $$$ }' --lang rs
undefined
ast-grep -p 'pub fn $NAME($$$) { $$$ }' --lang rs
undefined

Go

Go

bash
undefined
bash
undefined

Find goroutines

查找 goroutine

ast-grep -p 'go $FUNC($$$)' --lang go
ast-grep -p 'go $FUNC($$$)' --lang go

Find defer statements

查找 defer 语句

ast-grep -p 'defer $FUNC($$$)' --lang go
ast-grep -p 'defer $FUNC($$$)' --lang go

Find error handling

查找错误处理逻辑

ast-grep -p 'if err != nil { $$$ }' --lang go
undefined
ast-grep -p 'if err != nil { $$$ }' --lang go
undefined

Common Refactoring Recipes

常用重构方案

bash
undefined
bash
undefined

Replace deprecated API calls

替换废弃的 API 调用

ast-grep -p 'oldAPI.$METHOD($$$)' -r 'newAPI.$METHOD($$$)' --lang js -U
ast-grep -p 'oldAPI.$METHOD($$$)' -r 'newAPI.$METHOD($$$)' --lang js -U

Rename a function across files

跨文件重命名函数

ast-grep -p 'oldName($$$ARGS)' -r 'newName($$$ARGS)' --lang py -U
ast-grep -p 'oldName($$$ARGS)' -r 'newName($$$ARGS)' --lang py -U

Remove console.log statements

移除 console.log 语句

ast-grep -p 'console.log($$$)' -r '' --lang js -U
ast-grep -p 'console.log($$$)' -r '' --lang js -U

Convert require to import

将 require 转换为 import

ast-grep -p 'const $NAME = require($PKG)'
-r 'import $NAME from $PKG' --lang js -i
ast-grep -p 'const $NAME = require($PKG)'
-r 'import $NAME from $PKG' --lang js -i

Add error handling wrapper

添加错误处理包装

ast-grep -p 'await $EXPR'
-r 'await $EXPR.catch(handleError)' --lang ts -i
undefined
ast-grep -p 'await $EXPR'
-r 'await $EXPR.catch(handleError)' --lang ts -i
undefined

Command-Line Flags

命令行参数

FlagPurpose
-p, --pattern
Search pattern
-r, --rewrite
Replacement pattern
-l, --lang
Target language
-i, --interactive
Review changes one by one
-U, --update-all
Apply all changes
--json
JSON output (
compact
,
stream
,
pretty
)
-A N
Lines after match
-B N
Lines before match
-C N
Lines around match
--debug-query
Debug pattern parsing
参数用途
-p, --pattern
搜索模式
-r, --rewrite
替换模式
-l, --lang
目标语言
-i, --interactive
逐次审核变更
-U, --update-all
应用所有变更
--json
JSON 格式输出(可选
compact
stream
pretty
-A N
展示匹配结果后N行
-B N
展示匹配结果前N行
-C N
展示匹配结果前后N行
--debug-query
调试模式解析查询

YAML Rules (Scan Mode)

YAML 规则(扫描模式)

For reusable rules, use
ast-grep scan
with YAML configuration:
bash
undefined
如果需要复用规则,可以搭配 YAML 配置使用
ast-grep scan
命令:
bash
undefined

Scan with config

使用配置文件扫描

ast-grep scan -c sgconfig.yml
ast-grep scan -c sgconfig.yml

Run specific rule

运行指定规则

ast-grep scan -r rule-name
ast-grep scan -r rule-name

Initialize a rules project

初始化规则项目

ast-grep new project my-linter ast-grep new rule no-console-log

Minimal rule file:
```yaml
id: no-empty-catch
language: JavaScript
severity: warning
message: Empty catch block hides errors
rule:
  pattern: try { $$$ } catch ($E) { }
fix: |
  try { $$$ } catch ($E) { console.error($E) }
For comprehensive YAML rule syntax, constraints, transformations, and testing, see REFERENCE.md.
ast-grep new project my-linter ast-grep new rule no-console-log

最小规则文件示例:
```yaml
id: no-empty-catch
language: JavaScript
severity: warning
message: Empty catch block hides errors
rule:
  pattern: try { $$$ } catch ($E) { }
fix: |
  try { $$$ } catch ($E) { console.error($E) }
完整的 YAML 规则语法、约束、转换和测试方法请参考 REFERENCE.md

Agentic Optimizations

智能优化场景

ContextCommand
Quick structural search
ast-grep -p 'pattern' --lang js --json=compact
Count matches
ast-grep -p 'pattern' --lang js --json=stream | wc -l
File list only
ast-grep -p 'pattern' --json=stream | jq -r '.file' | sort -u
Batch refactor
ast-grep -p 'old' -r 'new' --lang js -U
Scan with rules
ast-grep scan --json
Debug pattern
ast-grep -p 'pattern' --debug-query --lang js
场景命令
快速结构化搜索
ast-grep -p 'pattern' --lang js --json=compact
统计匹配数量
ast-grep -p 'pattern' --lang js --json=stream | wc -l
仅输出匹配的文件列表
ast-grep -p 'pattern' --json=stream | jq -r '.file' | sort -u
批量重构
ast-grep -p 'old' -r 'new' --lang js -U
使用规则扫描
ast-grep scan --json
调试模式解析规则
ast-grep -p 'pattern' --debug-query --lang js

Quick Reference

快速参考

bash
undefined
bash
undefined

1. Search for pattern

1. 搜索模式

ast-grep -p 'pattern' --lang js src/
ast-grep -p 'pattern' --lang js src/

2. Preview rewrite

2. 预览替换效果

ast-grep -p 'old' -r 'new' --lang js
ast-grep -p 'old' -r 'new' --lang js

3. Apply rewrite

3. 应用替换

ast-grep -p 'old' -r 'new' --lang js -U
ast-grep -p 'old' -r 'new' --lang js -U

4. Scan with rules

4. 使用规则扫描

ast-grep scan -c sgconfig.yml
ast-grep scan -c sgconfig.yml

5. Debug pattern

5. 调试模式解析规则

ast-grep -p 'pattern' --debug-query --lang js
undefined
ast-grep -p 'pattern' --debug-query --lang js
undefined