developer coding template risk: medium
AST-Grep Code Analysis Superpower
Provides configuration, patterns, and instructions for using ast-grep to perform AST-based analysis on JavaScript and React code for security vulnerabilities, performance issues, a…
- Policy sensitive
- Human review
PROMPT
---
name: ast-code-analysis-superpower
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.
---
# AST-Grep Code Analysis
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.
## 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
Found 4 issues (2 errors, 2 warnings)
```
## Project Setup
```bash
# Initialize ast-grep in project
ast-grep init
# Create rule directories
mkdir -p sg-rules/{security,performance,structure}
# Add to CI pipeline
# .github/workflows/lint.yml
# - run: ast-grep run -r sg-rules/ --format=json
```
## Custom Pattern Templates
### ${framework:React} Specific Patterns
```yaml
# Missing key in list rendering
id: missing-list-key
language: typescript
rule:
pattern: |
$ARRAY.map(($ITEM) => <$COMPONENT $$$PROPS />)
constraints:
$PROPS:
not:
has:
pattern: 'key={$_}'
meta:
severity: WARNING
message: "Missing key prop in list rendering"
```
### Async/Await Patterns
```yaml
# Missing error handling in async
id: unhandled-async
language: ${language:javascript}
rule:
pattern: |
async function $NAME($$$) {
$$$BODY
}
constraints:
$BODY:
not:
has:
pattern: 'try { $$$ } catch'
meta:
severity: WARNING
message: "Async function without try-catch error handling"
```
## Integration with CI/CD
```yaml
# GitHub Actions example
name: AST Analysis
on: [push, pull_request]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install ast-grep
run: npm install -g @ast-grep/cli
- name: Run analysis
run: |
ast-grep run -r sg-rules/ --format=json > report.json
if grep -q '"severity": "${severity_level:ERROR}"' report.json; then
echo "Critical issues found!"
exit 1
fi
``` INPUTS
- language
-
Target programming language
e.g. javascript
- analysis_focus
-
Focus area like security or performance
e.g. security
- severity_level
-
Severity threshold like ERROR or WARNING
e.g. ERROR
- framework
-
Framework like React
e.g. React
- max_nesting
-
Maximum nesting depth for analysis
e.g. 3
- simple_code_lines
-
Line threshold for simple code
e.g. 50
- sample_size
-
Number of matches for manual review
e.g. 10
REQUIRED CONTEXT
- code snippet or codebase
OPTIONAL CONTEXT
- target language
- analysis focus
- severity level
- framework
- max nesting depth
ROLES & RULES
- 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 (ERROR/WARNING/INFO)
EXPECTED OUTPUT
- Format
- structured_report
- Constraints
-
- include severity
- example output format with file:line: severity [rule] message
SUCCESS CRITERIA
- Test pattern accuracy
- Check false positive rate
- Validate severity
- Verify cross-file coverage
FAILURE MODES
- Too generic patterns cause many false positives
- Missing `inside` matches wrong locations
- No `not` clauses matches valid patterns
- JS patterns on TS due to type annotations
EXAMPLES
Includes multiple YAML examples of ast-grep rules for security, performance, structure, React-specific patterns, and an example console output.
CAVEATS
- Dependencies
-
- ast-grep CLI installed
- Rule directories like sg-rules/{security,performance,structure}
- Target codebase or files
- Configuration variables like language, analysis_focus, severity_level, framework, max_nesting
- Missing context
-
- Path to the target codebase or file globs
- Custom rule modifications for specific projects
QUALITY
- OVERALL
- 0.92
- CLARITY
- 0.95
- SPECIFICITY
- 0.90
- REUSABILITY
- 0.95
- COMPLETENESS
- 0.90
IMPROVEMENT SUGGESTIONS
- Standardize placeholder substitution method, e.g., 'Use a .env file or sed replacement for ${vars}'
- Add more diverse patterns for non-React frameworks like Vue or Angular
- Include a troubleshooting section for ast-grep installation and execution errors
USAGE
Copy the prompt above and paste it into your AI of choice — Claude, ChatGPT, Gemini, or anywhere else you're working. Replace any placeholder sections with your own context, then ask for the output.
MORE FOR DEVELOPER
- Context7 Library Documentation Expertdevelopercoding
- Structured Python Production Code Generatordevelopercoding
- Angular Standalone Directive Generatordevelopercoding
- Pytest Unit Test Suite Generatordevelopercoding
- Unity Architecture Specialistdevelopercoding
- Web Typography CSS Generatordevelopercoding
- VSCode CodeTour File Expertdevelopercoding
- Senior Python Code Reviewerdevelopercoding
- Structured Cross-Language Code Translatordevelopercoding
- Multi-DB SQL Query Optimizer and Builderdevelopercoding