AST Code Analysis Guide: Detect Vulnerabilities and Anti-patterns
Description
Advanced Code Analysis with AST-Grep
This tool is a comprehensive guide to using AST (Abstract Syntax Tree) for structural code analysis. Unlike traditional text search, this approach identifies complex logical errors and vulnerabilities by analyzing the actual structure of your project.
Who is this prompt for?
- Developers: For automating code review processes and identifying anti-patterns in large codebases.
- Security Specialists: For quickly finding hardcoded secrets, weak tokens, and vulnerable functions.
- DevOps Engineers: For implementing automated code quality checks in CI/CD pipelines.
Key Benefits
- Accuracy: Structural pattern recognition minimizes false positives.
- Ready-made Templates: Includes rules for React (hook dependencies), security, and deep nesting.
- Versatility: Supports JavaScript, TypeScript, and other languages supported by ast-grep.
>_ Prompt
---
name: ast-code-analysis-superpower
description: AST-based code pattern analysis using ast-grep for security, performance, and structural issues. Use when reviewing code for security vulnerabilities, analyzing framework-specific patterns, or detecting structural anti-patterns across large codebases.
---
# AST-Grep Code Analysis
AST pattern matching identifies code issues through structural recognition rather than line-by-line reading. Code structure reveals hidden relationships and vulnerabilities.
## 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
```
## Essential Patterns
### Security: Hardcoded Secrets
```yaml
id: hardcoded-secrets
language: ${language:javascript}
rule:
pattern: |
const $VAR = '$LITERAL';
$FUNC($VAR, ...)
meta:
severity: ${severity_level:ERROR}
message: "Potential hardcoded secret detected"
```
### Performance: ${framework:React} Hook Dependencies
```yaml
id: react-hook-dependency-array
language: typescript
rule:
pattern: |
useEffect(() => {
$BODY
}, [$FUNC])
meta:
severity: WARNING
message: "Function dependency may cause infinite re-renders"
```
## Running Analysis
```bash
# Security scan
ast-grep run -r sg-rules/security/
# Full scan with JSON output
ast-grep run -r sg-rules/ --format=json > analysis-report.json
```