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, write new rules, working with @ast-grep/napi 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.
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.
Use this skill when users:
Follow this process to help users write effective ast-grep rules:
Clearly understand what the user wants to find. Ask clarifying questions if needed:
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;
}
Translate the pattern into an ast-grep rule. Start simple and add complexity as needed.
Key principles:
stopBy: end for relational rules (inside, has) to ensure search goes to the end of the directionpattern for simple structureskind with has/inside for complex structuresall, any, or notExample rule file (test_rule.yml):