PromptFrontendOpen

Ast-grep code analysis prompt

AST Code Analysis Superpower is a prompt for developers who review large or complex codebases. It has the AI use ast-grep pattern matching to find security, performance and structural issues by reading code structure rather than going line by line.

What it does

It targets security vulnerabilities, React hook dependency and performance patterns, and structural anti-patterns across many files. A decision tree sends simple code under about 50 lines to manual review and routes complex, nested or multi-file code to security, performance or structure patterns.

How to use it

Install ast-grep first with npm install -g @ast-grep/cli or mise, then set the target language, analysis focus, severity level, framework and maximum nesting depth. The defaults are JavaScript, security, ERROR, React and a depth of 3.

More in Frontend and the Business prompt library.

Full text

Front matter
name: AST Code Analysis Superpower
description: - 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-
kind: Prompt

AST Code Analysis Superpower


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

# 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

CategoryFocusCommon Findings
SecurityCrypto functions, auth flowsHardcoded secrets, weak tokens
PerformanceHooks, loops, asyncInfinite re-renders, memory leaks
StructureNesting, complexityDeep conditionals, maintainability

Essential Patterns

Security: Hardcoded Secrets

# 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

# 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

# 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

# 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

# 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

MistakeSymptomFix
Too generic patternsMany false positivesAdd context constraints
Missing insideMatches wrong locationsScope with parent context
No not clausesMatches valid patternsExclude known-good cases
JS patterns on TSType annotations break matchCreate 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

# 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

# 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

# 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

# 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

Contributor: [email removed]

Source and license

Source: https://github.com/f/prompts.chat/blob/main/prompts/00575.md

Author: f, prompts.chat prompt library. License: CC0-1.0.

Shown here with formatting for the web; email addresses removed. Keep the author and license notice when you reuse it.

Related entries

There are more like this in the members library

The Business prompt library holds 3,008 entries. Members can search all of them by meaning and read every one in full.