Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree patterns, find specific code structures, or perform complex code queries that go beyond simple text search.
This skill helps translate natural language queries into ast-grep rules for structural code search. ast-grep (sg) is a high-performance, polyglot tool (C, C++, Go, HTML, Java, Python, Rust, TS/JS, YAML) that uses Abstract Syntax Tree (AST) patterns to match code based on its structure rather than just text.
Use this skill when users:
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):