代码结构扫描与问题定位
借助语法树模式匹配检查代码安全、性能与结构问题,提供扫描规则和验证步骤。
完整提示词
---
name: ast-code-analysis-superpower
description: 使用 ast-grep 进行基于 AST 的代码模式分析,用于安全、性能和结构问题。适用于以下情况:(1) 审查代码以查找安全漏洞,(2) 分析 React hook 依赖或性能模式,(3) 检测大型代码库中的结构反模式,(4) 需要超越手动检查的系统化模式匹配。
---
# AST-Grep Code Analysis
AST 模式匹配通过结构识别而非逐行阅读来发现代码问题。代码结构揭示了隐藏的关系、漏洞和反模式,这些是表面检查所无法发现的。
## Configuration
- **Target Language**: ${language:javascript}
- **Analysis Focus**: ${analysis_focus:security}
- **Severity Level**: ${severity_level:ERROR}
- **Framework**: ${framework:React}
- **Max Nesting Depth**: ${max_nesting:3}
## Prerequisites
```bash
# Install ast-grep (if not available)
npm install -g @ast-grep/cli
# Or: mise install -g ast-grep
```
## Decision Tree: When to Use AST Analysis
```
Code review needed?
|
+-- Simple code (<${simple_code_lines:50} lines, obvious structure) --> Manual review
|
+-- Complex code (nested, multi-file, abstraction layers)
|
+-- Security review required? --> Use security patterns
+-- Performance analysis? --> Use performance patterns
+-- Structural quality? --> Use structure patterns
+-- Cross-file patterns? --> Run with --include glob
```
## Pattern Categories
| Category | Focus | Common Findings |
|----------|-------|-----------------|
| Security | Crypto functions, auth flows | Hardcoded secrets, weak tokens |
| Performance | Hooks, loops, async | Infinite re-renders, memory leaks |
| Structure | Nesting, complexity | Deep conditionals, maintainability |
## Essential Patterns
### Security: Hardcoded Secrets
```yaml
# sg-rules/security/hardcoded-secrets.yml
id: hardcoded-secrets
language: ${language:javascript}
rule:
pattern: |
const $VAR = '$LITERAL';
$FUNC($VAR, ...)
meta:
severity: ${severity_level:ERROR}
message: "Potential hardcoded secret detected"
```
### Security: Insecure Token Generation
```yaml
# sg-rules/security/insecure-tokens.yml
id: insecure-token-generation
language: ${language:javascript}
rule:
pattern: |
btoa(JSON.stringify($OBJ) + '.' + $SECRET)
meta:
severity: ${severity_level:ERROR}
message: "Insecure token generation using base64"
```
### Performance: ${framework:React} Hook Dependencies
```yaml
# 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 may cause infinite re-renders"
```
### Structure: Deep Nesting
```yaml
# sg-rules/structure/deep-nesting.yml
id: deep-nesting
language: ${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 (>${max_nesting:3} levels) - consider refactoring"
```
## Running Analysis
```bash
# Security scan
ast-grep run -r sg-rules/security/
# Performance scan on ${framework:React} files
ast-grep run -r sg-rules/performance/ --include="*.tsx,*.jsx"
# Full scan with JSON output
ast-grep run -r sg-rules/ --format=json > analysis-report.json
# Interactive mode for investigation
ast-grep run -r sg-rules/ --interactive
```
## Pattern Writing Checklist
- [ ] Pattern matches specific anti-pattern, not general code
- [ ] Uses `inside` or `has` for context constraints
- [ ] Includes `not` constraints to reduce false positives
- [ ] Separate rules per language (JS vs TS)
- [ ] Appropriate severity (${severity_level:ERROR}/WARNING/INFO)
## Common Mistakes
| Mistake | Symptom | Fix |
|---------|---------|-----|
| Too generic patterns | Many false positives | Add context constraints |
| Missing `inside` | Matches wrong locations | Scope with parent context |
| No `not` clauses | Matches valid patterns | Exclude known-good cases |
| JS patterns on TS | Type annotations break match | Create language-specific rules |
## Verification Steps
1. **Test pattern accuracy**: Run on known-vulnerable code samples
2. **Check false positive rate**: Review first ${sample_size:10} matches manually
3. **Validate severity**: Confirm ${severity_level:ERROR}-level findings are actionable
4. **Cross-file coverage**: Verify pattern runs across intended scope
## Example Output
```
$ ast-grep run -r sg-rules/
src/components/UserProfile.jsx:15: ${severity_level:ERROR} [insecure-tokens] Insecure token generation
src/hooks/useAuth.js:8: ${severity_level:ERROR} [hardcoded-secrets] Potential hardcoded secret
```
src/components/Dashboard.tsx:23: WARNING [react-hook-deps] Function dependency
src/utils/processData.js:45: WARNING [deep-nesting] Deep nesting detected
发现 4 个问题(2 个错误,2 个警告)
```
## 项目设置
```bash
# 在项目中初始化 ast-grep
ast-grep init
# 创建规则目录
mkdir -p sg-rules/{security,performance,structure}
# 添加到 CI 流水线
# .github/workflows/lint.yml
# - run: ast-grep run -r sg-rules/ --format=json
```
## 自定义模式模板
### ${framework:React} 特定模式
```yaml
# 列表渲染中缺少 key
id: missing-list-key
language: typescript
rule:
pattern: |
$ARRAY.map(($ITEM) => <$COMPONENT $$$PROPS />)
constraints:
$PROPS:
not:
has:
pattern: 'key={$_}'
meta:
severity: WARNING
message: "列表渲染中缺少 key prop"
```
### Async/Await 模式
```yaml
# async 中缺少错误处理
id: unhandled-async
language: ${language:javascript}
rule:
pattern: |
async function $NAME($$$) {
$$$BODY
}
constraints:
$BODY:
not:
has:
pattern: 'try { $$$ } catch'
meta:
severity: WARNING
message: "缺少 try-catch 错误处理的 async 函数"
```
## 与 CI/CD 集成
```yaml
# GitHub Actions 示例
name: AST 分析
on: [push, pull_request]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: 安装 ast-grep
run: npm install -g @ast-grep/cli
- name: 运行分析
run: |
ast-grep run -r sg-rules/ --format=json > report.json
if grep -q '"severity": "${severity_level:ERROR}"' report.json; then
echo "发现严重问题!"
exit 1
fi
```可替换内容
- [$FUNC]
- [ ]
- [insecure-tokens]
- [hardcoded-secrets]
- [react-hook-deps]
- [deep-nesting]
- [push, pull_request]
分类与标签
编程开发、代码审查、静态分析、安全扫描、持续集成