ast-grep
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseast-grep Community Best Practices
ast-grep社区最佳实践
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.
本指南由ast-grep社区维护,是关于ast-grep规则编写与使用的综合最佳实践手册。包含8个类别下的46条规则,按影响优先级排序,可指导自动化规则生成与代码转换工作。
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
在以下场景中可参考本指南:
- 为代码检查或搜索编写新的ast-grep规则
- 调试无法匹配预期代码的规则模式
- 针对大型代码库优化规则性能
- 搭建结构规范的ast-grep项目
- 评审ast-grep规则的正确性与可维护性
General Workflow
通用工作流程
Follow this workflow when creating ast-grep rules for code search:
创建用于代码搜索的ast-grep规则时,遵循以下流程:
Step 1: Understand the Query
步骤1:明确查询需求
Clarify what you want to find:
- Target programming language
- Edge cases to handle
- What to include vs exclude
确定你要查找的内容:
- 目标编程语言
- 需要处理的边缘情况
- 需要包含和排除的内容
Step 2: Create Example Code
步骤2:编写示例代码
Write a sample code snippet representing the desired match pattern.
编写能代表预期匹配模式的示例代码片段。
Step 3: Write the ast-grep Rule
步骤3:编写ast-grep规则
Choose the right approach:
- Use for simple structures
pattern - Use with
kind/hasfor complex structuresinside - Combine with ,
all, oranyfor compound queriesnot - Always use for relational rules (
stopBy: end,inside) to ensure complete searchhas
选择合适的实现方式:
- 简单结构使用
pattern - 复杂结构结合与
kind/hasinside - 使用、
all或any构建复合查询not - 关联规则(、
inside)务必使用has,以确保完整搜索stopBy: end
Step 4: Test the Rule
步骤4:测试规则
bash
undefinedbash
undefinedInspect AST structure
检查AST结构
ast-grep run --pattern '[code]' --lang [language] --debug-query=ast
ast-grep run --pattern '[code]' --lang [language] --debug-query=ast
Test inline rule
测试内联规则
echo "[code]" | ast-grep scan --inline-rules "[rule]" --stdin
echo "[code]" | ast-grep scan --inline-rules "[rule]" --stdin
Test from file
测试文件中的规则
ast-grep scan --rule [file.yml] [path]
undefinedast-grep scan --rule [file.yml] [path]
undefinedStep 5: Search the Codebase
步骤5:在代码库中执行搜索
Deploy the validated rule:
bash
undefined部署验证后的规则:
bash
undefinedSearch with pattern (simple matches)
使用模式搜索(简单匹配)
ast-grep run --pattern '[pattern]' --lang [language] [path]
ast-grep run --pattern '[pattern]' --lang [language] [path]
Search with rule file (complex queries)
使用规则文件搜索(复杂查询)
ast-grep scan --rule [file.yml] [path]
ast-grep scan --rule [file.yml] [path]
Apply fixes interactively
交互式应用修复
ast-grep scan --rule [file.yml] --interactive [path]
undefinedast-grep scan --rule [file.yml] --interactive [path]
undefinedQuick Tips
快速提示
- Always use - Ensures complete subtree traversal for relational rules
stopBy: end - Start simple, add complexity - Begin with patterns, progress to kinds, then relational rules
- Debug with AST inspection - Use to verify structure matching
--debug-query=ast - Escape in inline rules - Use or single quotes for shell commands
\$VAR - Test in playground first - Use https://ast-grep.github.io/playground.html for rapid iteration
- 务必使用- 确保关联规则能完整遍历子树
stopBy: end - 从简单到复杂 - 先从模式入手,再逐步使用类型规则和关联规则
- 通过AST检查调试 - 使用验证结构匹配情况
--debug-query=ast - 内联规则转义 - 在Shell命令中使用或单引号
\$VAR - 先在沙箱测试 - 访问https://ast-grep.github.io/playground.html进行快速迭代
Rule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Pattern Correctness | CRITICAL | |
| 2 | Meta Variable Usage | CRITICAL | |
| 3 | Rule Composition | HIGH | |
| 4 | Constraint Design | HIGH | |
| 5 | Rewrite Correctness | MEDIUM-HIGH | |
| 6 | Project Organization | MEDIUM | |
| 7 | Performance Optimization | MEDIUM | |
| 8 | Testing & Debugging | LOW-MEDIUM | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 模式正确性 | 关键 | |
| 2 | 元变量使用 | 关键 | |
| 3 | 规则组合 | 高 | |
| 4 | 约束条件设计 | 高 | |
| 5 | 重写正确性 | 中高 | |
| 6 | 项目结构 | 中 | |
| 7 | 性能优化 | 中 | |
| 8 | 测试与调试 | 中低 | |
Quick Reference
快速参考
1. Pattern Correctness (CRITICAL)
1. 模式正确性(关键)
- - Use valid parseable code as patterns
pattern-valid-syntax - - Account for language-specific syntax differences
pattern-language-aware - - Use context and selector for code fragments
pattern-context-selector - - Avoid matching inside comments and strings
pattern-avoid-comments-strings - - Configure pattern strictness appropriately
pattern-strictness-levels - - Choose kind or pattern based on specificity needs
pattern-kind-vs-pattern - - Use debug query to inspect AST structure
pattern-debug-ast - - Use nthChild for index-based positional matching
pattern-nthchild-matching - - Use range for character position matching
pattern-range-matching
- - 使用可解析的有效代码作为模式
pattern-valid-syntax - - 考虑编程语言的语法差异
pattern-language-aware - - 为代码片段使用上下文和选择器
pattern-context-selector - - 避免匹配注释和字符串内容
pattern-avoid-comments-strings - - 合理配置模式严格度
pattern-strictness-levels - - 根据特异性需求选择kind或pattern
pattern-kind-vs-pattern - - 使用调试查询检查AST结构
pattern-debug-ast - - 使用nthChild进行基于索引的位置匹配
pattern-nthchild-matching - - 使用range进行字符位置匹配
pattern-range-matching
2. Meta Variable Usage (CRITICAL)
2. 元变量使用(关键)
- - Follow meta variable naming conventions
meta-naming-convention - - Match single AST nodes with meta variables
meta-single-node - - Reuse meta variables to enforce equality
meta-reuse-binding - - Use underscore prefix for non-capturing matches
meta-underscore-noncapture - - Use double dollar for unnamed node matching
meta-named-vs-unnamed - - Understand multi-match variables are lazy
meta-multi-match-lazy
- - 遵循元变量命名规范
meta-naming-convention - - 使用元变量匹配单个AST节点
meta-single-node - - 复用元变量以确保一致性
meta-reuse-binding - - 使用下划线前缀表示非捕获匹配
meta-underscore-noncapture - - 使用双美元符号匹配未命名节点
meta-named-vs-unnamed - - 了解多匹配变量的惰性特性
meta-multi-match-lazy
3. Rule Composition (HIGH)
3. 规则组合(高)
- - Use all for AND logic between rules
compose-all-for-and-logic - - Use any for OR logic between rules
compose-any-for-or-logic - - Use not for exclusion patterns
compose-not-for-exclusion - - Use inside for contextual matching
compose-inside-for-context - - Use has for child node requirements
compose-has-for-children - - Use matches for rule reusability
compose-matches-for-reuse - - Use precedes and follows for sequential positioning
compose-precedes-follows - - Use field to target specific sub-nodes
compose-field-targeting
- - 使用all实现规则间的逻辑与
compose-all-for-and-logic - - 使用any实现规则间的逻辑或
compose-any-for-or-logic - - 使用not实现排除模式
compose-not-for-exclusion - - 使用inside实现上下文匹配
compose-inside-for-context - - 使用has定义子节点要求
compose-has-for-children - - 使用matches实现规则复用
compose-matches-for-reuse - - 使用precedes和follows实现顺序位置匹配
compose-precedes-follows - - 使用field定位特定子节点
compose-field-targeting
4. Constraint Design (HIGH)
4. 约束条件设计(高)
- - Use kind constraints to filter meta variables
const-kind-filter - - Use regex constraints for text patterns
const-regex-filter - - Avoid constraints inside not rules
const-not-inside-not - - Use pattern constraints for structural filtering
const-pattern-constraint - - Understand constraints apply after matching
const-post-match-timing
- - 使用类型约束过滤元变量
const-kind-filter - - 使用正则约束匹配文本模式
const-regex-filter - - 避免在not规则内使用约束
const-not-inside-not - - 使用模式约束实现结构过滤
const-pattern-constraint - - 了解约束在匹配完成后生效
const-post-match-timing
5. Rewrite Correctness (MEDIUM-HIGH)
5. 重写正确性(中高)
- - Preserve program semantics in rewrites
rewrite-preserve-semantics - - Reference all necessary meta variables in fix
rewrite-meta-variable-reference - - Use transform for complex rewrites
rewrite-transform-operations - - Test rewrites on representative code
rewrite-test-before-deploy - - Ensure fix templates produce valid syntax
rewrite-syntax-validity
- - 在重写时保留程序语义
rewrite-preserve-semantics - - 在修复逻辑中引用所有必要的元变量
rewrite-meta-variable-reference - - 使用transform实现复杂重写
rewrite-transform-operations - - 在代表性代码上测试重写逻辑
rewrite-test-before-deploy - - 确保修复模板生成有效语法
rewrite-syntax-validity
6. Project Organization (MEDIUM)
6. 项目结构(中)
- - Use standard project directory structure
org-project-structure - - Use unique descriptive rule IDs
org-unique-rule-ids - - Assign appropriate severity levels
org-severity-levels - - Use file filtering for targeted rules
org-file-filtering - - Write clear actionable messages
org-message-clarity
- - 使用标准项目目录结构
org-project-structure - - 使用唯一且具有描述性的规则ID
org-unique-rule-ids - - 分配合适的严重级别
org-severity-levels - - 使用文件过滤实现规则定向
org-file-filtering - - 编写清晰且可执行的提示信息
org-message-clarity
7. Performance Optimization (MEDIUM)
7. 性能优化(中)
- - Use specific patterns over generic ones
perf-specific-patterns - - Use stopBy to limit search depth
perf-stopby-boundaries - - Leverage parallel scanning with threads
perf-thread-parallelism - - Avoid heavy regex in hot paths
perf-avoid-regex-heavy
- - 使用特定模式而非通用模式
perf-specific-patterns - - 使用stopBy限制搜索深度
perf-stopby-boundaries - - 利用多线程实现并行扫描
perf-thread-parallelism - - 在高频路径中避免复杂正则
perf-avoid-regex-heavy
8. Testing & Debugging (LOW-MEDIUM)
8. 测试与调试(中低)
- - Write both valid and invalid test cases
test-valid-invalid-cases - - Use snapshot testing for fix verification
test-snapshot-updates - - Test patterns in playground first
test-playground-first - - Test edge cases and boundary conditions
test-edge-cases
- - 编写有效和无效两种测试用例
test-valid-invalid-cases - - 使用快照测试验证修复效果
test-snapshot-updates - - 先在沙箱中测试模式
test-playground-first - - 测试边缘情况和边界条件
test-edge-cases
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
- AGENTS.md - 包含所有规则的完整编译指南
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 |
| 文件 | 描述 |
|---|---|
| AGENTS.md | 包含所有规则的完整编译指南 |
| references/_sections.md | 类别定义与排序说明 |
| assets/templates/_template.md | 新增规则的模板 |
| metadata.json | 版本与参考信息 |