鱼皮AI导航
鱼皮AI导航
  • 主页
  • 社区
  • AI工具
  • AI知识库
  • AI提示词
  • MCP
  • Skills
  • AI学习资源
  • AI资讯
  • GitHub开源
登录/注册

ast-grep

提供基于抽象语法树的结构化代码搜索能力,支持跨语言精准匹配代码模式、定位特定语法结构、识别复杂代码特征,适用于需理解代码语义而非简单文本匹配的深度代码分析场景。

访问 GitHub
文档Skills.MD
name
ast-grep
description
Guide for writing ast-grep rules to perform structural code search and analysis. Use when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or perform complex code queries that go beyond simple text search. This skill should be used when users ask to search for code patterns, find specific language constructs, or locate code with particular structural characteristics.

ast-grep Code Search

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.

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

General Workflow

Follow this process to help users write effective ast-grep rules:

Step 1: Understand the Query

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

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; }

Step 3: Write the ast-grep Rule

Translate the pattern into an ast-grep rule. Start simple and add complexity as needed.

Key principles:

  • Always use stopBy: end for relational rules (inside, has) to ensure search goes to the end of the direction
  • Use pattern for simple structures
  • Use kind with has/inside for complex structures
  • Break complex queries into smaller sub-rules using all, any, or not

Example rule file (test_rule.yml):

▼
yaml
复制代码
id: async-with-await language: javascript rule: kind: function_declaration has: pattern: await $EXPR stopBy: end

See references/rule_reference.md for comprehensive rule documentation.

Step 4: Test the Rule

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" --stdin

Option B: Test with rule files (recommended for complex rules)

▼
bash
复制代码
ast-grep scan --rule test_rule.yml test_example.js

Debugging if no matches:

  1. Simplify the rule (remove sub-rules)
  2. Add stopBy: end to relational rules if not present
  3. Use --debug-query to understand the AST structure (see below)
  4. Check if kind values are correct for the language
  5. For zero matches from run --pattern (not rules), see the "Zero Matches?" tip below

Step 5: Search the Codebase

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/project

For complex rule-based searches:

▼
bash
复制代码
ast-grep scan --rule my_rule.yml /path/to/project

For inline rules (without creating files):

▼
bash
复制代码
ast-grep scan --inline-rules "id: my-rule language: javascript rule: pattern: \$PATTERN" /path/to/project

ast-grep CLI Commands

Inspect Code Structure (--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=cst

Available formats:

  • cst: Concrete Syntax Tree (shows all nodes including punctuation)
  • ast: Abstract Syntax Tree (shows only named nodes)
  • pattern: Shows how ast-grep interprets your pattern

Use this to:

  • Find the correct kind values for nodes
  • Understand the structure of code you want to match
  • Debug why patterns aren't matching

Example:

▼
bash
复制代码
# See the structure of your target code ast-grep run --pattern 'class User { constructor() {} }' \ --lang javascript \ --debug-query=cst # See how ast-grep interprets your pattern ast-grep run --pattern 'class $NAME { $$$BODY }' \ --lang javascript \ --debug-query=pattern

Test Rules (scan with --stdin)

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" --stdin

Add --json for structured output:

▼
bash
复制代码
echo "const x = await fetch();" | ast-grep scan --inline-rules "..." --stdin --json

Search with Patterns (run)

Simple pattern-based search for single AST node matches:

▼
bash
复制代码
# Basic pattern search ast-grep run --pattern 'console.log($ARG)' --lang javascript . # Search specific files ast-grep run --pattern 'class $NAME' --lang python /path/to/project # JSON output for programmatic use 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)

Reading --json Output

--json prints a bare JSON array of matches (no matches wrapper). For pattern foo($ARG, $$$REST):

▼
json
复制代码
[{ "text": "foo(\"value\", 1, 2)", "file": "src/app.js", "range": { "start": { "line": 41, "column": 10 }, "end": { "line": 41, "column": 27 } }, "metaVariables": { "single": { "ARG": { "text": "\"value\"" } }, "multi": { "REST": [ { "text": "1" }, { "text": "2" } ] } } }]

scan --json uses the same schema.

(Each match also includes lines and language.) range.start.line is 0-based. Named metavariables ($ARG) land in single, list metavariables ($$$REST) in multi as a list (empty if nothing captured). Extract with jq:

▼
bash
复制代码
ast-grep run --pattern 'foo($ARG)' --lang javascript --json . \ | jq -r '.[] | "\(.file):\(.range.start.line + 1): \(.metaVariables.single.ARG.text)"'

Search with Rules (scan)

YAML rule-based search for complex structural queries:

▼
bash
复制代码
# With rule file 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 # JSON output 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.

Tips for Writing Effective Rules

Always Use stopBy: end

For relational rules, always use stopBy: end unless there's a specific reason not to:

▼
yaml
复制代码
has: pattern: await $EXPR stopBy: end

This ensures the search traverses the entire subtree rather than stopping at the first non-matching node.

Start Simple, Then Add Complexity

Begin with the simplest rule that could work:

  1. Try a pattern first
  2. If that doesn't work, try kind to match the node type
  3. Add relational rules (has, inside) as needed
  4. Combine with composite rules (all, any, not) for complex logic

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")

Debug with AST Inspection

When rules don't match:

  1. Use --debug-query=cst to see the actual AST structure
  2. Check if metavariables are being detected correctly
  3. Verify the node kind matches what you expect
  4. Ensure relational rules are searching in the right direction

Zero Matches? Patterns Match Whole AST Nodes

run --pattern matches complete AST nodes, not text substrings, so zero matches can mean "code absent" or "pattern has the wrong node shape":

  • Qualified paths are whole nodes: env::var($ENV) does NOT match std::env::var("X"). Try both bare and fully-qualified forms, or use $$$ to absorb extra intermediate nodes.
  • To tell them apart: test the pattern on a snippet known to contain the code, and inspect how ast-grep parsed it with --debug-query=pattern (works for run, not just scan/rules). For zero matches from rules instead, follow the Step 4 debugging checklist.

Escaping in Inline Rules

When using --inline-rules, escape metavariables in shell commands:

  • Use \$VAR instead of $VAR (shell interprets $ as variable)
  • Or use single quotes: '$VAR' works in most shells

Example:

▼
bash
复制代码
# Correct: escaped $ ast-grep scan --inline-rules "rule: {pattern: 'console.log(\$ARG)'}" . # Or use single quotes ast-grep scan --inline-rules 'rule: {pattern: "console.log($ARG)"}' .

Common 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

Find 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

Find 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

Resources

references/

Contains detailed documentation for ast-grep rule syntax:

  • rule_reference.md: Comprehensive ast-grep rule documentation covering atomic rules, relational rules, composite rules, and metavariables

Load these references when detailed rule syntax information is needed.

快捷安装

复制到终端去安装 Skill

npxskillsaddhttps://github.com/ast-grep/agent-skill--skillast-grep
站长:程序员鱼皮 老鱼简历 商务合作 增值电信业务经营许可证
2026 鱼皮AI导航 | 沪ICP备19026706号-6
站长:程序员鱼皮 老鱼简历 商务合作 增值电信业务经营许可证
2026 鱼皮AI导航 | 沪ICP备19026706号-6
🔥热门工具
朱雀AI检测朱雀AI检测
朱雀AI检测助手朱雀AI检测助手
LovartLovart
老鱼简历老鱼简历
WritePass官网WritePass官网
面多多面多多
CursorCursor
星月写作星月写作
朱雀AI检测助手朱雀AI检测助手
零感AI零感AI
Skills 推荐
debug
debug 是一个系统化定位软件缺陷根因的技能,适用于用户报告 'fix'、'broken'、'error' 等问题或测试意外失败时。它通过可验证的假设、最小复现、因果链分析和回归测试,确保在修复前准确定位根本原因。
retrieving-developer-knowledge
retrieving-developer-knowledge 用于搜索、获取和整合 Google 官方开发者文档,覆盖 Google Cloud、AI/Gemini、Android、Chrome、Web、Flutter、Go、Firebase 等平台,适用于查询 gcloud CLI 命令、API 语法、IAM 权限或架构对比等场景。
diff-intake
diff-intake 读取 PR 或分支差异,生成结构化 YAML 变更摘要,用于下游 analytics instrumentation 技能。适用于用户提交 PR 链接、分支对比或原始 diff 后需理解变更内容、评估分析覆盖或启动埋点流程的场景。
lean-build
以极简方式构建高风险功能,强调架构一致性、范围严格控制与明确终止条件,通过复用现有接口、消除冗余逻辑、剔除非必要抽象与配置,实现端到端可验证的窄口径交付。
explore-run
面向深度学习研究的受控探索性实验,支持小样本验证、短周期训练探测、批量参数扫描、空闲 GPU 搜索及快速迁移学习试运行,在明确授权前提下生成带公平性说明与无夸大总结的边界化证据,输出结构化探索报告与候选运行排序。