OpenRuna
Sign in

AST Code Analysis Superpower

TEXT
Variables detected: ${language:javascript}${analysis_focus:security}${severity_level:ERROR}${framework:React}${max_nesting:3}${simple_code_lines:50}${sample_size:10}— replace before using.
Prompt6725 chars · 802 words
---
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
```

Overview

AST Code Analysis Superpower is a free prompt on OpenRuna. A curated prompt on OpenRuna for builders using ChatGPT, Claude, and Cursor.

What this prompt does

"AST Code Analysis Superpower" is designed to help you get reliable results from AI assistants for real prompt tasks. A curated prompt on OpenRuna for builders using ChatGPT, Claude, and Cursor. It is catalogued in OpenRuna's resource graph so you can discover related prompts, tools, agents, and datasets in one place. Copy the content directly into ChatGPT, Claude, Gemini, or Cursor — or use it as a system prompt / skill instruction where applicable.

Use cases

  • Use "AST Code Analysis Superpower" when you need a repeatable prompt for professional workflows without writing instructions from scratch each time.
  • Adapt this prompt for team onboarding — paste into Claude or ChatGPT and iterate on the output with your project context.
  • Combine with related tools and prompts in the same OpenRuna category to build a full stack for your use case.
  • Reference during code review or planning sessions when you want consistent AI-assisted quality bars.

Example output

When you run this prompt, expect structured output similar to:

---
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,…

Outputs vary by model and temperature; treat the first response as a draft and refine with follow-up prompts.

Tips by platform

Claude

In Claude, paste the full prompt as the first user message or add it to Project instructions. Ask Claude to confirm assumptions before executing. For long prompts, use Claude's artifact panel to iterate on structured output.

ChatGPT

In ChatGPT, start a new chat and paste this prompt verbatim. Enable GPT-4o or your preferred model for coding tasks. Use follow-ups like "apply this to [your context]" for best results.

Cursor

In Cursor, add key instructions from this prompt to .cursorrules or a SKILL.md file. Reference it in Agent mode with @ mentions. Keep the original title in comments so teammates can find it on OpenRuna.

Frequently asked questions

What is "AST Code Analysis Superpower"?
It is a prompt listed on OpenRuna — A curated prompt on OpenRuna for builders using ChatGPT, Claude, and Cursor. You can copy and adapt it for ChatGPT, Claude, Cursor, or other AI tools.
Is this prompt free to use?
Most OpenRuna resources are open or CC0-licensed. Check the license on this page before commercial use. Premium collections are clearly marked.
How do I get the best results?
Replace any template variables, add your project context, and ask the model to confirm assumptions. Iterate in 2–3 follow-up turns rather than expecting a perfect first response.
Can I use this with Claude and ChatGPT?
Yes. The prompt is model-agnostic text. Tips on this page cover Claude, ChatGPT, and Cursor specifically.
Where can I find related resources?
Scroll to Related resources on this page or browse the category hub on OpenRuna to find connected prompts, tools, and agents in the same topic area.

Related resources