Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 61 additions & 18 deletions .claude/skills/ast-grep/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,46 @@ description: Guide for writing ast-grep rules to perform structural 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.
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

- 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
- 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:
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.
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:
**Example:** If searching for "async functions that use await", create a test
file:

```javascript
// test_example.js
Expand All @@ -47,15 +58,19 @@ async function example() {

### Step 3: Write the ast-grep Rule

Translate the pattern into an ast-grep rule. Start simple and add complexity as needed.
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

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

```yaml
id: async-with-await
language: javascript
Expand All @@ -70,9 +85,11 @@ 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:
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)**

```bash
echo "async function test() { await fetch(); }" | ast-grep scan --inline-rules "id: test
language: javascript
Expand All @@ -84,11 +101,13 @@ rule:
```

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

```bash
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)
Expand All @@ -99,16 +118,19 @@ ast-grep scan --rule test_rule.yml test_example.js
Once the rule matches the example code correctly, search the actual codebase:

**For simple pattern searches:**

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

**For complex rule-based searches:**

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

**For inline rules (without creating files):**

```bash
ast-grep scan --inline-rules "id: my-rule
language: javascript
Expand All @@ -129,16 +151,19 @@ ast-grep run --pattern 'async function example() { await fetch(); }' \
```

**Available formats:**

- `cst`: Concrete Syntax Tree (shows all nodes including punctuation)
- `ast`: Abstract Syntax Tree (shows only named nodes)
- `pattern`: Shows how ast-grep interprets your pattern

**Use this to:**

- Find the correct `kind` values for nodes
- Understand the structure of code you want to match
- Debug why patterns aren't matching

**Example:**

```bash
# See the structure of your target code
ast-grep run --pattern 'class User { constructor() {} }' \
Expand All @@ -163,6 +188,7 @@ rule:
```

**Add --json for structured output:**

```bash
echo "const x = await fetch();" | ast-grep scan --inline-rules "..." --stdin --json
```
Expand All @@ -183,6 +209,7 @@ ast-grep run --pattern 'function $NAME($$$)' --lang javascript --json .
```

**When to use:**

- Simple, single-node matches
- Quick searches without complex logic
- When you don't need relational rules (inside/has)
Expand All @@ -209,30 +236,35 @@ ast-grep scan --rule my_rule.yml --json /path/to/project
```

**When to use:**

- Complex structural searches
- Relational rules (inside, has, precedes, follows)
- Composite logic (all, any, not)
- When you need the power of full YAML rules

**Tip:** For relational rules (inside/has), always add `stopBy: end` to ensure complete traversal.
**Tip:** For relational rules (inside/has), always add `stopBy: end` to ensure
complete traversal.

## Tips for Writing Effective Rules

### Always Use stopBy: end

For relational rules, always use `stopBy: end` unless there's a specific reason not to:
For relational rules, always use `stopBy: end` unless there's a specific reason
not to:

```yaml
has:
pattern: await $EXPR
stopBy: end
```

This ensures the search traverses the entire subtree rather than stopping at the first non-matching node.
This ensures the search traverses the entire subtree rather than stopping at the
first non-matching node.

### Start Simple, Then Add Complexity

Begin with the simplest rule that could work:

1. Try a `pattern` first
2. If that doesn't work, try `kind` to match the node type
3. Add relational rules (`has`, `inside`) as needed
Expand All @@ -241,12 +273,15 @@ Begin with the simplest rule that could work:
### Use the Right Rule Type

- **Pattern**: For simple, direct code matching (e.g., `console.log($ARG)`)
- **Kind + Relational**: For complex structures (e.g., "function containing await")
- **Composite**: For logical combinations (e.g., "function with await but not in try-catch")
- **Kind + Relational**: For complex structures (e.g., "function containing
await")
- **Composite**: For logical combinations (e.g., "function with await but not in
try-catch")

### Debug with AST Inspection

When rules don't match:

1. Use `--debug-query=cst` to see the actual AST structure
2. Check if metavariables are being detected correctly
3. Verify the node `kind` matches what you expect
Expand All @@ -255,10 +290,12 @@ When rules don't match:
### Escaping in Inline Rules

When using `--inline-rules`, escape metavariables in shell commands:

- Use `\$VAR` instead of `$VAR` (shell interprets `$` as variable)
- Or use single quotes: `'$VAR'` works in most shells

**Example:**

```bash
# Correct: escaped $
ast-grep scan --inline-rules "rule: {pattern: 'console.log(\$ARG)'}" .
Expand All @@ -272,6 +309,7 @@ ast-grep scan --inline-rules 'rule: {pattern: "console.log($ARG)"}' .
### Find Functions with Specific Content

Find async functions that use await:

```bash
ast-grep scan --inline-rules "id: async-await
language: javascript
Expand All @@ -286,6 +324,7 @@ rule:
### Find Code Inside Specific Contexts

Find console.log inside class methods:

```bash
ast-grep scan --inline-rules "id: console-in-class
language: javascript
Expand All @@ -299,6 +338,7 @@ rule:
### Find Code Missing Expected Patterns

Find async functions without try-catch:

```bash
ast-grep scan --inline-rules "id: async-no-trycatch
language: javascript
Expand All @@ -317,7 +357,10 @@ rule:
## Resources

### references/

Contains detailed documentation for ast-grep rule syntax:
- `rule_reference.md`: Comprehensive ast-grep rule documentation covering atomic rules, relational rules, composite rules, and metavariables

- `rule_reference.md`: Comprehensive ast-grep rule documentation covering atomic
rules, relational rules, composite rules, and metavariables

Load these references when detailed rule syntax information is needed.
Loading