ast-grep
ast-grep Community Best Practices
Comprehensive best practices guide for ast-grep rule writing and usage, maintained by the ast-grep community. Contains 46 rules across 8 categories, prioritized by impact to guide automated rule generation and code transformation.
When to Apply
Reference these guidelines when:
- Writing new ast-grep rules for linting or search
- Debugging patterns that don't match expected code
- Optimizing rule performance for large codebases
- Setting up ast-grep projects with proper organization
- Reviewing ast-grep rules for correctness and maintainability
General Workflow
Follow this workflow when creating ast-grep rules for code search:
Step 1: Understand the Query
Clarify what you want to find:
- Target programming language
- Edge cases to handle
- What to include vs exclude
Step 2: Create Example Code
Write a sample code snippet representing the desired match pattern.
Step 3: Write the ast-grep Rule
Choose the right approach:
- Use
patternfor simple structures - Use
kindwithhas/insidefor complex structures - Combine with
all,any, ornotfor compound queries - Always use
stopBy: endfor relational rules (inside,has) to ensure complete search
Step 4: Test the Rule
# Inspect AST structure
ast-grep run --pattern '[code]' --lang [language] --debug-query=ast
# Test inline rule
echo "[code]" | ast-grep scan --inline-rules "[rule]" --stdin
# Test from file
ast-grep scan --rule [file.yml] [path]
Step 5: Search the Codebase
Deploy the validated rule:
# Search with pattern (simple matches)
ast-grep run --pattern '[pattern]' --lang [language] [path]
# Search with rule file (complex queries)
ast-grep scan --rule [file.yml] [path]
# Apply fixes interactively
ast-grep scan --rule [file.yml] --interactive [path]
Quick Tips
- Always use
stopBy: end- Ensures complete subtree traversal for relational rules - Start simple, add complexity - Begin with patterns, progress to kinds, then relational rules
- Debug with AST inspection - Use
--debug-query=astto verify structure matching - Escape in inline rules - Use
\$VARor single quotes for shell commands - Test in playground first - Use https://ast-grep.github.io/playground.html for rapid iteration
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Pattern Correctness | CRITICAL | pattern- |
| 2 | Meta Variable Usage | CRITICAL | meta- |
| 3 | Rule Composition | HIGH | compose- |
| 4 | Constraint Design | HIGH | const- |
| 5 | Rewrite Correctness | MEDIUM-HIGH | rewrite- |
| 6 | Project Organization | MEDIUM | org- |
| 7 | Performance Optimization | MEDIUM | perf- |
| 8 | Testing & Debugging | LOW-MEDIUM | test- |
Quick Reference
1. Pattern Correctness (CRITICAL)
pattern-valid-syntax- Use valid parseable code as patternspattern-language-aware- Account for language-specific syntax differencespattern-context-selector- Use context and selector for code fragmentspattern-avoid-comments-strings- Avoid matching inside comments and stringspattern-strictness-levels- Configure pattern strictness appropriatelypattern-kind-vs-pattern- Choose kind or pattern based on specificity needspattern-debug-ast- Use debug query to inspect AST structurepattern-nthchild-matching- Use nthChild for index-based positional matchingpattern-range-matching- Use range for character position matching
2. Meta Variable Usage (CRITICAL)
meta-naming-convention- Follow meta variable naming conventionsmeta-single-node- Match single AST nodes with meta variablesmeta-reuse-binding- Reuse meta variables to enforce equalitymeta-underscore-noncapture- Use underscore prefix for non-capturing matchesmeta-named-vs-unnamed- Use double dollar for unnamed node matchingmeta-multi-match-lazy- Understand multi-match variables are lazy
3. Rule Composition (HIGH)
compose-all-for-and-logic- Use all for AND logic between rulescompose-any-for-or-logic- Use any for OR logic between rulescompose-not-for-exclusion- Use not for exclusion patternscompose-inside-for-context- Use inside for contextual matchingcompose-has-for-children- Use has for child node requirementscompose-matches-for-reuse- Use matches for rule reusabilitycompose-precedes-follows- Use precedes and follows for sequential positioningcompose-field-targeting- Use field to target specific sub-nodes
4. Constraint Design (HIGH)
const-kind-filter- Use kind constraints to filter meta variablesconst-regex-filter- Use regex constraints for text patternsconst-not-inside-not- Avoid constraints inside not rulesconst-pattern-constraint- Use pattern constraints for structural filteringconst-post-match-timing- Understand constraints apply after matching
5. Rewrite Correctness (MEDIUM-HIGH)
rewrite-preserve-semantics- Preserve program semantics in rewritesrewrite-meta-variable-reference- Reference all necessary meta variables in fixrewrite-transform-operations- Use transform for complex rewritesrewrite-test-before-deploy- Test rewrites on representative coderewrite-syntax-validity- Ensure fix templates produce valid syntax
6. Project Organization (MEDIUM)
org-project-structure- Use standard project directory structureorg-unique-rule-ids- Use unique descriptive rule IDsorg-severity-levels- Assign appropriate severity levelsorg-file-filtering- Use file filtering for targeted rulesorg-message-clarity- Write clear actionable messages
7. Performance Optimization (MEDIUM)
perf-specific-patterns- Use specific patterns over generic onesperf-stopby-boundaries- Use stopBy to limit search depthperf-thread-parallelism- Leverage parallel scanning with threadsperf-avoid-regex-heavy- Avoid heavy regex in hot paths
8. Testing & Debugging (LOW-MEDIUM)
test-valid-invalid-cases- Write both valid and invalid test casestest-snapshot-updates- Use snapshot testing for fix verificationtest-playground-first- Test patterns in playground firsttest-edge-cases- Test edge cases and boundary conditions
How to Use
Read individual reference files for detailed explanations and code examples:
- Section definitions - Category structure and impact levels
- Rule template - Template for adding new rules
Full Compiled Document
- AGENTS.md - Complete compiled guide with all rules
Reference Files
| File | Description |
|---|---|
| AGENTS.md | Complete compiled guide with all rules |
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |
More from pproenca/dot-skills
zod
Zod schema validation best practices for type safety, parsing, and error handling. This skill should be used when defining z.object schemas, using z.string validations, safeParse, or z.infer. This skill does NOT cover React Hook Form integration patterns (use react-hook-form skill) or OpenAPI client generation (use orval skill).
2.1Kclean-architecture
Clean Architecture principles and best practices from Robert C. Martin's book. This skill should be used when designing software systems, reviewing code structure, or refactoring applications to achieve better separation of concerns. Triggers on tasks involving layers, boundaries, dependency direction, entities, use cases, or system architecture.
1.4Kemilkowal-animations
Emil Kowalski's animation best practices for web interfaces. Use when writing, reviewing, or implementing animations in React, CSS, or Framer Motion. Triggers on tasks involving transitions, easing, gestures, toasts, drawers, or motion.
927vitest
Vitest testing framework patterns for test setup, async testing, mocking with vi.*, snapshots, and test performance (formerly test-vitest). This skill should be used when writing or debugging Vitest tests. This skill does NOT cover TDD methodology (use test-tdd skill), API mocking with MSW (use test-msw skill), or Jest-specific APIs.
910typescript
This skill should be used when the user asks to "optimize TypeScript performance", "speed up tsc compilation", "configure tsconfig.json", "fix type errors", "improve async patterns", or encounters TS errors (TS2322, TS2339, "is not assignable to"). Also triggers on .ts, .tsx, .d.ts file work involving type definitions, module organization, or memory management. Does NOT cover TypeScript basics, framework-specific patterns, or testing.
824nuqs
nuqs (type-safe URL query state) best practices for Next.js applications. This skill should be used when writing, reviewing, or refactoring code that uses nuqs for URL state management. Triggers on tasks involving useQueryState, useQueryStates, search params, URL state, query parameters, nuqs parsers, or Next.js routing with state.
739