ast-grep-search
БесплатноБез исполняемых скриптовНе проверенFind and replace code patterns structurally with ast-grep. Use when matching code by AST structure, finding functions with specific signatures, or detecting…
Об этом скилле
ast-grep Structural Code Search & Refactoring
Structural code search and refactoring using ast-grep — matches code by its AST (abstract syntax tree) rather than text patterns.
When to Use This Skill
| Use this skill when... | Use something else instead when... |
|---|---|
| The pattern depends on AST structure (function shape, call form, argument count) | Searching plain text or regex matches → tools-plugin:rg-code-search |
| Refactoring API call sites across many files while preserving captured variables | Running a one-shot anti-pattern scan with a report → code-antipatterns |
| Hand-written structural search/replace for an ad-hoc migration | Functional refactors of a known file/directory → code-refactor |
| Building a new ast-grep rule for a codebase-specific smell | Looking up agentic flags for an existing linter → code-lint |
When to Use ast-grep vs Grep/ripgrep
| Use ast-grep when... | Use grep/rg when... |
|---|---|
| Pattern depends on code structure | Simple text or regex match |
| Need to match any number of arguments | Searching logs, docs, config |
| Refactoring across many files | One-off literal string search |
| Finding anti-patterns (empty catch, etc.) | Language doesn't matter |
| Replacing while preserving variables | Quick filename/line check |
Decision rule: If your search pattern contains wildcards for "any expression," "any arguments," or "any function name," use ast-grep.
Find References With the Sharpest Instrument
Promoted from ~/.claude/rules/tool-use-patterns.md. Edit refuses on a file
unread this session, so "read it first" is already a harness invariant. The
uncovered half is checking what else depends on what you're changing, and
the reflex there is grep, which cannot tell a call from a comment, a
definition from a mention, or foo() from "foo" in a string. Measured across
282 local sessions: ~2,400 code-symbol searches went through grep/rg,
against 6 ast-grep calls and 6 LSP calls.
Ladder, sharpest first. Falling back down it is normal; starting at the bottom for a code symbol is the miss.
| Reach for | When |
|---|---|
LSP — findReferences, incomingCalls, goToDefinition |
A language server is running for that filetype. Exact: no comment/string hits, and it follows imports and re-exports that no text pattern can. |
ast-grep -p '$FN($$$ARGS)' |
No LSP, or the target is a shape rather than a name — a call with a given arity, a decorator, an un-awaited async call. Cross-language, bash included. |
rg |
Non-code: markdown rules, chezmoi templates, config keys, justfile recipes, workflow YAML. The right tool there, not a fallback — most of a dotfiles or plugins repo is prose. |
Two things that make the middle rung less automatic than it looks. A bare
identifier pattern matches the definition too (ast-grep --lang bash -p 'foo'
returns foo() { … } alongside every call), so an unshaped pattern is just
grep with extra syntax. And a language server has to be on PATH, not
merely installed — bash-language-server sitting in ~/.local/share/nvim/mason/bin
is invisible to the LSP tool, which silently drops shell to the middle rung.
Structural tools carry their own empty-result trap: an ast-grep pattern that
fails to parse returns no matches and exit 0, indistinguishable from a clean
tree. Control-test the negative against a term you know is present, in the tool
you are actually using (agent-patterns-plugin:tool-result-traps).
Pattern Syntax
| Pattern | Matches | Example |
|---|---|---|
$VAR |
Single AST node | console.log($MSG) |
$$$ARGS |
Zero or more nodes | func($$$ARGS) |
$_ |
Single node (no capture) | $_ == $_ |
$A == $A |
Same node repeated | Finds x == x (not x == y) |
Essential Commands
Search for Patterns
# 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
# Search in specific directory
ast-grep -p 'import $PKG' --lang js src/
# JSON output for parsing
ast-grep -p 'pattern' --lang js --json=compact
Search and Replace
# Preview changes (default - shows matches)
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
# Interactive review
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
# Update import paths
ast-grep -p "import $NAME from '@old/$PATH'" \
-r "import $NAME from '@new/$PATH'" --lang ts -U
Language Codes
| Code | Language | Code | Language |
|---|---|---|---|
js |
JavaScript | py |
Python |
ts |
TypeScrip |
Установить ast-grep-search в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Bash(sg *)Bash(ast-grep *)ReadGrepGlobВложенные файлы
FAQ
Что делает скилл ast-grep-search?
Find and replace code patterns structurally with ast-grep. Use when matching code by AST structure, finding functions with specific signatures, or detecting anti-patterns regex cannot match.
Как установить скилл ast-grep-search?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ast-grep-search запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic