ast-code-graph
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAST & Code Graph Indexing
AST & Code Graph Indexing
Overview
概述
Text-based search (, ) finds string matches. AST-based analysis understands structure — it knows the difference between a function definition, a function call, a comment, and a string literal.
grepripgrepPrimary tool: ast-grep ( / ) — a fast, Rust-based CLI for structural code search, lint, and rewriting. It uses tree-sitter for parsing and supports 20+ languages out of the box.
sgast-grepCore principle: When the question is about code structure, use AST analysis. When the question is about text content, use grep.
基于文本的搜索(、)查找字符串匹配项。基于AST的分析则能理解代码结构——它可以区分函数定义、函数调用、注释和字符串字面量之间的差异。
grepripgrep核心工具: ast-grep( / )——一款基于Rust开发的快速CLI工具,用于结构化代码搜索、代码检查与重写。它使用tree-sitter进行解析,开箱即支持20+种编程语言。
sgast-grep核心原则: 当需求涉及代码结构时,使用AST分析;当需求涉及文本内容时,使用grep。
When to Use
适用场景
Use this skill when the task involves:
| Task | Why AST beats grep |
|---|---|
| Refactoring / renaming | Grep finds the string in comments and strings too; AST finds only the symbol |
| Dead code detection | Grep can't tell if an export is actually imported elsewhere |
| Dependency tracing | "What modules does X depend on?" requires understanding |
| Impact analysis | "If I change function X, what breaks?" needs call-graph traversal |
| Circular dependency detection | Requires building and analyzing a full import graph |
| Code migration | Rewriting deprecated API patterns structurally across a codebase |
| Custom linting | Enforcing project-specific patterns that standard linters don't cover |
Don't use this skill when:
- Searching for a specific string, error message, or config value → use
grep - Finding files by name or extension → use /
findfd - The codebase is < 5 files and you can read them all → just read them
当任务包含以下内容时,使用该技能:
| 任务 | AST优于grep的原因 |
|---|---|
| 重构/重命名 | Grep会在注释和字符串中也找到该字符串;而AST只会定位到符号本身 |
| 死代码检测 | Grep无法判断某个导出是否真的在其他地方被导入 |
| 依赖追踪 | “模块X依赖哪些模块?”需要理解 |
| 影响分析 | “如果我修改函数X,哪些内容会受影响?”需要调用图遍历 |
| 循环依赖检测 | 需要构建并分析完整的导入图 |
| 代码迁移 | 在整个代码库中结构化重写已废弃的API模式 |
| 自定义代码检查 | 强制执行标准检查工具未覆盖的项目特定规范 |
不适用场景:
- 搜索特定字符串、错误信息或配置值 → 使用
grep - 按名称或扩展名查找文件 → 使用/
findfd - 代码库少于5个文件且可直接通读 → 直接阅读即可
Phase 1: Search — Find Code by Structure
阶段1:搜索——按结构查找代码
ast-grep (recommended — all languages)
ast-grep(推荐——支持所有语言)
ast-grep uses pattern syntax that looks like the code you're searching for, with wildcards that match any AST node.
$METAVARBasic pattern search:
bash
undefinedast-grep使用模式语法,其写法与你要搜索的代码类似,通过通配符匹配任意AST节点。
$METAVAR基础模式搜索:
bash
undefinedFind all calls to console.log
Find all calls to console.log
ast-grep -p 'console.log($MSG)' -l js src/
ast-grep -p 'console.log($MSG)' -l js src/
Find all require() calls
Find all require() calls
ast-grep -p 'require($MOD)' -l js src/
ast-grep -p 'require($MOD)' -l js src/
Find all async functions
Find all async functions
ast-grep -p 'async function $NAME($$$PARAMS) { $$$BODY }' -l js src/
ast-grep -p 'async function $NAME($$$PARAMS) { $$$BODY }' -l js src/
Find if-else without braces
Find if-else without braces
ast-grep -p 'if ($COND) $STMT' -l js src/
**Key metavariable syntax:**
- `$NAME` — matches a single AST node (like regex `.`)
- `$$$ARGS` — matches zero or more nodes (like regex `.*`)
- `$_` — anonymous match (don't need to reference it)
**Search with rewrite preview:**
```bashast-grep -p 'if ($COND) $STMT' -l js src/
**关键元变量语法:**
- `$NAME` —— 匹配单个AST节点(类似正则表达式 `.`)
- `$$$ARGS` —— 匹配零个或多个节点(类似正则表达式 `.*`)
- `$_` —— 匿名匹配(无需引用该变量)
**带重写预览的搜索:**
```bashPreview replacing var with const
Preview replacing var with const
ast-grep -p 'var $NAME = $VALUE' -r 'const $NAME = $VALUE' -l js src/
ast-grep -p 'var $NAME = $VALUE' -r 'const $NAME = $VALUE' -l js src/
Apply interactively (prompts y/n per match)
Apply interactively (prompts y/n per match)
ast-grep -p 'var $NAME = $VALUE' -r 'const $NAME = $VALUE' -l js --interactive src/
See [ast-grep-cheatsheet.md](ast-grep-cheatsheet.md) for the full pattern reference.ast-grep -p 'var $NAME = $VALUE' -r 'const $NAME = $VALUE' -l js --interactive src/
查看 [ast-grep-cheatsheet.md](ast-grep-cheatsheet.md) 获取完整的模式参考。Fallback: Language-Specific Parsers
备选方案:语言特定解析器
When you need full AST traversal beyond pattern matching:
JavaScript/TypeScript — bundled helper:
bash
undefined当你需要超出模式匹配的完整AST遍历时:
JavaScript/TypeScript——内置工具:
bash
undefinedExport list with line numbers
Export list with line numbers
node /home/user/.gemini/antigravity/skills/ast-code-graph/scripts/parse-js.mjs <file> --symbols
node /home/user/.gemini/antigravity/skills/ast-code-graph/scripts/parse-js.mjs <file> --symbols
Full JSON AST
Full JSON AST
node /home/user/.gemini/antigravity/skills/ast-code-graph/scripts/parse-js.mjs <file>
**Python — bundled graph builder:**
```bash
python3 /home/user/.gemini/antigravity/skills/ast-code-graph/scripts/build-graph.py <directory> [flags]node /home/user/.gemini/antigravity/skills/ast-code-graph/scripts/parse-js.mjs <file>
**Python——内置图构建工具:**
```bash
python3 /home/user/.gemini/antigravity/skills/ast-code-graph/scripts/build-graph.py <directory> [flags]Phase 2: Analyze — Use Rules for Complex Queries
阶段2:分析——使用规则进行复杂查询
ast-grep supports YAML rule configurations for combining multiple conditions with logical operators.
ast-grep支持YAML规则配置,可通过逻辑运算符组合多个条件。
Inline rules (ad-hoc, no file needed)
内联规则(临时使用,无需文件)
bash
ast-grep scan --inline-rules '
id: find-unsafe-eval
language: JavaScript
rule:
pattern: eval($CODE)
' src/bash
ast-grep scan --inline-rules '
id: find-unsafe-eval
language: JavaScript
rule:
pattern: eval($CODE)
' src/Rule file (reusable)
规则文件(可复用)
Save as :
rules/no-console-log.ymlyaml
id: no-console-log
language: JavaScript
severity: warning
message: Remove console.log before committing
rule:
pattern: console.log($$$ARGS)Run:
bash
ast-grep scan --rule rules/no-console-log.yml src/保存为 :
rules/no-console-log.ymlyaml
id: no-console-log
language: JavaScript
severity: warning
message: Remove console.log before committing
rule:
pattern: console.log($$$ARGS)运行:
bash
ast-grep scan --rule rules/no-console-log.yml src/Composing rules
组合规则
Rules support , , , , , , :
allanynothasinsidefollowsprecedesyaml
id: await-in-loop
language: JavaScript
rule:
pattern: await $EXPR
inside:
any:
- kind: for_statement
- kind: for_in_statement
- kind: while_statement
stopBy: end规则支持 、、、、、、:
allanynothasinsidefollowsprecedesyaml
id: await-in-loop
language: JavaScript
rule:
pattern: await $EXPR
inside:
any:
- kind: for_statement
- kind: for_in_statement
- kind: while_statement
stopBy: endPhase 3: Index — Build the Code Graph
阶段3:索引——构建代码图
For deeper analysis (call graphs, dependency trees, dead code), build a structured graph. See graph-schema.md for the node/edge schema.
对于深度分析(调用图、依赖树、死代码),需构建结构化图。查看 graph-schema.md 了解节点/边的 schema。
Using ast-grep for graph building
使用ast-grep构建图
Combine ast-grep's output with graph construction:
--jsonbash
undefined结合ast-grep的输出与图构建:
--jsonbash
undefinedExport all function definitions as JSON
Export all function definitions as JSON
ast-grep -p 'function $NAME($$$PARAMS) { $$$BODY }' -l js --json src/
ast-grep -p 'function $NAME($$$PARAMS) { $$$BODY }' -l js --json src/
Export all import statements as JSON
Export all import statements as JSON
ast-grep -p 'import $$$SPECS from $MOD' -l js --json src/
ast-grep -p 'import $$$SPECS from $MOD' -l js --json src/
Export all require calls as JSON
Export all require calls as JSON
ast-grep -p 'const $NAME = require($MOD)' -l js --json src/
undefinedast-grep -p 'const $NAME = require($MOD)' -l js --json src/
undefinedUsing bundled scripts
使用内置脚本
Python codebases:
bash
python3 scripts/build-graph.py <dir> --callers <symbol> # find callers
python3 scripts/build-graph.py <dir> --unused # dead code
python3 scripts/build-graph.py <dir> --depends-on <mod> # reverse deps
python3 scripts/build-graph.py <dir> --cycles # circular importsPython代码库:
bash
python3 scripts/build-graph.py <dir> --callers <symbol> # find callers
python3 scripts/build-graph.py <dir> --unused # dead code
python3 scripts/build-graph.py <dir> --depends-on <mod> # reverse deps
python3 scripts/build-graph.py <dir> --cycles # circular importsPhase 4: Act — Apply Changes Safely
阶段4:执行——安全应用变更
Structural rewriting with ast-grep
使用ast-grep进行结构化重写
bash
undefinedbash
undefinedReplace deprecated API calls
Replace deprecated API calls
ast-grep -p 'oldApi($ARGS)' -r 'newApi($ARGS)' -l js --interactive src/
ast-grep -p 'oldApi($ARGS)' -r 'newApi($ARGS)' -l js --interactive src/
Convert arrow functions to regular functions
Convert arrow functions to regular functions
ast-grep -p 'const $NAME = ($$$PARAMS) => { $$$BODY }'
-r 'function $NAME($$$PARAMS) { $$$BODY }' -l js --interactive src/
-r 'function $NAME($$$PARAMS) { $$$BODY }' -l js --interactive src/
ast-grep -p 'const $NAME = ($$$PARAMS) => { $$$BODY }'
-r 'function $NAME($$$PARAMS) { $$$BODY }' -l js --interactive src/
-r 'function $NAME($$$PARAMS) { $$$BODY }' -l js --interactive src/
Add error handling wrapper
Add error handling wrapper
ast-grep -p 'fetch($URL)' -r 'safeFetch($URL)' -l js --interactive src/
undefinedast-grep -p 'fetch($URL)' -r 'safeFetch($URL)' -l js --interactive src/
undefinedSafe refactoring workflow
安全重构流程
- Search — to find all matches
ast-grep -p '<pattern>' src/ - Review — Add to inspect match details and context
--json - Preview — Add to see the replacement
-r '<rewrite>' - Apply — Add to selectively apply changes
--interactive - Verify — Re-run the search to confirm zero remaining matches
- 搜索 —— 查找所有匹配项
ast-grep -p '<pattern>' src/ - 审查 —— 添加参数查看匹配详情与上下文
--json - 预览 —— 添加查看替换效果
-r '<rewrite>' - 应用 —— 添加参数选择性应用变更
--interactive - 验证 —— 重新运行搜索确认无剩余匹配项
Quick Reference
快速参考
| I want to... | ast-grep command |
|---|---|
Find all calls to | |
| Find function definitions | |
| Find unused imports | |
Rename | |
Convert | |
| Find patterns in JSON output | |
| Run YAML lint rule | |
| Check change impact | Build graph → find all transitive callers (reverse BFS) |
| 我想要... | ast-grep命令 |
|---|---|
查找所有 | |
| 查找函数定义 | |
| 查找未使用的导入 | |
将 | |
将 | |
| 以JSON格式输出匹配模式 | |
| 运行YAML检查规则 | |
| 检查变更影响 | 构建图 → 查找所有传递调用者(反向BFS) |
Supporting Files
支持文件
- ast-grep-cheatsheet.md — Full ast-grep pattern and CLI reference
- graph-schema.md — Node and edge type definitions with ER diagram
- query-patterns.md — Detailed cookbook of query patterns with examples
- scripts/parse-js.mjs — Cross-platform Node.js script for JS/TS AST parsing (fallback)
- scripts/build-graph.py — Python code graph builder (stdlib only)
- ast-grep-cheatsheet.md —— 完整的ast-grep模式与CLI参考
- graph-schema.md —— 节点与边类型定义(含ER图)
- query-patterns.md —— 带示例的查询模式详细手册
- scripts/parse-js.mjs —— 跨平台Node.js脚本,用于JS/TS AST解析(备选方案)
- scripts/build-graph.py —— Python代码图构建工具(仅依赖标准库)