1
---
2
name: ast-code-analysis-superpower
3
description: AST-based code pattern analysis using ast-grep for security, performance, and structural issues. Use when (1) reviewing code for security vulnerabilities, (2) analyzing React hook dependencies or performance patterns, (3) detecting structural anti-patterns across large codebases, (4) needing systematic pattern matching beyond manual inspection.
4
---
5
6
# AST-Grep Code Analysis
7
8
AST pattern matching identifies code issues through structural recognition rather than line-by-line reading. Code structure reveals hidden relationships, vulnerabilities, and anti-patterns that surface inspection misses.
9
10
## Configuration
11
12
- **Target Language**: ${language:javascript}
13
- **Analysis Focus**: ${analysis_focus:security}
14
- **Severity Level**: ${severity_level:ERROR}
15
- **Framework**: ${framework:React}
16
- **Max Nesting Depth**: ${max_nesting:3}
17
18
## Prerequisites
19
20
```bash
21
# Install ast-grep (if not available)
22
npm install -g @ast-grep/cli
23
# Or: mise install -g ast-grep
24
```
25
26
## Decision Tree: When to Use AST Analysis
27
28
```
29
Code review needed?
30
|
31
+-- Simple code (<${simple_code_lines:50} lines, obvious structure) --> Manual review
32
|
33
+-- Complex code (nested, multi-file, abstraction layers)
34
|
35
+-- Security review required? --> Use security patterns
36
+-- Performance analysis? --> Use performance patterns
37
+-- Structural quality? --> Use structure patterns
38
+-- Cross-file patterns? --> Run with --include glob
39
```
40
41
## Pattern Categories
42
43
| Category | Focus | Common Findings |
44
|----------|-------|-----------------|
45
| Security | Crypto functions, auth flows | Hardcoded secrets, weak tokens |
46
| Performance | Hooks, loops, async | Infinite re-renders, memory leaks |
47
| Structure | Nesting, complexity | Deep conditionals, maintainability |
48
49
## Essential Patterns
50
51
### Security: Hardcoded Secrets
52
53
```yaml
54
# sg-rules/security/hardcoded-secrets.yml
55
id: hardcoded-secrets
56
language: ${language:javascript}
57
rule:
58
pattern: |
59
const $VAR = '$LITERAL';
60
$FUNC($VAR, ...)
61
meta:
62
severity: ${severity_level:ERROR}
63
message: "Potential hardcoded secret detected"
64
```
65
66
### Security: Insecure Token Generation
67
68
```yaml
69
# sg-rules/security/insecure-tokens.yml
70
id: insecure-token-generation
71
language: ${language:javascript}
72
rule:
73
pattern: |
74
btoa(JSON.stringify($OBJ) + '.' + $SECRET)
75
meta:
76
severity: ${severity_level:ERROR}
77
message: "Insecure token generation using base64"
78
```
79
80
### Performance: ${framework:React} Hook Dependencies
81
82
```yaml
83
# sg-rules/performance/react-hook-deps.yml
84
id: react-hook-dependency-array
85
language: typescript
86
rule:
87
pattern: |
88
useEffect(() => {
89
$BODY
90
}, [$FUNC])
91
meta:
92
severity: WARNING
93
message: "Function dependency may cause infinite re-renders"
94
```
95
96
### Structure: Deep Nesting
97
98
```yaml
99
# sg-rules/structure/deep-nesting.yml
100
id: deep-nesting
101
language: ${language:javascript}
102
rule:
103
any:
104
- pattern: |
105
if ($COND1) {
106
if ($COND2) {
107
if ($COND3) {
108
$BODY
109
}
110
}
111
}
112
- pattern: |
113
for ($INIT) {
114
for ($INIT2) {
115
for ($INIT3) {
116
$BODY
117
}
118
}
119
}
120
meta:
121
severity: WARNING
122
message: "Deep nesting (>${max_nesting:3} levels) - consider refactoring"
123
```
124
125
## Running Analysis
126
127
```bash
128
# Security scan
129
ast-grep run -r sg-rules/security/
130
131
# Performance scan on ${framework:React} files
132
ast-grep run -r sg-rules/performance/ --include="*.tsx,*.jsx"
133
134
# Full scan with JSON output
135
ast-grep run -r sg-rules/ --format=json > analysis-report.json
136
137
# Interactive mode for investigation
138
ast-grep run -r sg-rules/ --interactive
139
```
140
141
## Pattern Writing Checklist
142
143
- [ ] Pattern matches specific anti-pattern, not general code
144
- [ ] Uses `inside` or `has` for context constraints
145
- [ ] Includes `not` constraints to reduce false positives
146
- [ ] Separate rules per language (JS vs TS)
147
- [ ] Appropriate severity (${severity_level:ERROR}/WARNING/INFO)
148
149
## Common Mistakes
150
151
| Mistake | Symptom | Fix |
152
|---------|---------|-----|
153
| Too generic patterns | Many false positives | Add context constraints |
154
| Missing `inside` | Matches wrong locations | Scope with parent context |
155
| No `not` clauses | Matches valid patterns | Exclude known-good cases |
156
| JS patterns on TS | Type annotations break match | Create language-specific rules |
157
158
## Verification Steps
159
160
1. **Test pattern accuracy**: Run on known-vulnerable code samples
161
2. **Check false positive rate**: Review first ${sample_size:10} matches manually
162
3. **Validate severity**: Confirm ${severity_level:ERROR}-level findings are actionable
163
4. **Cross-file coverage**: Verify pattern runs across intended scope
164
165
## Example Output
166
167
```
168
$ ast-grep run -r sg-rules/
169
src/components/UserProfile.jsx:15: ${severity_level:ERROR} [insecure-tokens] Insecure token generation
170
src/hooks/useAuth.js:8: ${severity_level:ERROR} [hardcoded-secrets] Potential hardcoded secret
171
src/components/Dashboard.tsx:23: WARNING [react-hook-deps] Function dependency
172
src/utils/processData.js:45: WARNING [deep-nesting] Deep nesting detected
173
174
Found 4 issues (2 errors, 2 warnings)
175
```
176
177
## Project Setup
178
179
```bash
180
# Initialize ast-grep in project
181
ast-grep init
182
183
# Create rule directories
184
mkdir -p sg-rules/{security,performance,structure}
185
186
# Add to CI pipeline
187
# .github/workflows/lint.yml
188
# - run: ast-grep run -r sg-rules/ --format=json
189
```
190
191
## Custom Pattern Templates
192
193
### ${framework:React} Specific Patterns
194
195
```yaml
196
# Missing key in list rendering
197
id: missing-list-key
198
language: typescript
199
rule:
200
pattern: |
201
$ARRAY.map(($ITEM) => <$COMPONENT $$$PROPS />)
202
constraints:
203
$PROPS:
204
not:
205
has:
206
pattern: 'key={$_}'
207
meta:
208
severity: WARNING
209
message: "Missing key prop in list rendering"
210
```
211
212
### Async/Await Patterns
213
214
```yaml
215
# Missing error handling in async
216
id: unhandled-async
217
language: ${language:javascript}
218
rule:
219
pattern: |
220
async function $NAME($$$) {
221
$$$BODY
222
}
223
constraints:
224
$BODY:
225
not:
226
has:
227
pattern: 'try { $$$ } catch'
228
meta:
229
severity: WARNING
230
message: "Async function without try-catch error handling"
231
```
232
233
## Integration with CI/CD
234
235
```yaml
236
# GitHub Actions example
237
name: AST Analysis
238
on: [push, pull_request]
239
jobs:
240
analyze:
241
runs-on: ubuntu-latest
242
steps:
243
- uses: actions/checkout@v4
244
- name: Install ast-grep
245
run: npm install -g @ast-grep/cli
246
- name: Run analysis
247
run: |
248
ast-grep run -r sg-rules/ --format=json > report.json
249
if grep -q '"severity": "${severity_level:ERROR}"' report.json; then
250
echo "Critical issues found!"
251
exit 1
252
fi
253
```