---
name: analyze-ast
description: Analyze code structure using AST parsing for Python, C++, and MFC
---

# AST Code Analysis Skill

## Description

This skill provides deep code analysis using Abstract Syntax Tree (AST) parsing. It supports Python, C++, and MFC (Microsoft Foundation Classes) codebases, extracting symbols, understanding code structure, and enabling safe refactoring operations.

## When to Use

- When you need to understand the structure of a codebase
- When looking for function definitions, classes, or methods
- When refactoring code (rename symbols, extract functions)
- When analyzing MFC message maps and handlers
- When you need to find all references to a symbol

## Supported Languages

| Language | Parser | Features |
|----------|--------|----------|
| Python | Built-in `ast` module | Functions, classes, methods, decorators, type hints |
| C++ | Tree-sitter (or regex fallback) | Functions, classes, structs, enums, namespaces |
| MFC | Extended C++ parser | Message maps, handlers, dialog classes, DDX/DDV |

## Commands

```
/analyze-ast <file>           # Analyze a single file
/analyze-ast --symbols        # List all symbols in current file
/analyze-ast --find <name>    # Find symbol definition
/analyze-ast --refs <name>    # Find all references to a symbol
/analyze-ast --rename <old> <new>  # Preview rename operation
```

## How to Use

### Step 1: Analyze File Structure

Parse a file to understand its structure:

```
Analyze the structure of src/main.py
```

This will extract:
- All function and method definitions
- Class definitions with base classes
- Variable assignments
- Import statements
- Decorators and type hints

### Step 2: Find Symbols

Search for specific symbols:

```
Find the definition of UserService class
Find all functions in utils.py
```

### Step 3: Find References

Locate all usages of a symbol:

```
Find all references to process_data function
Where is Config class used?
```

### Step 4: Refactoring

Perform safe refactoring operations:

```
Rename function old_name to new_name
Extract lines 50-60 into a new function called calculate_total
```

## Symbol Types

### Python Symbols
- `function` - Regular functions
- `async_function` - Async functions
- `method` - Class methods
- `class` - Class definitions
- `variable` - Module-level variables
- `decorator` - Decorator definitions

### C++ Symbols
- `function` - Free functions
- `method` - Class member functions
- `class` - Class definitions
- `struct` - Struct definitions
- `enum` - Enum definitions
- `namespace` - Namespace definitions
- `macro` - Preprocessor macros

### MFC-Specific Symbols
- `message_handler` - Message handler functions
- `message_map` - BEGIN_MESSAGE_MAP blocks
- `dialog_class` - CDialog-derived classes
- `view_class` - CView-derived classes
- `document_class` - CDocument-derived classes

## MFC Analysis Features

### Message Map Parsing

The analyzer understands MFC message maps:

```cpp
BEGIN_MESSAGE_MAP(CMyDialog, CDialogEx)
    ON_BN_CLICKED(IDC_BUTTON1, &CMyDialog::OnBnClickedButton1)
    ON_WM_PAINT()
    ON_WM_TIMER()
END_MESSAGE_MAP()
```

Extracts:
- Handler function names
- Associated control IDs
- Windows message types

### Class Hierarchy

Recognizes MFC base classes:
- CWinApp, CFrameWnd, CMDIFrameWnd
- CDialog, CDialogEx, CPropertyPage
- CView, CScrollView, CFormView
- CDocument, CWnd
- Control classes (CButton, CEdit, CListCtrl, etc.)

## Output Format

Analysis results include:

```json
{
  "file_path": "src/main.py",
  "language": "python",
  "symbols": [
    {
      "name": "process_data",
      "type": "function",
      "line": 42,
      "signature": "def process_data(items: list[Item]) -> Result",
      "docstring": "Process a list of items and return result."
    }
  ],
  "references": [...],
  "imports": [...]
}
```

## Best Practices

1. **Start with Structure**: Analyze file structure before making changes
2. **Check References**: Always check references before renaming
3. **Review Edits**: Preview refactoring changes before applying
4. **Use Type Hints**: Python type hints improve analysis accuracy
5. **Keep Code Parseable**: Ensure code compiles/runs for accurate AST

## Examples

### Example 1: Understanding a Python Module

**User Request:** "What functions are in utils/helpers.py?"

**Approach:**
1. Parse the file with Python AST parser
2. Extract all function symbols
3. Show name, signature, and docstring for each

### Example 2: MFC Message Handler Analysis

**User Request:** "What message handlers does CMainFrame have?"

**Approach:**
1. Parse with MFC parser
2. Find BEGIN_MESSAGE_MAP for CMainFrame
3. Extract all handlers with their message types
4. Show the handler list with associated messages

### Example 3: Safe Rename Refactoring

**User Request:** "Rename get_data to fetch_data across the project"

**Approach:**
1. Find symbol definition for get_data
2. Search all project files for references
3. Generate edit list for all occurrences
4. Preview changes before applying
5. Apply edits on confirmation

## Notes

- Tree-sitter provides better C++ parsing when installed
- Regex fallback works for most common patterns
- MFC parsing requires typical MFC header patterns
- Analysis caches results for performance
- Invalid syntax may cause partial analysis
