home / skills / 0xdarkmatter / claude-mods / structural-search

structural-search skill

/skills/structural-search

This skill searches code by AST structure using ast-grep to find semantic patterns and support large-scale refactoring.

npx playbooks add skill 0xdarkmatter/claude-mods --skill structural-search

Review the files below or copy the command above to add this skill to your agents.

Files (8)
SKILL.md
3.0 KB
---
name: structural-search
description: "Search code by AST structure using ast-grep. Find semantic patterns like function calls, imports, class definitions instead of text patterns. Triggers on: find all calls to X, search for pattern, refactor usages, find where function is used, structural search, ast-grep, sg."
compatibility: "Requires ast-grep (sg) CLI tool. Install: brew install ast-grep (macOS) or cargo install ast-grep (cross-platform)."
allowed-tools: "Bash"
---

# Structural Search

Search code by its abstract syntax tree (AST) structure. Finds semantic patterns that regex cannot match reliably.

## Tools

| Tool | Command | Use For |
|------|---------|---------|
| ast-grep | `sg -p 'pattern'` | AST-aware code search |

## Pattern Syntax

| Pattern | Matches | Example |
|---------|---------|---------|
| `$NAME` | Named identifier | `function $NAME() {}` |
| `$_` | Any single node | `console.log($_)` |
| `$$$` | Zero or more nodes | `function $_($$$) {}` |

## Top 10 Essential Patterns

```bash
# 1. Find console.log calls
sg -p 'console.log($_)'

# 2. Find React hooks
sg -p 'const [$_, $_] = useState($_)'
sg -p 'useEffect($_, [$$$])'

# 3. Find function definitions
sg -p 'function $NAME($$$) { $$$ }'
sg -p 'def $NAME($$$): $$$' --lang python

# 4. Find imports
sg -p 'import $_ from "$_"'
sg -p 'from $_ import $_' --lang python

# 5. Find async patterns
sg -p 'await $_'
sg -p 'async function $NAME($$$) { $$$ }'

# 6. Find error handling
sg -p 'try { $$$ } catch ($_) { $$$ }'
sg -p 'if err != nil { $$$ }' --lang go

# 7. Find potential issues
sg -p '$_ == $_'           # == instead of ===
sg -p 'eval($_)'           # Security risk
sg -p '$_.innerHTML = $_'  # XSS vector

# 8. Preview refactoring
sg -p 'console.log($_)' -r 'logger.info($_)'

# 9. Apply refactoring
sg -p 'var $NAME = $_' -r 'const $NAME = $_' --rewrite

# 10. Search specific language
sg -p 'pattern' --lang typescript
```

## Quick Reference

| Task | Command |
|------|---------|
| Find pattern | `sg -p 'pattern'` |
| Specific language | `sg -p 'pattern' --lang python` |
| Replace (preview) | `sg -p 'old' -r 'new'` |
| Replace (apply) | `sg -p 'old' -r 'new' --rewrite` |
| Show context | `sg -p 'pattern' -A 3` |
| JSON output | `sg -p 'pattern' --json` |
| File list only | `sg -p 'pattern' -l` |
| Count matches | `sg -p 'pattern' --count` |
| Run YAML rules | `sg scan` |

## When to Use

- Finding all usages of a function/method
- Locating specific code patterns (hooks, API calls)
- Preparing for large-scale refactoring
- When regex would match false positives
- Detecting anti-patterns and security issues
- Creating custom linting rules

## Additional Resources

For complete patterns, load:
- `./references/js-ts-patterns.md` - JavaScript/TypeScript patterns
- `./references/python-patterns.md` - Python patterns
- `./references/go-rust-patterns.md` - Go and Rust patterns
- `./references/security-patterns.md` - Security vulnerability detection
- `./references/advanced-usage.md` - YAML rules and tool integration
- `./assets/rule-template.yaml` - Starter template for custom rules

Overview

This skill performs structural code search using ast-grep (sg) so you can find semantic AST patterns instead of brittle text matches. It locates constructs like function calls, imports, class definitions, hooks, and error-handling patterns across languages and supports previewed or applied refactors. Use it to power precise code discovery, large-scale refactors, and security or anti-pattern detection.

How this skill works

You express target patterns using ast-grep's pattern syntax (named identifiers like $NAME, wildcards like $_, and repetition $$$). The sg CLI parses files into ASTs and matches those patterns across a repository, returning contextual results, file lists, counts, or JSON output. It also supports previewed replacements (-r) and applying rewrites (--rewrite), plus language-specific scanning and YAML rule execution.

When to use it

  • Find every usage of a function, method, or import across a codebase.
  • Locate language-specific constructs (hooks, async/await, try/catch) that regex would miss or mis-match.
  • Prepare and preview consistent refactors before applying changes repository-wide.
  • Detect anti-patterns, security risks (eval, innerHTML), or language-specific issues.
  • Create or validate custom linting and code-quality rules with YAML rule scans.

Best practices

  • Start with preview mode (-r without --rewrite) to inspect replacements before applying them.
  • Use named captures ($NAME) and $_ to create precise yet flexible patterns.
  • Limit scope with --lang or path filters when scanning large repos to reduce noise.
  • Combine -A for context or --json for machine-readable results to integrate with scripts.
  • Test patterns on representative files before running a wide --rewrite operation.

Example use cases

  • Find all console.log calls: sg -p 'console.log($_)' and preview replacing with logger.info($_).
  • Locate React hook usage: sg -p 'const [$_, $_] = useState($_)' or sg -p 'useEffect($_, [$$$])'.
  • Refactor var to const across JS: sg -p 'var $NAME = $_' -r 'const $NAME = $_' --rewrite.
  • Detect insecure patterns: sg -p 'eval($_)' or sg -p '$_.innerHTML = $_' to audit security hotspots.
  • Search across languages: sg -p 'def $NAME($$$): $$$' --lang python or sg -p 'pattern' --lang typescript.

FAQ

Can I preview changes before applying a rewrite?

Yes. Use -r to preview replacements and add --rewrite only when you want to apply edits.

How do I narrow searches to one language?

Add --lang <language> to the sg command to target a specific parser and reduce false matches.