| name | description | allowed-tools |
|---|---|---|
ast-grep-search |
Syntax-aware code searching that understands code structure rather than just text patterns. Always prefer ast-grep than grep for code searches. |
Read, Grep, Bash(ast-grep:*), Bash(sg:*) |
ast-grep allows searching code based on its Abstract Syntax Tree (AST), enabling syntax-aware pattern matching. It is ideal for finding function calls, method invocations, variable declarations, and other code structures while respecting language syntax.
Use ast-grep when:
- Searching for function/method calls with varying arguments
- Finding code patterns that respect language syntax
- Matching code structure regardless of formatting/whitespace
- Locating specific AST nodes (imports, exports, classes, function definitions)
- Need to understand semantic code structure
- Searching requires syntax awareness
Use grep/ripgrep when:
- Simple string or regex searches
- Searching in comments, strings, or documentation
- Looking for identifiers or variable names
- Quick text-based searches where syntax doesn't matter
ast-grep cannot:
- Perform type-aware searches (doesn't understand type inference)
- Search across files for relationships (e.g., "find all callers")
- Handle ambiguous partial syntax
- Search inside macro expansions (searches source only)
- Understand semantic equivalence (different code, same meaning)
ast-grep --lang <language> -p '<pattern>' [paths...]ast-grep uses meta-variables prefixed with $ to create structural patterns:
-
$IDENTIFIER- Matches a single AST node (expression, identifier, statement, type)- Examples:
$VAR,$EXPR,$ARG,$METHOD,$TYPE
- Examples:
-
$$$MULTI- Matches zero or more consecutive nodes (ellipsis pattern)- Examples:
$$$ARGS,$$$BODY,$$$FIELDS,$$$PARAMS
- Examples:
- Use concrete syntax for known parts (keywords, operators, punctuation)
- Use meta-variables only where variation is expected
- Preserve language syntax (brackets, semicolons, commas)
- Start specific then generalize if too few results
- Respect AST boundaries - patterns must be valid AST nodes
Find any function call:
ast-grep -l rust -p 'function_name($$$ARGS)'Find method calls on any object:
ast-grep -l typescript -p '$OBJ.method_name($$$ARGS)'Find variable declarations:
ast-grep -l rust -p 'let $VAR = $EXPR'Find struct instantiation with any fields:
ast-grep -l rust -p '$TYPE { $$$FIELDS }'Show surrounding code:
# 3 lines after matches
ast-grep -l rust -p '$PATTERN' -A 3
# 3 lines before matches
ast-grep -l rust -p '$PATTERN' -B 3
# 3 lines before and after
ast-grep -l rust -p '$PATTERN' -C 3Three JSON output formats available:
# Pretty-printed JSON
ast-grep -l rust -p '$PATTERN' --json=pretty
# Streaming JSON (one object per line)
ast-grep -l rust -p '$PATTERN' --json=stream
# Compact JSON (single line)
ast-grep -l rust -p '$PATTERN' --json=compactParse the user's description: $ARGUMENTS
Determine:
- What pattern? - What code structure are we searching for?
- Which language? - Rust (crates/) or TypeScript (packages/)?
- Which scope? - Specific directory, whole crates/, or whole packages/?
- What context needed? - Should we show surrounding code?
Build a pattern following these principles:
- Identify concrete parts - Function names, keywords, operators
- Identify variable parts - Use
$VARfor single nodes - Identify sequences - Use
$$$VARSfor argument lists, statement blocks - Preserve syntax - Keep brackets, braces, semicolons exact
- Test mentally - Would this pattern match the target code?
Pattern development tips:
- Start with actual code example, then generalize
- Use
--debug-query=patternto see how ast-grep parses it - Test on known examples first
- Add more concrete syntax if results too broad
- Generalize if results too narrow
Choose appropriate command:
# Basic search
!`ast-grep --lang <language> -p '<pattern>' <path>`
# With context lines
!`ast-grep --lang <language> -p '<pattern>' -C 2 <path>`
# JSON output for processing
!`ast-grep --lang <language> -p '<pattern>' --json=stream <path>`- Count matches - How many files and total matches?
- Show representative examples - Don't overwhelm with all results
- Identify patterns - Common themes in matches?
- Suggest next steps - Refine search, explore specific files, or related searches
If results are:
- Too broad - Add more concrete syntax, narrow the scope
- Too narrow - Use more meta-variables, broaden the pattern
- Wrong matches - Check pattern syntax, use --debug-query
- No matches - Verify language, check pattern validity, test simpler pattern
Query: "Find all places where errors are converted using .context()"
!`ast-grep -l rust -p '$EXPR.context($MSG)' crates/`Query: "Show implementations of the transform hook in plugins"
!`ast-grep -l rust -p 'fn transform(&self, $$$PARAMS) -> $RET { $$$BODY }' crates/rolldown_plugin*/`Query: "Find TypeScript type assertions"
!`ast-grep -l typescript -p '$EXPR as $TYPE' packages/`Query: "Find all #[napi] annotated functions"
!`ast-grep -l rust -p '#[napi] fn $NAME($$$PARAMS) $$$REST' crates/rolldown_binding/`Query: "Find all files importing from rolldown core"
!`ast-grep -l typescript -p 'import { $$$IMPORTS } from "rolldown"' packages/`Query: "Find unhandled promises (await without try-catch)"
!`ast-grep -l typescript -p 'await $EXPR' packages/ -A 0 -B 5`Then manually inspect for missing error handling.
Query: "Find all .clone() calls that might be expensive"
!`ast-grep -l rust -p '$EXPR.clone()' crates/rolldown/src/`Query: "Find all functions taking mutable self"
!`ast-grep -l rust -p 'fn $NAME(&mut self, $$$PARAMS) $$$REST' crates/`ast-grep supports 40+ languages:
Compiled languages: C, C++, C#, Go, Java, Kotlin, Rust, Swift, Dart Scripting languages: Python, Ruby, PHP, Lua, Elixir Web languages: JavaScript, TypeScript, HTML, CSS Other: Bash, YAML, JSON, Thrift, Protobuf, and more
- Start simple - Begin with basic patterns, add complexity as needed
- Test iteratively - Run on small scope first, expand when confident
- Use concrete syntax - More concrete = more precise results
- Leverage ellipsis -
$$$ARGSis powerful for variable-length sequences - Read the AST - Use --debug-query to understand structure
- Combine with grep - Use grep for preliminary filtering, ast-grep for precision
- Save useful patterns - Document patterns that work well for reuse
- Use configuration - For repeated searches, create sgconfig.yml rules
After executing searches, provide:
- Summary - "Found X matches in Y files"
- Sample Results - Show relevant file paths and code snippets
- Analysis - Identify patterns, commonalities, or insights
- Recommendations - Suggest next steps, refinements, or related searches
- Full LLM Documentation: https://ast-grep.github.io/llms-full.txt
- Interactive Playground: https://ast-grep.github.io/playground.html
- Pattern Syntax Guide: https://ast-grep.github.io/guide/pattern-syntax.html
- Rule Configuration: https://ast-grep.github.io/guide/rule-config.html
- Cookbook Examples: https://ast-grep.github.io/catalog/
- GitHub Repository: https://github.com/ast-grep/ast-grep