ast-grep

laulauland 的头像作者 laulauland

使用ast-grep进行基于AST的代码搜索。在按语法结构而非文本模式搜索代码、查找特定代码模式或重构时使用。

📖 中文导读:使用ast-grep进行基于AST的代码搜索。在按语法结构而非文本模式搜索代码、查找特定代码模式或重构时使用。 以下正文为该技能的原始 SKILL.md 内容(英文),上方安装命令可直接使用。

ast-grep

Use ast-grep to search code by syntax (AST), not text. Write patterns as valid code; use $VARS to match a single node and $$$VARS to match zero-or-more nodes.

Basic Usage

# Set language with --lang (or let it infer)
ast-grep -p 'PATTERN' --lang LANG PATH

# Output JSON with --json for programmatic use
ast-grep -p 'PATTERN' --json compact .

# Add -A/-B/-C for context
ast-grep -p 'PATTERN' -C 2 .

Pattern Syntax

Pattern Matches
$VAR Single AST node
$$$VARS Zero or more nodes
Literal code Exact structure

Examples

Find Function Calls

# Any function call in TypeScript
ast-grep -p '$F($$$ARGS)' --lang ts .

# Console logs with any arguments
ast-grep -p 'console.log($$$)' --lang js src/

Find Patterns

# Re-used operand (same subexpression twice)
ast-grep -p '$A == $A' .

# If statements
ast-grep -p 'if ($COND) { $$$ }' --lang js .

Imports

# Find imports
ast-grep -p 'import $S from $M' --lang ts .

# Narrow by node kind (extract subpart)
ast-grep -p 'import $S from $M' --selector import_clause --lang ts .

Machine-Readable Output

ast-grep -p '$CALLEE($$$ARGS)' --lang ts --json compact .

Common Use Cases

  • Finding deprecated API usage
  • Locating specific patterns for refactoring
  • Auditing code for security issues
  • Finding duplicate logic patterns
  • Searching for React hooks usage
  • Finding async/await patterns