ast-code-graph

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AST & Code Graph Indexing

AST & Code Graph Indexing

Overview

概述

Text-based search (
grep
,
ripgrep
) 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.
Primary tool: ast-grep (
sg
/
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.
Core principle: When the question is about code structure, use AST analysis. When the question is about text content, use grep.
基于文本的搜索(
grep
ripgrep
)查找字符串匹配项。基于AST的分析则能理解代码结构——它可以区分函数定义、函数调用、注释和字符串字面量之间的差异。
核心工具: ast-grep
sg
/
ast-grep
)——一款基于Rust开发的快速CLI工具,用于结构化代码搜索、代码检查与重写。它使用tree-sitter进行解析,开箱即支持20+种编程语言。
核心原则: 当需求涉及代码结构时,使用AST分析;当需求涉及文本内容时,使用grep。

When to Use

适用场景

Use this skill when the task involves:
TaskWhy AST beats grep
Refactoring / renamingGrep finds the string in comments and strings too; AST finds only the symbol
Dead code detectionGrep can't tell if an export is actually imported elsewhere
Dependency tracing"What modules does X depend on?" requires understanding
import
/
require
Impact analysis"If I change function X, what breaks?" needs call-graph traversal
Circular dependency detectionRequires building and analyzing a full import graph
Code migrationRewriting deprecated API patterns structurally across a codebase
Custom lintingEnforcing 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
    find
    /
    fd
  • The codebase is < 5 files and you can read them all → just read them
当任务包含以下内容时,使用该技能:
任务AST优于grep的原因
重构/重命名Grep会在注释和字符串中也找到该字符串;而AST只会定位到符号本身
死代码检测Grep无法判断某个导出是否真的在其他地方被导入
依赖追踪“模块X依赖哪些模块?”需要理解
import
/
require
语句
影响分析“如果我修改函数X,哪些内容会受影响?”需要调用图遍历
循环依赖检测需要构建并分析完整的导入图
代码迁移在整个代码库中结构化重写已废弃的API模式
自定义代码检查强制执行标准检查工具未覆盖的项目特定规范
不适用场景:
  • 搜索特定字符串、错误信息或配置值 → 使用
    grep
  • 按名称或扩展名查找文件 → 使用
    find
    /
    fd
  • 代码库少于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
$METAVAR
wildcards that match any AST node.
Basic pattern search:
bash
undefined
ast-grep使用模式语法,其写法与你要搜索的代码类似,通过
$METAVAR
通配符匹配任意AST节点。
基础模式搜索:
bash
undefined

Find 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:**

```bash
ast-grep -p 'if ($COND) $STMT' -l js src/

**关键元变量语法:**

- `$NAME` —— 匹配单个AST节点(类似正则表达式 `.`)
- `$$$ARGS` —— 匹配零个或多个节点(类似正则表达式 `.*`)
- `$_` —— 匿名匹配(无需引用该变量)

**带重写预览的搜索:**

```bash

Preview 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
undefined

Export 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.yml
:
yaml
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.yml
yaml
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
all
,
any
,
not
,
has
,
inside
,
follows
,
precedes
:
yaml
id: await-in-loop
language: JavaScript
rule:
  pattern: await $EXPR
  inside:
    any:
      - kind: for_statement
      - kind: for_in_statement
      - kind: while_statement
    stopBy: end
规则支持
all
any
not
has
inside
follows
precedes
yaml
id: await-in-loop
language: JavaScript
rule:
  pattern: await $EXPR
  inside:
    any:
      - kind: for_statement
      - kind: for_in_statement
      - kind: while_statement
    stopBy: end

Phase 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
--json
output with graph construction:
bash
undefined
结合ast-grep的
--json
输出与图构建:
bash
undefined

Export 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/
undefined
ast-grep -p 'const $NAME = require($MOD)' -l js --json src/
undefined

Using 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 imports
Python代码库:
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 imports

Phase 4: Act — Apply Changes Safely

阶段4:执行——安全应用变更

Structural rewriting with ast-grep

使用ast-grep进行结构化重写

bash
undefined
bash
undefined

Replace 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/
ast-grep -p 'const $NAME = ($$$PARAMS) => { $$$BODY }'
-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/
undefined
ast-grep -p 'fetch($URL)' -r 'safeFetch($URL)' -l js --interactive src/
undefined

Safe refactoring workflow

安全重构流程

  1. Search
    ast-grep -p '<pattern>' src/
    to find all matches
  2. Review — Add
    --json
    to inspect match details and context
  3. Preview — Add
    -r '<rewrite>'
    to see the replacement
  4. Apply — Add
    --interactive
    to selectively apply changes
  5. Verify — Re-run the search to confirm zero remaining matches
  1. 搜索 ——
    ast-grep -p '<pattern>' src/
    查找所有匹配项
  2. 审查 —— 添加
    --json
    参数查看匹配详情与上下文
  3. 预览 —— 添加
    -r '<rewrite>'
    查看替换效果
  4. 应用 —— 添加
    --interactive
    参数选择性应用变更
  5. 验证 —— 重新运行搜索确认无剩余匹配项

Quick Reference

快速参考

I want to...ast-grep command
Find all calls to
foo()
ast-grep -p 'foo($$$ARGS)' src/
Find function definitions
ast-grep -p 'function $NAME($$$P) { $$$B }' src/
Find unused imports
ast-grep scan --inline-rules '...' src/
Rename
oldFn
newFn
ast-grep -p 'oldFn($$$A)' -r 'newFn($$$A)' --interactive src/
Convert
var
const
ast-grep -p 'var $N = $V' -r 'const $N = $V' --interactive src/
Find patterns in JSON output
ast-grep -p '<pattern>' --json src/
Run YAML lint rule
ast-grep scan --rule rule.yml src/
Check change impactBuild graph → find all transitive callers (reverse BFS)
我想要...ast-grep命令
查找所有
foo()
调用
ast-grep -p 'foo($$$ARGS)' src/
查找函数定义
ast-grep -p 'function $NAME($$$P) { $$$B }' src/
查找未使用的导入
ast-grep scan --inline-rules '...' src/
oldFn
重命名为
newFn
ast-grep -p 'oldFn($$$A)' -r 'newFn($$$A)' --interactive src/
var
转换为
const
ast-grep -p 'var $N = $V' -r 'const $N = $V' --interactive src/
以JSON格式输出匹配模式
ast-grep -p '<pattern>' --json src/
运行YAML检查规则
ast-grep scan --rule rule.yml src/
检查变更影响构建图 → 查找所有传递调用者(反向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代码图构建工具(仅依赖标准库)