Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

ast-grep

БесплатноБез исполняемых скриптовНе проверен

Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST)…

ampcodeот ampcode★ 76 звёзд на GitHub18 установок в других каталогах

Об этом скилле

ast-grep Code Search

Overview

This skill helps translate natural language queries into ast-grep rules for structural code search. ast-grep uses Abstract Syntax Tree (AST) patterns to match code based on its structure rather than just text, enabling powerful and precise code search across large codebases.

When to Use This Skill

Use this skill when users:

  • Need to search for code patterns using structural matching (e.g., "find all async functions that don't have error handling")
  • Want to locate specific language constructs (e.g., "find all function calls with specific parameters")
  • Request searches that require understanding code structure rather than just text
  • Ask to search for code with particular AST characteristics
  • Need to perform complex code queries that traditional text search cannot handle

General Workflow

Follow this process to help users write effective ast-grep rules:

Step 1: Understand the Query

Clearly understand what the user wants to find. Ask clarifying questions if needed:

  • What specific code pattern or structure are they looking for?
  • Which programming language?
  • Are there specific edge cases or variations to consider?
  • What should be included or excluded from matches?

Step 2: Create Example Code

Write a simple code snippet that represents what the user wants to match. Save this to a temporary file for testing.

Example: If searching for "async functions that use await", create a test file:

// test_example.js
async function example() {
	const result = await fetchData()
	return result
}

Step 3: Write the ast-grep Rule

Translate the pattern into an ast-grep rule. Start simple and add complexity as needed.

Key principles:

  • Always use stopBy: end for relational rules (inside, has) to ensure search goes to the end of the direction
  • Use pattern for simple structures
  • Use kind with has/inside for complex structures
  • Break complex queries into smaller sub-rules using all, any, or not

Example rule file (test_rule.yml):

id: async-with-await
language: javascript
rule:
  kind: function_declaration
  has:
    pattern: await $EXPR
    stopBy: end

See references/rule_reference.md for comprehensive rule documentation.

Step 4: Test the Rule

Use ast-grep CLI to verify the rule matches the example code. There are two main approaches:

Option A: Test with inline rules (for quick iterations)

echo "async function test() { await fetch(); }" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
  kind: function_declaration
  has:
    pattern: await \$EXPR
    stopBy: end" --stdin

Option B: Test with rule files (recommended for complex rules)

ast-grep scan --rule test_rule.yml test_example.js

Debugging if no matches:

  1. Simplify the rule (remove sub-rules)
  2. Add stopBy: end to relational rules if not present
  3. Use --debug-query to understand the AST structure (see below)
  4. Check if kind values are correct for the language

Step 5: Search the Codebase

Once the rule matches the example code correctly, search the actual codebase:

For simple pattern searches:

ast-grep run --pattern 'console.log($ARG)' --lang javascript /path/to/project

For complex rule-based searches:

ast-grep scan --rule my_rule.yml /path/to/project

For inline rules (without creating files):

ast-grep scan --inline-rules "id: my-rule
language: javascript
rule:
  pattern: \$PATTERN" /path/to/project

Rewriting Code with ast-grep

ast-grep is a powerful AST-based tool that can search for code patterns and transform them into new code. It works like a syntax-aware sed/grep that understands code structure rather than just text.

Method 1: Command Line with --rewrite

The simplest approach is using the --rewrite (or -r) flag directly in your terminal:

ast-grep run --pattern 'foo' --rewrite 'bar' --lang python

This finds all occurrences of foo and replaces them with bar. A practical example:

# Convert old-style property checks to optional chaining
ast-grep -p '$PROP && $PROP()' --rewrite '$PROP?.()' --interactive -l ts ./src

Key flags:

  • --interactive or -i: Review each change before applying
  • --update-all or -U: Apply all changes without confirmation

Method 2: YAML Rules with fix

For more complex transformations, use YAML rule files with the fix field:

id: change_def
language: Python
rule:
  pattern: |
    def foo($X):
      $$$S
fix: |-
  def baz($X):
    $$$S

Run with: ast-grep scan -r rule.yml ./src

Meta-Variables

Meta-variables are the key to powerful rewrites. They act like capture groups in regex:

Meta-variable Matches
$NAME Any single AST node (expression, identifier, etc.)
`$$$ITE
Полный SKILL.md на GitHub

Установить ast-grep в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/rule_reference.md

FAQ

Что делает скилл ast-grep?

Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or perform complex code queries that go beyond simple text search. This skill should be used when users ask to search for code patterns, find specific language constructs, or locate code with particular structural characteristics.

Как установить скилл ast-grep?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл ast-grep запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить ast-grep с