mcpField
A
ast-grep-code-analysis

ast-grep-code-analysis

github.com/zenobi-us测试与质量6860 次安装今天更新
代码仓库

关于 ast-grep-code-analysis

使用 ast-grep 结构模式查找跨文件代码问题的分析技能,指导安全、性能和代码结构审查,尤其适用于复杂或大型代码库。

主要功能

  1. 01使用 AST 模式匹配代码
  2. 02分析安全相关代码模式
  3. 03检查 React hook 等性能模式
  4. 04检测深层嵌套等结构问题
  5. 05运行规则集并生成 JSON 报告

适用场景

  1. 01在大型代码库中查找硬编码密钥
  2. 02检查 React 代码中的 hook 依赖模式
  3. 03跨文件查找深层嵌套的控制流

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/zenobi-us/dotfiles --skill ast-grep-code-analysis

安装后在 Claude Code 中输入/ast-grep-code-analysis确认已加载。

详细介绍

AST-Grep 代码分析

说明

此技能要求在开发环境中安装并配置 as-grep。如果尚未安装,我们可以使用 mise -g --pin ast-grep

概述

AST-Grep 代码分析使用抽象语法树模式匹配,系统地识别代码问题,以结构化模式识别取代逐行手动检查。

核心原则:代码结构揭示的信息多于表面阅读——AST 模式可以发现手动检查容易遗漏的隐藏关系、安全漏洞和架构问题。

使用时机

digraph when_to_use {
    "Need to analyze code?" [shape=diamond];
    "Complex/nested structure?" [shape=diamond];
    "Security review needed?" [shape=diamond];
    "Performance analysis?" [shape=diamond];
    "Use ast-grep patterns" [shape=box];
    "Manual review sufficient" [shape=box];

    "Need to analyze code?" -> "Complex/nested structure?" [label="yes"];
    "Complex/nested structure?" -> "Security review needed?" [label="yes"];
    "Security review needed?" -> "Performance analysis?" [label="yes"];
    "Performance analysis?" -> "Use ast-grep patterns" [label="yes"];
    "Complex/nested structure?" -> "Manual review sufficient" [label="no"];
    "Security review needed?" -> "Manual review sufficient" [label="no"];
    "Performance analysis?" -> "Manual review sufficient" [label="no"];
}

适用于:

  • 代码包含嵌套函数、复杂控制流或多个抽象层
  • 需要进行安全审查(身份验证、授权、数据处理)
  • 需要进行性能分析(React 钩子、循环、异步模式)
  • 代码库庞大,无法实际进行手动检查
  • 需要识别多个文件中的模式
  • 时间紧迫,需要采用系统化方法,而非临时分析

不适用于:

  • 简单、直观的代码(少于 50 行)
  • 结构清晰明了的单文件实用程序
  • 任务只需快速浏览即可完成时

核心模式

之前(手动检查):

// Agent manually reads line by line
if (data[i].admin) {
  userObj.token = generateToken(data[i].id); // "This looks insecure"
}

之后(AST 模式匹配):

# ast-grep rule: insecure-token-generation
rule:
  pattern: |
    function $FUNC($ARGS) {
      const secret = $SECRET;
      return btoa(JSON.stringify($PAYLOAD) + '.' + $SECRET);
    }
  meta:
    severity: ERROR
    message: "Hardcoded secret in token generation"

快速参考

分析类型AST 模式重点常见问题
安全加密函数中的字符串字面量硬编码密钥、加密强度不足
性能React 钩子依赖项无限次重新渲染、内存泄漏
结构函数嵌套深度控制流复杂、可维护性差
数据流变量赋值和使用情况未使用变量、隐式依赖

实施

安装和设置
# Install ast-grep
npm install -g @ast-grep/cli

# Initialize configuration
ast-grep init

# Create rules directory
mkdir -p sg-rules/security sg-rules/performance sg-rules/structure
基本安全模式

硬编码密钥检测:

# sg-rules/security/hardcoded-secrets.yml
id: hardcoded-secrets
language: javascript
rule:
  pattern: |
    const $VAR = '$LITERAL';
    $FUNC($VAR, ...)
  meta:
    severity: ERROR
    message: "Potential hardcoded secret detected"

不安全的令牌生成:

# sg-rules/security/insecure-tokens.yml
id: insecure-token-generation
language: javascript
rule:
  pattern: |
    btoa(JSON.stringify($OBJ) + '.' + $SECRET)
  meta:
    severity: ERROR
    message: "Insecure token generation using base64"
性能模式检测

React 钩子依赖项:

# sg-rules/performance/react-hook-deps.yml
id: react-hook-dependency-array
language: typescript
rule:
  pattern: |
    useEffect(() => {
      $BODY
    }, [$FUNC])
  meta:
    severity: WARNING
    message: "Function dependency in useEffect may cause infinite re-renders"

缺少 useCallback 优化:

# sg-rules/performance/missing-use-callback.yml
id: missing-use-callback
language: typescript
rule:
  pattern: |
    const $FUNC = ($ARGS) => {
      $BODY
    };
  inside:
    kind: function_declaration
    has:
      kind: arrow_function
  meta:
    severity: INFO
    message: "Consider wrapping function in useCallback for optimization"
结构分析模式

深层嵌套检测:

# sg-rules/structure/deep-nesting.yml
id: deep-nesting
language: javascript
rule:
  any:
    - pattern: |
        if ($COND1) {
          if ($COND2) {
            if ($COND3) {
              $BODY
            }
          }
        }
    - pattern: |
        for ($INIT) {
          for ($INIT2) {
            for ($INIT3) {
              $BODY
            }
          }
        }
  meta:
    severity: WARNING
    message: "Deep nesting detected - consider refactoring"
运行分析
# Run all security rules
ast-grep run -r sg-rules/security/

# Run performance analysis on React components
ast-grep run -r sg-rules/performance/ --include="*.tsx,*.jsx"

# Generate comprehensive report
ast-grep run -r sg-rules/ --format=json > analysis-report.json

# Interactive analysis
ast-grep run -r sg-rules/ --interactive

常见错误

错误原因修复方法
模式过于宽泛试图捕获所有情况聚焦于具体且影响重大的模式
缺少上下文模式未考虑周围代码使用 inside 和 has 约束
误报匹配范围过宽使用 not 添加否定约束
依赖特定语言的假设将 JavaScript 模式应用于 TypeScript为每种语言创建单独规则
未按严重程度排序将所有问题都标记为错误使用适当的严重级别

实际效果

AST 分析之前:

  • 手动代码审查:中型代码库需 2–3 小时
  • 漏掉的安全漏洞:40–60%
  • 不同审查者的分析结果不一致
  • 缺乏系统化的模式检测方法

AST 分析之后:

  • 自动模式检测:5–10 分钟
  • 安全漏洞检测率:90%+
  • 分析一致且可重复
  • 全面覆盖已知反模式

结果示例:

$ ast-grep run -r sg-rules/
src/components/UserProfile.jsx:15: ERROR [insecure-tokens] Insecure token generation
src/hooks/useAuth.js:8: ERROR [hardcoded-secrets] Potential hardcoded secret
src/components/UserProfile.jsx:23: WARNING [react-hook-deps] Function dependency may cause re-renders
src/utils/processData.js:45: WARNING [deep-nesting] Deep nesting detected

Found 4 issues (2 errors, 2 warnings)

集成工作流

  1. 设置:为安全、性能和结构创建规则集
  2. 建立基线:对现有代码库运行分析,以确定模式
  3. 迭代:根据误报和漏报优化规则
  4. 自动化:集成到 CI/CD 管道中,持续进行分析
  5. 监控:跟踪问题随时间的减少情况

所需背景知识:了解 AST 概念、模式匹配和代码结构分析。AST 模式能够揭示手动检查容易遗漏的问题——实现系统、全面且可重复的代码分析。

评论

支持 Markdown