ast-grep

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ast-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
    pattern
    for simple structures
  • Use
    kind
    with
    has
    /
    inside
    for complex structures
  • Combine with
    all
    ,
    any
    , or
    not
    for compound queries
  • Always use
    stopBy: end
    for relational rules
    (
    inside
    ,
    has
    ) to ensure complete search
选择合适的实现方式:
  • 简单结构使用
    pattern
  • 复杂结构结合
    kind
    has
    /
    inside
  • 使用
    all
    any
    not
    构建复合查询
  • 关联规则(
    inside
    has
    )务必使用
    stopBy: end
    ,以确保完整搜索

Step 4: Test the Rule

步骤4:测试规则

bash
undefined
bash
undefined

Inspect 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]
undefined
ast-grep scan --rule [file.yml] [path]
undefined

Step 5: Search the Codebase

步骤5:在代码库中执行搜索

Deploy the validated rule:
bash
undefined
部署验证后的规则:
bash
undefined

Search 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]
undefined
ast-grep scan --rule [file.yml] --interactive [path]
undefined

Quick Tips

快速提示

  1. Always use
    stopBy: end
    - Ensures complete subtree traversal for relational rules
  2. Start simple, add complexity - Begin with patterns, progress to kinds, then relational rules
  3. Debug with AST inspection - Use
    --debug-query=ast
    to verify structure matching
  4. Escape in inline rules - Use
    \$VAR
    or single quotes for shell commands
  5. Test in playground first - Use https://ast-grep.github.io/playground.html for rapid iteration
  1. 务必使用
    stopBy: end
    - 确保关联规则能完整遍历子树
  2. 从简单到复杂 - 先从模式入手,再逐步使用类型规则和关联规则
  3. 通过AST检查调试 - 使用
    --debug-query=ast
    验证结构匹配情况
  4. 内联规则转义 - 在Shell命令中使用
    \$VAR
    或单引号
  5. 先在沙箱测试 - 访问https://ast-grep.github.io/playground.html进行快速迭代

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Pattern CorrectnessCRITICAL
pattern-
2Meta Variable UsageCRITICAL
meta-
3Rule CompositionHIGH
compose-
4Constraint DesignHIGH
const-
5Rewrite CorrectnessMEDIUM-HIGH
rewrite-
6Project OrganizationMEDIUM
org-
7Performance OptimizationMEDIUM
perf-
8Testing & DebuggingLOW-MEDIUM
test-
优先级类别影响程度前缀
1模式正确性关键
pattern-
2元变量使用关键
meta-
3规则组合
compose-
4约束条件设计
const-
5重写正确性中高
rewrite-
6项目结构
org-
7性能优化
perf-
8测试与调试中低
test-

Quick Reference

快速参考

1. Pattern Correctness (CRITICAL)

1. 模式正确性(关键)

  • pattern-valid-syntax
    - Use valid parseable code as patterns
  • pattern-language-aware
    - Account for language-specific syntax differences
  • pattern-context-selector
    - Use context and selector for code fragments
  • pattern-avoid-comments-strings
    - Avoid matching inside comments and strings
  • pattern-strictness-levels
    - Configure pattern strictness appropriately
  • pattern-kind-vs-pattern
    - Choose kind or pattern based on specificity needs
  • pattern-debug-ast
    - Use debug query to inspect AST structure
  • pattern-nthchild-matching
    - Use nthChild for index-based positional matching
  • pattern-range-matching
    - Use range for character position matching
  • pattern-valid-syntax
    - 使用可解析的有效代码作为模式
  • pattern-language-aware
    - 考虑编程语言的语法差异
  • pattern-context-selector
    - 为代码片段使用上下文和选择器
  • pattern-avoid-comments-strings
    - 避免匹配注释和字符串内容
  • pattern-strictness-levels
    - 合理配置模式严格度
  • pattern-kind-vs-pattern
    - 根据特异性需求选择kind或pattern
  • pattern-debug-ast
    - 使用调试查询检查AST结构
  • pattern-nthchild-matching
    - 使用nthChild进行基于索引的位置匹配
  • pattern-range-matching
    - 使用range进行字符位置匹配

2. Meta Variable Usage (CRITICAL)

2. 元变量使用(关键)

  • meta-naming-convention
    - Follow meta variable naming conventions
  • meta-single-node
    - Match single AST nodes with meta variables
  • meta-reuse-binding
    - Reuse meta variables to enforce equality
  • meta-underscore-noncapture
    - Use underscore prefix for non-capturing matches
  • meta-named-vs-unnamed
    - Use double dollar for unnamed node matching
  • meta-multi-match-lazy
    - Understand multi-match variables are lazy
  • meta-naming-convention
    - 遵循元变量命名规范
  • meta-single-node
    - 使用元变量匹配单个AST节点
  • meta-reuse-binding
    - 复用元变量以确保一致性
  • meta-underscore-noncapture
    - 使用下划线前缀表示非捕获匹配
  • meta-named-vs-unnamed
    - 使用双美元符号匹配未命名节点
  • meta-multi-match-lazy
    - 了解多匹配变量的惰性特性

3. Rule Composition (HIGH)

3. 规则组合(高)

  • compose-all-for-and-logic
    - Use all for AND logic between rules
  • compose-any-for-or-logic
    - Use any for OR logic between rules
  • compose-not-for-exclusion
    - Use not for exclusion patterns
  • compose-inside-for-context
    - Use inside for contextual matching
  • compose-has-for-children
    - Use has for child node requirements
  • compose-matches-for-reuse
    - Use matches for rule reusability
  • compose-precedes-follows
    - Use precedes and follows for sequential positioning
  • compose-field-targeting
    - Use field to target specific sub-nodes
  • compose-all-for-and-logic
    - 使用all实现规则间的逻辑与
  • compose-any-for-or-logic
    - 使用any实现规则间的逻辑或
  • compose-not-for-exclusion
    - 使用not实现排除模式
  • compose-inside-for-context
    - 使用inside实现上下文匹配
  • compose-has-for-children
    - 使用has定义子节点要求
  • compose-matches-for-reuse
    - 使用matches实现规则复用
  • compose-precedes-follows
    - 使用precedes和follows实现顺序位置匹配
  • compose-field-targeting
    - 使用field定位特定子节点

4. Constraint Design (HIGH)

4. 约束条件设计(高)

  • const-kind-filter
    - Use kind constraints to filter meta variables
  • const-regex-filter
    - Use regex constraints for text patterns
  • const-not-inside-not
    - Avoid constraints inside not rules
  • const-pattern-constraint
    - Use pattern constraints for structural filtering
  • const-post-match-timing
    - Understand constraints apply after matching
  • const-kind-filter
    - 使用类型约束过滤元变量
  • const-regex-filter
    - 使用正则约束匹配文本模式
  • const-not-inside-not
    - 避免在not规则内使用约束
  • const-pattern-constraint
    - 使用模式约束实现结构过滤
  • const-post-match-timing
    - 了解约束在匹配完成后生效

5. Rewrite Correctness (MEDIUM-HIGH)

5. 重写正确性(中高)

  • rewrite-preserve-semantics
    - Preserve program semantics in rewrites
  • rewrite-meta-variable-reference
    - Reference all necessary meta variables in fix
  • rewrite-transform-operations
    - Use transform for complex rewrites
  • rewrite-test-before-deploy
    - Test rewrites on representative code
  • rewrite-syntax-validity
    - Ensure fix templates produce valid syntax
  • rewrite-preserve-semantics
    - 在重写时保留程序语义
  • rewrite-meta-variable-reference
    - 在修复逻辑中引用所有必要的元变量
  • rewrite-transform-operations
    - 使用transform实现复杂重写
  • rewrite-test-before-deploy
    - 在代表性代码上测试重写逻辑
  • rewrite-syntax-validity
    - 确保修复模板生成有效语法

6. Project Organization (MEDIUM)

6. 项目结构(中)

  • org-project-structure
    - Use standard project directory structure
  • org-unique-rule-ids
    - Use unique descriptive rule IDs
  • org-severity-levels
    - Assign appropriate severity levels
  • org-file-filtering
    - Use file filtering for targeted rules
  • org-message-clarity
    - Write clear actionable messages
  • org-project-structure
    - 使用标准项目目录结构
  • org-unique-rule-ids
    - 使用唯一且具有描述性的规则ID
  • org-severity-levels
    - 分配合适的严重级别
  • org-file-filtering
    - 使用文件过滤实现规则定向
  • org-message-clarity
    - 编写清晰且可执行的提示信息

7. Performance Optimization (MEDIUM)

7. 性能优化(中)

  • perf-specific-patterns
    - Use specific patterns over generic ones
  • perf-stopby-boundaries
    - Use stopBy to limit search depth
  • perf-thread-parallelism
    - Leverage parallel scanning with threads
  • perf-avoid-regex-heavy
    - Avoid heavy regex in hot paths
  • perf-specific-patterns
    - 使用特定模式而非通用模式
  • perf-stopby-boundaries
    - 使用stopBy限制搜索深度
  • perf-thread-parallelism
    - 利用多线程实现并行扫描
  • perf-avoid-regex-heavy
    - 在高频路径中避免复杂正则

8. Testing & Debugging (LOW-MEDIUM)

8. 测试与调试(中低)

  • test-valid-invalid-cases
    - Write both valid and invalid test cases
  • test-snapshot-updates
    - Use snapshot testing for fix verification
  • test-playground-first
    - Test patterns in playground first
  • test-edge-cases
    - Test edge cases and boundary conditions
  • 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

参考文件

FileDescription
AGENTS.mdComplete compiled guide with all rules
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
AGENTS.md包含所有规则的完整编译指南
references/_sections.md类别定义与排序说明
assets/templates/_template.md新增规则的模板
metadata.json版本与参考信息