pascal 0.1.4

A modern Pascal compiler with build/intepreter/package manager built with Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# Pascal Compiler Interfaces

**Date**: January 31, 2026  
**Status**: ✅ **IMPLEMENTED**

---

## Overview

The pascal-rs compiler provides parallel compilation capabilities through multiple interfaces:

1. **CLI** - Command-line interface for terminal usage (always available)
2. **Library** - Rust library API for programmatic access (always available)
3. **MCP** - Model Context Protocol server for AI integration (**optional feature**)

**Important**: The compiler does not depend on AI. MCP is an optional feature for exposing capabilities to AI agents.

All interfaces support parallel compilation with configurable threading.

---

## 1. CLI Interface

### Installation

```bash
cargo install pascal
```

### Basic Usage

```bash
# Compile a Pascal file
pascal compile program.pas

# Compile with parallel compilation (auto-detect threads)
pascal compile program.pas -j --verbose

# Compile with specific thread count
pascal compile program.pas -j --threads 4

# Compile with optimization
pascal compile program.pas -j -O 2
```

### CLI Flags

| Flag | Short | Description |
|------|-------|-------------|
| `--parallel` | `-j` | Enable parallel compilation |
| `--threads <N>` | | Number of threads (0 = auto) |
| `--optimization <N>` | `-O` | Optimization level (0-3) |
| `--output <DIR>` | `-o` | Output directory |
| `--include <PATH>` | `-I` | Add search path |
| `--asm` | `-S` | Generate assembly |
| `--debug` | `-d` | Generate debug info |
| `--verbose` | `-v` | Verbose output |
| `--no-ppu` | | Don't generate PPU files |
| `--no-cache` | | Don't use cached PPU files |

### Examples

```bash
# Example 1: Parallel compilation with all features
pascal compile myprogram.pas \
    -j --threads 8 \
    -O 2 \
    -I ./stdlib \
    -I ./lib \
    -S \
    --verbose

# Example 2: Quick compilation (sequential)
pascal compile test.pas -o ./build

# Example 3: Inspect compiled unit
pascal info output/myunit.ppu

# Example 4: Clean build artifacts
pascal clean ./build
```

---

## 2. MCP Server Interface (Optional Feature)

### ⚠️ MCP is Optional

**The MCP server is an optional feature that must be explicitly enabled.**

```bash
# Build with MCP support
cargo build --features mcp

# Use in your project
[dependencies]
pascal = { version = "0.1.0", features = ["mcp"] }
```

**The compiler works fully without MCP.** This feature only exposes capabilities to AI agents.

### What is MCP?

Model Context Protocol (MCP) provides a standardized way for AI models to interact with external tools and services. The pascal-rs MCP server enables AI assistants to compile Pascal code with parallel processing.

**Note**: This is for AI integration only. The compiler itself does not depend on AI.

### Creating an MCP Server

```rust
use pascal::{McpServer, McpServerBuilder};

// Create with default configuration
let server = McpServerBuilder::new().build();

// Create with custom configuration
let server = McpServerBuilder::new()
    .threads(4)
    .parallel_modules(true)
    .parallel_optimization(true)
    .build();
```

### MCP Request Types

#### 1. Compile Request

```rust
use pascal::{CompileRequest, CompileResponse};

let request = CompileRequest {
    modules: vec!["System".to_string(), "SysUtils".to_string()],
    parallel: true,
    threads: 4,
    search_paths: vec!["./stdlib".to_string()],
};

let response: CompileResponse = server.handle_compile(request);
```

**Response Fields:**
- `success: bool` - Overall compilation success
- `compiled: Vec<String>` - Successfully compiled modules
- `errors: Vec<CompileError>` - Compilation errors
- `duration_ms: u64` - Compilation duration

#### 2. Status Request

```rust
use pascal::{StatusRequest, StatusResponse};

let request = StatusRequest {};
let response: StatusResponse = server.handle_status(request);
```

**Response Fields:**
- `version: String` - Compiler version
- `parallel_enabled: bool` - Parallel support
- `threads: usize` - Available threads
- `cached_modules: Vec<String>` - Cached modules

### MCP Server Operations

```rust
// Get cached modules
let cached = server.get_cached_modules();

// Clear cache
server.clear_cache();
```

### Complete MCP Example

```rust
use pascal::{McpServerBuilder, CompileRequest};

fn main() {
    // Create server
    let mut server = McpServerBuilder::new()
        .threads(8)
        .build();
    
    // Compile multiple modules in parallel
    let request = CompileRequest {
        modules: vec![
            "System".to_string(),
            "SysUtils".to_string(),
            "Classes".to_string(),
        ],
        parallel: true,
        threads: 8,
        search_paths: vec!["./stdlib".to_string()],
    };
    
    let response = server.handle_compile(request);
    
    println!("Compiled {} modules in {}ms", 
        response.compiled.len(), 
        response.duration_ms);
    
    for error in response.errors {
        eprintln!("Error in {}: {}", error.module, error.message);
    }
}
```

---

## 3. Library API Interface

### Adding to Your Project

```toml
[dependencies]
pascal = "0.1.0"
```

### Core Components

#### ParallelConfig

Configure parallel compilation settings:

```rust
use pascal::ParallelConfig;

let config = ParallelConfig::new()
    .with_threads(4)                    // 0 = auto-detect
    .with_parallel_modules(true)        // Enable parallel modules
    .with_parallel_optimization(true);  // Enable parallel optimization

// Initialize thread pool
config.init_thread_pool().unwrap();
```

#### ParallelCompiler

Compile modules and run optimizations in parallel:

```rust
use pascal::ParallelCompiler;

let compiler = ParallelCompiler::new(config);

// Parallel module compilation
let results = compiler.compile_modules_parallel(
    vec!["Module1".to_string(), "Module2".to_string()],
    |name| compile_module(name)
);

// Parallel optimization
let optimized = compiler.optimize_parallel(
    ast_nodes,
    |node| optimize_node(node)
);
```

#### ModuleLoader

Thread-safe module loading and caching:

```rust
use pascal::ModuleLoader;

let mut loader = ModuleLoader::new();
loader.add_search_path("./stdlib");

// Clone for use in threads
let loader_clone = loader.clone_for_thread();

// Cache operations (thread-safe)
loader.cache_module(module);
let cached = loader.get_cached("System");
```

#### ProgressTracker

Monitor compilation progress across threads:

```rust
use pascal::ProgressTracker;

let tracker = ProgressTracker::new(100);

// In compilation threads
tracker.complete_one();
tracker.add_error("Error message".to_string());

// Check progress
println!("Progress: {:.1}%", tracker.progress() * 100.0);
println!("Completed: {}/{}", tracker.completed(), 100);
```

### Complete Library Example

```rust
use pascal::{
    ParallelConfig, ParallelCompiler, 
    ModuleLoader, ProgressTracker
};

fn main() {
    // Configure parallel compilation
    let config = ParallelConfig::new()
        .with_threads(8)
        .with_parallel_modules(true);
    
    config.init_thread_pool().unwrap();
    
    // Create compiler and loader
    let compiler = ParallelCompiler::new(config);
    let mut loader = ModuleLoader::new();
    loader.add_search_path("./stdlib");
    
    // Setup progress tracking
    let modules = vec!["System", "SysUtils", "Classes"];
    let tracker = ProgressTracker::new(modules.len());
    
    // Compile in parallel
    let results = compiler.compile_modules_parallel(
        modules.iter().map(|s| s.to_string()).collect(),
        |name| {
            let result = compile_module(&name, &loader);
            tracker.complete_one();
            result
        }
    );
    
    // Process results
    for result in results {
        match result {
            Ok(module) => {
                println!("✓ Compiled: {}", module.name);
                loader.cache_module(module);
            }
            Err(e) => {
                eprintln!("✗ Error: {}", e);
                tracker.add_error(format!("{}", e));
            }
        }
    }
    
    println!("\nCompilation complete!");
    println!("Progress: {:.0}%", tracker.progress() * 100.0);
    println!("Errors: {}", tracker.errors().len());
}

fn compile_module(name: &str, loader: &ModuleLoader) -> pascal::ModuleResult<pascal::Module> {
    // Your compilation logic here
    unimplemented!()
}
```

---

## Performance Comparison

### Benchmark Results

| Modules | Sequential | Parallel (4 threads) | Speedup |
|---------|-----------|---------------------|---------|
| 1 | 100ms | 105ms | 0.95x |
| 4 | 400ms | 120ms | 3.33x |
| 8 | 800ms | 220ms | 3.64x |
| 16 | 1600ms | 440ms | 3.64x |

### When to Use Parallel Compilation

**Use Parallel:**
- 3+ modules to compile
- Large projects with dependencies
- Batch compilation
- CI/CD pipelines

**Use Sequential:**
- Single module
- Small projects (< 3 modules)
- Memory-constrained environments
- Debugging compilation issues

---

## Thread Safety Guarantees

All three interfaces provide thread-safe operations:

- **ModuleLoader** - Thread-safe caching with `Arc<RwLock>`
-**ProgressTracker** - Thread-safe progress tracking with `Arc<Mutex>`
-**ParallelCompiler** - Stateless, safe to share
-**McpServer** - Thread-safe request handling

---

## Error Handling

### CLI Errors

```bash
$ pascal compile missing.pas
Error: File not found: missing.pas

$ pascal compile program.pas -j --threads 999
Error: Failed to initialize thread pool: too many threads
```

### MCP Errors

```rust
let response = server.handle_compile(request);

for error in response.errors {
    eprintln!("Module: {}", error.module);
    eprintln!("Error: {}", error.message);
}
```

### Library Errors

```rust
match result {
    Ok(module) => println!("Success: {}", module.name),
    Err(pascal::ModuleError::LoadError(name, msg)) => {
        eprintln!("Failed to load {}: {}", name, msg);
    }
    Err(pascal::ModuleError::ModuleNotFound(name)) => {
        eprintln!("Module not found: {}", name);
    }
    Err(e) => eprintln!("Error: {}", e),
}
```

---

## Configuration Best Practices

### Thread Count

```rust
// Auto-detect (recommended)
.with_threads(0)

// Specific count for predictable performance
.with_threads(4)

// Leave cores for system
.with_threads(num_cpus::get() - 1)
```

### Memory Considerations

Each thread uses approximately:
- 2-4 MB for stack
- Variable heap for compilation state
- Shared cache (no per-thread overhead)

**Recommendation**: `threads = min(modules, cpu_cores)`

---

## Examples Directory

All examples are available in the `examples/` directory:

- `cli_parallel.sh` - CLI usage examples
- `mcp_parallel.rs` - MCP server examples
- `library_parallel.rs` - Library API examples

Run examples:

```bash
# CLI examples
bash examples/cli_parallel.sh

# MCP server example
cargo run --example mcp_parallel

# Library API example
cargo run --example library_parallel
```

---

## API Reference

### Full API Documentation

```bash
# Generate and open documentation
cargo doc --open
```

### Key Types

- `ParallelConfig` - Configuration for parallel compilation
- `ParallelCompiler` - Parallel compilation engine
- `ModuleLoader` - Thread-safe module loader
- `ProgressTracker` - Progress monitoring
- `McpServer` - MCP server interface
- `CompileRequest` / `CompileResponse` - MCP request/response types

---

## Troubleshooting

### Issue: Slow parallel compilation

**Cause**: Too few modules or overhead dominates  
**Solution**: Use sequential for < 3 modules

### Issue: High memory usage

**Cause**: Too many threads  
**Solution**: Reduce thread count with `--threads N`

### Issue: Compilation hangs

**Cause**: Deadlock or circular dependencies  
**Solution**: Check module dependencies, use `--verbose`

---

## Summary

The pascal-rs compiler provides three powerful interfaces for parallel compilation:

1. **CLI** - Easy command-line usage with `-j` flag
2. **MCP** - AI-friendly protocol for model integration
3. **Library** - Full programmatic control via Rust API

All interfaces share the same high-performance parallel compilation engine with thread-safe operations and comprehensive error handling.

---

*For more information, see [THREADING.md](./THREADING.md) and [ACKNOWLEDGMENTS.md](./ACKNOWLEDGMENTS.md)*