ast-grep
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseast-grep Code Search
ast-grep 代码搜索
Overview
概述
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.
本技能可帮助将自然语言查询转换为ast-grep规则,用于结构化代码搜索。ast-grep使用抽象语法树(AST)模式,基于代码结构而非仅文本进行匹配,能够在大型代码库中实现强大且精准的代码搜索。
When to Use This Skill
适用场景
Use this skill when users:
- Need to search for code patterns using structural matching (e.g., "find all async functions that don't have error handling")
- Want to locate specific language constructs (e.g., "find all function calls with specific parameters")
- Request searches that require understanding code structure rather than just text
- Ask to search for code with particular AST characteristics
- Need to perform complex code queries that traditional text search cannot handle
当用户有以下需求时,使用本技能:
- 需要通过结构匹配搜索代码模式(例如:“查找所有未做错误处理的异步函数”)
- 想要定位特定语言构造(例如:“查找所有带有特定参数的函数调用”)
- 请求需要理解代码结构而非仅文本的搜索
- 要求查找具有特定AST特征的代码
- 需要执行传统文本搜索无法处理的复杂代码查询
General Workflow
通用工作流程
Follow this process to help users write effective ast-grep rules:
遵循以下流程,帮助用户编写有效的ast-grep规则:
Step 1: Understand the Query
步骤1:理解查询需求
Clearly understand what the user wants to find. Ask clarifying questions if needed:
- What specific code pattern or structure are they looking for?
- Which programming language?
- Are there specific edge cases or variations to consider?
- What should be included or excluded from matches?
明确用户想要查找的内容。如有需要,提出澄清问题:
- 他们要查找的具体代码模式或结构是什么?
- 针对哪种编程语言?
- 是否有需要考虑的特定边缘情况或变体?
- 匹配结果应包含或排除哪些内容?
Step 2: Create Example Code
步骤2:创建示例代码
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:
javascript
// test_example.js
async function example() {
const result = await fetchData();
return result;
}编写一个简单的代码片段,代表用户想要匹配的内容。将其保存到临时文件中用于测试。
示例:
如果要搜索“使用await的异步函数”,创建测试文件:
javascript
// test_example.js
async function example() {
const result = await fetchData();
return result;
}Step 3: Write the ast-grep Rule
步骤3:编写ast-grep规则
Translate the pattern into an ast-grep rule. Start simple and add complexity as needed.
Key principles:
- Always use for relational rules (
stopBy: end,inside) to ensure search goes to the end of the directionhas - Use for simple structures
pattern - Use with
kind/hasfor complex structuresinside - Break complex queries into smaller sub-rules using ,
all, oranynot
Example rule file (test_rule.yml):
yaml
id: async-with-await
language: javascript
rule:
kind: function_declaration
has:
pattern: await $EXPR
stopBy: endSee for comprehensive rule documentation.
references/rule_reference.md将模式转换为ast-grep规则。从简单规则开始,逐步增加复杂度。
核心原则:
- 对于关系型规则(、
inside),始终使用has,确保搜索覆盖整个指定方向的范围stopBy: end - 简单结构使用
pattern - 复杂结构结合与
kind/hasinside - 使用、
all或any将复杂查询拆分为更小的子规则not
示例规则文件(test_rule.yml):
yaml
id: async-with-await
language: javascript
rule:
kind: function_declaration
has:
pattern: await $EXPR
stopBy: end如需全面的规则文档,请查看。
references/rule_reference.mdStep 4: Test the Rule
步骤4:测试规则
Use ast-grep CLI to verify the rule matches the example code. There are two main approaches:
Option A: Test with inline rules (for quick iterations)
bash
echo "async function test() { await fetch(); }" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
kind: function_declaration
has:
pattern: await \$EXPR
stopBy: end" --stdinOption B: Test with rule files (recommended for complex rules)
bash
ast-grep scan --rule test_rule.yml test_example.jsDebugging if no matches:
- Simplify the rule (remove sub-rules)
- Add to relational rules if not present
stopBy: end - Use to understand the AST structure (see below)
--debug-query - Check if values are correct for the language
kind
使用ast-grep CLI验证规则是否匹配示例代码。主要有两种方法:
方法A:使用内联规则测试(快速迭代)
bash
echo "async function test() { await fetch(); }" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
kind: function_declaration
has:
pattern: await \$EXPR
stopBy: end" --stdin方法B:使用规则文件测试(复杂规则推荐)
bash
ast-grep scan --rule test_rule.yml test_example.js无匹配结果时的调试步骤:
- 简化规则(移除子规则)
- 若未添加,为关系型规则加上
stopBy: end - 使用了解AST结构(见下文)
--debug-query - 检查针对目标语言的值是否正确
kind
Step 5: Search the Codebase
步骤5:搜索代码库
Once the rule matches the example code correctly, search the actual codebase:
For simple pattern searches:
bash
ast-grep run --pattern 'console.log($ARG)' --lang javascript /path/to/projectFor complex rule-based searches:
bash
ast-grep scan --rule my_rule.yml /path/to/projectFor inline rules (without creating files):
bash
ast-grep scan --inline-rules "id: my-rule
language: javascript
rule:
pattern: \$PATTERN" /path/to/project当规则能正确匹配示例代码后,即可在实际代码库中进行搜索:
简单模式搜索:
bash
ast-grep run --pattern 'console.log($ARG)' --lang javascript /path/to/project复杂规则搜索:
bash
ast-grep scan --rule my_rule.yml /path/to/project内联规则搜索(无需创建文件):
bash
ast-grep scan --inline-rules "id: my-rule
language: javascript
rule:
pattern: \$PATTERN" /path/to/projectast-grep CLI Commands
ast-grep CLI 命令
Inspect Code Structure (--debug-query)
检查代码结构(--debug-query)
Dump the AST structure to understand how code is parsed:
bash
ast-grep run --pattern 'async function example() { await fetch(); }' \
--lang javascript \
--debug-query=cstAvailable formats:
- : Concrete Syntax Tree (shows all nodes including punctuation)
cst - : Abstract Syntax Tree (shows only named nodes)
ast - : Shows how ast-grep interprets your pattern
pattern
Use this to:
- Find the correct values for nodes
kind - Understand the structure of code you want to match
- Debug why patterns aren't matching
Example:
bash
undefined导出AST结构,了解代码的解析方式:
bash
ast-grep run --pattern 'async function example() { await fetch(); }' \
--lang javascript \
--debug-query=cst可用格式:
- : 具体语法树(显示所有节点,包括标点符号)
cst - : 抽象语法树(仅显示命名节点)
ast - : 显示ast-grep如何解析你的模式
pattern
用途:
- 查找节点对应的正确值
kind - 理解要匹配的代码结构
- 调试模式不匹配的原因
示例:
bash
undefinedSee the structure of your target code
查看目标代码的结构
ast-grep run --pattern 'class User { constructor() {} }'
--lang javascript
--debug-query=cst
--lang javascript
--debug-query=cst
ast-grep run --pattern 'class User { constructor() {} }'
--lang javascript
--debug-query=cst
--lang javascript
--debug-query=cst
See how ast-grep interprets your pattern
查看ast-grep如何解析你的模式
ast-grep run --pattern 'class $NAME { $$$BODY }'
--lang javascript
--debug-query=pattern
--lang javascript
--debug-query=pattern
undefinedast-grep run --pattern 'class $NAME { $$$BODY }'
--lang javascript
--debug-query=pattern
--lang javascript
--debug-query=pattern
undefinedTest Rules (scan with --stdin)
测试规则(结合--stdin的scan命令)
Test a rule against code snippet without creating files:
bash
echo "const x = await fetch();" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
pattern: await \$EXPR" --stdinAdd --json for structured output:
bash
echo "const x = await fetch();" | ast-grep scan --inline-rules "..." --stdin --json无需创建文件,直接针对代码片段测试规则:
bash
echo "const x = await fetch();" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
pattern: await \$EXPR" --stdin添加--json获取结构化输出:
bash
echo "const x = await fetch();" | ast-grep scan --inline-rules "..." --stdin --jsonSearch with Patterns (run)
模式搜索(run命令)
Simple pattern-based search for single AST node matches:
bash
undefined基于简单模式的搜索,匹配单个AST节点:
bash
undefinedBasic pattern search
基础模式搜索
ast-grep run --pattern 'console.log($ARG)' --lang javascript .
ast-grep run --pattern 'console.log($ARG)' --lang javascript .
Search specific files
搜索特定文件
ast-grep run --pattern 'class $NAME' --lang python /path/to/project
ast-grep run --pattern 'class $NAME' --lang python /path/to/project
JSON output for programmatic use
用于程序化调用的JSON输出
ast-grep run --pattern 'function $NAME($$$)' --lang javascript --json .
**When to use:**
- Simple, single-node matches
- Quick searches without complex logic
- When you don't need relational rules (inside/has)ast-grep run --pattern 'function $NAME($$$)' --lang javascript --json .
**适用场景:**
- 简单的单节点匹配
- 无需复杂逻辑的快速搜索
- 不需要关系型规则(inside/has)的场景Search with Rules (scan)
规则搜索(scan命令)
YAML rule-based search for complex structural queries:
bash
undefined基于YAML规则的搜索,用于复杂的结构化查询:
bash
undefinedWith rule file
使用规则文件
ast-grep scan --rule my_rule.yml /path/to/project
ast-grep scan --rule my_rule.yml /path/to/project
With inline rules
使用内联规则
ast-grep scan --inline-rules "id: find-async
language: javascript
rule:
kind: function_declaration
has:
pattern: await $EXPR
stopBy: end" /path/to/project
ast-grep scan --inline-rules "id: find-async
language: javascript
rule:
kind: function_declaration
has:
pattern: await $EXPR
stopBy: end" /path/to/project
JSON output
JSON输出
ast-grep scan --rule my_rule.yml --json /path/to/project
**When to use:**
- Complex structural searches
- Relational rules (inside, has, precedes, follows)
- Composite logic (all, any, not)
- When you need the power of full YAML rules
**Tip:** For relational rules (inside/has), always add `stopBy: end` to ensure complete traversal.ast-grep scan --rule my_rule.yml --json /path/to/project
**适用场景:**
- 复杂的结构化搜索
- 关系型规则(inside, has, precedes, follows)
- 复合逻辑(all, any, not)
- 需要完整YAML规则能力的场景
**提示:** 对于关系型规则(inside/has),始终添加`stopBy: end`以确保完整遍历。Tips for Writing Effective Rules
编写有效规则的技巧
Always Use stopBy: end
始终使用stopBy: end
For relational rules, always use unless there's a specific reason not to:
stopBy: endyaml
has:
pattern: await $EXPR
stopBy: endThis ensures the search traverses the entire subtree rather than stopping at the first non-matching node.
对于关系型规则,除非有特殊原因,否则始终使用:
stopBy: endyaml
has:
pattern: await $EXPR
stopBy: end这确保搜索遍历整个子树,而非在第一个不匹配的节点处停止。
Start Simple, Then Add Complexity
从简单到复杂逐步构建
Begin with the simplest rule that could work:
- Try a first
pattern - If that doesn't work, try to match the node type
kind - Add relational rules (,
has) as neededinside - Combine with composite rules (,
all,any) for complex logicnot
从最简单的可行规则开始:
- 先尝试使用
pattern - 如果不行,尝试使用匹配节点类型
kind - 按需添加关系型规则(、
has)inside - 结合复合规则(、
all、any)实现复杂逻辑not
Use the Right Rule Type
选择合适的规则类型
- Pattern: For simple, direct code matching (e.g., )
console.log($ARG) - Kind + Relational: For complex structures (e.g., "function containing await")
- Composite: For logical combinations (e.g., "function with await but not in try-catch")
- Pattern:用于简单、直接的代码匹配(例如:)
console.log($ARG) - Kind + 关系型规则:用于复杂结构(例如:“包含await的函数”)
- 复合规则:用于逻辑组合(例如:“包含await但不在try-catch中的函数”)
Debug with AST Inspection
用AST检查工具调试
When rules don't match:
- Use to see the actual AST structure
--debug-query=cst - Check if metavariables are being detected correctly
- Verify the node matches what you expect
kind - Ensure relational rules are searching in the right direction
当规则不匹配时:
- 使用查看实际的AST结构
--debug-query=cst - 检查元变量是否被正确识别
- 验证节点的是否符合预期
kind - 确保关系型规则的搜索方向正确
Escaping in Inline Rules
内联规则中的转义处理
When using , escape metavariables in shell commands:
--inline-rules- Use instead of
\$VAR(shell interprets$VARas variable)$ - Or use single quotes: works in most shells
'$VAR'
Example:
bash
undefined使用时,在shell命令中需要转义元变量:
--inline-rules- 使用代替
\$VAR(shell会将$VAR解析为变量)$ - 或使用单引号:在大多数shell中有效
'$VAR'
示例:
bash
undefinedCorrect: escaped $
正确写法:转义$
ast-grep scan --inline-rules "rule: {pattern: 'console.log($ARG)'}" .
ast-grep scan --inline-rules "rule: {pattern: 'console.log($ARG)'}" .
Or use single quotes
或使用单引号
ast-grep scan --inline-rules 'rule: {pattern: "console.log($ARG)"}' .
undefinedast-grep scan --inline-rules 'rule: {pattern: "console.log($ARG)"}' .
undefinedCommon Use Cases
常见使用场景
Find Functions with Specific Content
查找包含特定内容的函数
Find async functions that use await:
bash
ast-grep scan --inline-rules "id: async-await
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end" /path/to/project查找使用await的异步函数:
bash
ast-grep scan --inline-rules "id: async-await
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end" /path/to/projectFind Code Inside Specific Contexts
查找特定上下文内的代码
Find console.log inside class methods:
bash
ast-grep scan --inline-rules "id: console-in-class
language: javascript
rule:
pattern: console.log(\$\$\$)
inside:
kind: method_definition
stopBy: end" /path/to/project查找类方法中的console.log:
bash
ast-grep scan --inline-rules "id: console-in-class
language: javascript
rule:
pattern: console.log(\$\$\$)
inside:
kind: method_definition
stopBy: end" /path/to/projectFind Code Missing Expected Patterns
查找缺少预期模式的代码
Find async functions without try-catch:
bash
ast-grep scan --inline-rules "id: async-no-trycatch
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end
- not:
has:
pattern: try { \$\$\$ } catch (\$E) { \$\$\$ }
stopBy: end" /path/to/project查找未使用try-catch的异步函数:
bash
ast-grep scan --inline-rules "id: async-no-trycatch
language: javascript
rule:
all:
- kind: function_declaration
- has:
pattern: await \$EXPR
stopBy: end
- not:
has:
pattern: try { \$\$\$ } catch (\$E) { \$\$\$ }
stopBy: end" /path/to/projectResources
资源
references/
references/
Contains detailed documentation for ast-grep rule syntax:
- : Comprehensive ast-grep rule documentation covering atomic rules, relational rules, composite rules, and metavariables
rule_reference.md
Load these references when detailed rule syntax information is needed.
包含ast-grep规则语法的详细文档:
- : 全面的ast-grep规则文档,涵盖原子规则、关系型规则、复合规则和元变量
rule_reference.md
当需要详细的规则语法信息时,请查阅这些参考资料。