# DooPourd - Verilog Parser & Circuit Diagram Generator

A comprehensive Python framework for parsing Verilog code and generating circuit diagrams (SVG/PNG).

**GitHub:** https://github.com/Dev-vesper/DooPourd  
**PyPI:** https://pypi.org/project/DooPourd/  
**License:** MIT

## Features

- ✅ **Verilog Parsing** - Parse Verilog modules into Abstract Syntax Trees (AST)
- ✅ **Lexical Analysis** - Tokenize Verilog with full support for keywords, identifiers, operators
- ✅ **Circuit Diagrams** - Generate SVG and PNG circuit diagrams from Verilog
- ✅ **AST Visualization** - Generate graphical representation of code structure
- ✅ **Logging System** - Built-in debugging with detailed logs
- ✅ **Command-Line Tool** - Use via CLI without coding
- ✅ **Cross-Platform** - Works on Windows, Linux, macOS

## Directory Structure

```
verilog_framework/
├── core/                      # Parser and Lexer components
│   ├── ast_nodes.py          # AST node definitions
│   ├── lexer.py              # Tokenization engine
│   └── parser.py             # Syntax parser
├── visualization/            # Graph and diagram generation
│   ├── visitor.py            # AST visitor pattern implementation
│   └── visualizer.py         # Graphviz-based visualization
├── verilogtoimage/          # Circuit diagram generation
│   ├── logger.py            # Logging utilities
│   ├── converters.py        # Yosys, netlistsvg, CairoSVG converters
│   └── pipeline.py          # Image generation pipeline
└── utils/                    # Utility functions
```

## Installation

### ⏃ Easiest: Using Docker (All platforms!)

**Windows, macOS, Linux - Works identically!**

```bash
git clone https://github.com/Dev-vesper/DooPourd.git
cd DooPourd
docker-compose up -d
docker-compose exec doopound bash
```

Everything (Yosys, netlistsvg, Python) pre-installed!

---

### 💻 Windows Only - No Docker Needed!

See [WINDOWS_SETUP.md](WINDOWS_SETUP.md) for complete Windows native setup.

```bash
# Quick:
pip install DooPourd[all]
# Then install Yosys from: https://github.com/YosysHQ/oss-cad-suite/releases
# And: npm install -g netlistsvg
```

---

### Basic Installation (Parsing Only - Lightweight!)

Works on **Windows, Linux, macOS** with just Python:

```bash
pip install DooPourd
```

**This includes:**
- ✅ Verilog parsing (lexer + parser)
- ✅ AST generation
- ✅ Port/declaration analysis

**No external dependencies required!**

### With Visualization (Optional)

To visualize code structure as graphs:

```bash
pip install DooPourd[graph]
```

### With Circuit Diagrams (Optional - Requires Linux/WSL)

To generate circuit diagrams (SVG/PNG):

```bash
pip install DooPourd[circuit]
```

Also requires Yosys and netlistsvg (Linux/WSL only):

```bash
# On Ubuntu/Debian WSL:
sudo apt-get install yosys netlistsvg

# Or use Docker:
docker run -it ubuntu:22.04 bash
apt-get update && apt-get install -y yosys npm
npm install -g netlistsvg
```

### All Features

```bash
pip install DooPourd[all]
```

### From source

```bash
git clone https://github.com/Dev-vesper/DooPourd.git
cd DooPourd
pip install -e .
```

## Quick Start

### ✅ Works Everywhere (Windows/Linux/macOS)

The first 3 examples work with basic installation on any OS:

```python
from verilog_framework.core import parse_verilog

# Your Verilog code
verilog_code = """
module adder(input a, input b, output sum);
    assign sum = a + b;
endmodule
"""

# Parse it
ast = parse_verilog(verilog_code)

# Get information
print(f"Module name: {ast.name}")
print(f"Number of ports: {len(ast.port_list)}")
print(f"Number of statements: {len(ast.statements)}")
```

### 2. Parse from File

```python
from pathlib import Path
from verilog_framework.core import parse_verilog

# Read Verilog file
code = Path("my_module.v").read_text()

# Parse
ast = parse_verilog(code)

print(f"Module: {ast.name}")
```

### 3. Get Port Information

```python
from verilog_framework.core import parse_verilog

code = """
module counter(
    input clk,
    input reset,
    output [7:0] count
);
    reg [7:0] count;
endmodule
"""

ast = parse_verilog(code)

# Get inputs
inputs = [p.name for p in ast.port_list if p.direction == 'input']
print(f"Inputs: {inputs}")

# Get outputs
outputs = [p.name for p in ast.port_list if p.direction == 'output']
print(f"Outputs: {outputs}")
```

**Output:**
```
Inputs: ['clk', 'reset']
Outputs: ['count']
```

---

### 🔧 Windows/Linux/macOS - Stop Here! ✅

**Above examples (1-3) work on any OS!** Continue with example 4 only if you have Linux/WSL.

---

### 4️⃣ Generate Circuit Diagram (Linux/WSL Only - Optional)

```python
from verilog_framework.verilogtoimage import VerilogToImagePipeline

code = """
module full_adder(
    input a,
    input b,
    input cin,
    output sum,
    output cout
);
    assign sum = a ^ b ^ cin;
    assign cout = (a & b) | (cin & (a ^ b));
endmodule
"""

# Create pipeline
pipeline = VerilogToImagePipeline()

# Generate SVG
svg_file = pipeline.verilog_to_svg(code, "adder.svg")
print(f"SVG saved: {svg_file}")

# Generate PNG (requires CairoSVG)
try:
    png_file = pipeline.verilog_to_png(code, "adder.png")
    print(f"PNG saved: {png_file}")
except Exception as e:
    print(f"PNG generation skipped: {str(e)[:60]}")
```

**Requires Linux/WSL:**
```bash
sudo apt-get install yosys netlistsvg
pip install DooPourd[circuit]
```

---

### 5️⃣ Visualize Code Structure (Optional)

```python
from verilog_framework.core import parse_verilog
from verilog_framework.visualization import GraphvizVisualizer

code = """
module test(input a, output b);
    assign b = a;
endmodule
"""

ast = parse_verilog(code)
visualizer = GraphvizVisualizer()
dot_code = visualizer.generate_dot(ast)

# Save to file
with open("structure.dot", "w") as f:
    f.write(dot_code)
    
print("Structure saved to structure.dot")

# Render to PNG (requires Graphviz installed)
try:
    import subprocess
    subprocess.run(["dot", "-Tpng", "structure.dot", "-o", "structure.png"])
    print("PNG rendered: structure.png")
except:
    print("Install Graphviz to render PNG")
```

**Optional (for rendering to PNG):**
```bash
# Ubuntu/WSL:
sudo apt-get install graphviz
# Or macOS:
brew install graphviz
```

---

## Windows Support ✅

**Good news:** DooPourd **core parsing works perfectly on Windows!**

| Feature | Windows | macOS | Linux |
|---------|---------|-------|-------|
| Parse Verilog | ✅ | ✅ | ✅ |
| Extract AST | ✅ | ✅ | ✅ |
| Analyze modules | ✅ | ✅ | ✅ |
| Graphviz visualization | ⚠️ Need graphviz | ✅ | ✅ |
| Circuit diagrams (PNG) | ⚠️ WSL only | ✅ | ✅ |

**Just install with:** `pip install DooPourd`

**No Yosys, no external tools needed!**

## Supported Verilog Features

| Feature | Supported |
|---------|-----------|
| Module declarations | ✅ |
| Ports (input/output/inout) | ✅ |
| Wire declarations | ✅ |
| Reg declarations | ✅ |
| Continuous assignments | ✅ |
| Always blocks | ✅ |
| Always @(posedge/negedge) | ✅ |
| Expressions (binary/unary) | ✅ |
| Comments | ✅ |
| Multi-line code | ✅ |

**Note:** Some advanced Verilog features (functions, tasks, generate blocks) are not yet supported.

## License

MIT
