ruchy 4.2.0

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
# Ruchy Testing Infrastructure Documentation

## Overview

This document describes the testing infrastructure for Ruchy, including both the current implementation for validating book examples and the future roadmap for native Ruchy testing commands.

## Current Testing Architecture (v0.4.x)

### Binary Compilation Pipeline

```
.ruchy file → Parser → AST → Transpiler → Rust code → LLVM → Native Binary → Execution
```

Every Ruchy script goes through this pipeline to produce an optimized native binary via LLVM.

### Testing Harness API

The `ruchy::testing` module provides a public API for external projects (particularly `ruchy-book`) to validate code examples:

```rust
use ruchy::testing::{RuchyTestHarness, OptLevel};

// Create a test harness
let harness = RuchyTestHarness::new();

// Validate a single file
let result = harness.validate_file(Path::new("example.ruchy"))?;
assert!(result.compile_success);

// Assert specific output
harness.assert_output(
    r#"println("Hello")"#,
    "Hello",
    "hello_test"
)?;

// Validate all files in a directory
let results = harness.validate_directory(Path::new("examples/"))?;
```

### Configuration Options

```rust
let harness = RuchyTestHarness {
    keep_intermediates: false,      // Don't keep temp files
    optimization_level: OptLevel::Basic,  // -O2 LLVM optimization
    timeout_secs: 30,               // 30 second timeout
};
```

### For Book Repository Usage

The `ruchy-book` repository will use this infrastructure in its CI/CD:

```toml
# ruchy-book/Cargo.toml
[dev-dependencies]
ruchy = "0.4.13"

[[test]]
name = "validate_examples"
```

```rust
// ruchy-book/tests/validate_examples.rs
use ruchy::testing::RuchyTestHarness;

#[test]
fn test_all_book_examples() {
    let harness = RuchyTestHarness::new();
    
    // Validate all chapter examples
    for chapter in 1..=20 {
        let dir = format!("listings/ch{:02}/", chapter);
        let results = harness.validate_directory(Path::new(&dir))
            .expect("Failed to validate chapter examples");
        
        for result in results {
            assert!(result.compile_success, 
                    "Example {} failed to compile", result.name);
            
            // Check against expected output if it exists
            let output_file = Path::new(&result.name)
                .with_extension("output");
            if output_file.exists() {
                let expected = fs::read_to_string(output_file)?;
                assert_eq!(result.execution_output.unwrap().trim(), 
                          expected.trim());
            }
        }
    }
}
```

## Future CLI Commands (v0.5.x and beyond)

### Native Ruchy Testing Commands

Once Ruchy reaches self-hosting capability, users will have native commands:

#### `ruchy test` - Run tests
```bash
# Run all tests in current project
ruchy test

# Run specific test file
ruchy test tests/math_test.ruchy

# Run with coverage
ruchy test --coverage

# Watch mode
ruchy test --watch

# Run only tests matching pattern
ruchy test --filter "math_*"
```

Example test file:
```ruchy
// tests/math_test.ruchy
#[test]
fn test_addition() {
    assert_eq(2 + 2, 4)
}

#[test]
fn test_multiplication() {
    assert_eq(3 * 3, 9)
}

#[test]
#[should_panic(expected = "division by zero")]
fn test_division_by_zero() {
    let x = 10 / 0
}
```

#### `ruchy check` - Type checking
```bash
# Type check all files
ruchy check

# Check specific file
ruchy check src/main.ruchy

# Check with verbose output
ruchy check --verbose

# Strict mode (all warnings are errors)
ruchy check --strict
```

#### `ruchy lint` - Code quality
```bash
# Run default lints
ruchy lint

# Auto-fix issues
ruchy lint --fix

# Use specific lint profile
ruchy lint --profile strict

# Custom lint configuration
ruchy lint --config .ruchy-lint.toml
```

Lint configuration:
```toml
# .ruchy-lint.toml
[lints]
complexity = "warn"
unused_variables = "error"
naming_conventions = "warn"
documentation = "allow"

[rules.complexity]
max_cyclomatic = 10
max_cognitive = 15
```

#### `ruchy fmt` - Code formatting
```bash
# Format all files
ruchy fmt

# Format specific directory
ruchy fmt src/

# Check formatting without changing
ruchy fmt --check

# Use custom style
ruchy fmt --style compact
```

Format configuration:
```toml
# .ruchy-fmt.toml
indent_style = "space"
indent_size = 4
max_line_length = 100
trailing_comma = "always"
```

#### `ruchy build` - Compilation
```bash
# Build current project
ruchy build

# Release build with full LLVM optimizations
ruchy build --release

# Target specific architecture
ruchy build --target x86_64-unknown-linux-gnu

# Output binary name
ruchy build -o myapp

# Show LLVM IR
ruchy build --emit llvm-ir
```

#### `ruchy run` - Execution
```bash
# Run a script
ruchy run script.ruchy

# Run with arguments
ruchy run main.ruchy -- arg1 arg2

# Run in debug mode
ruchy run --debug script.ruchy

# Profile execution
ruchy run --profile script.ruchy
```

#### `ruchy doc` - Documentation
```bash
# Generate documentation
ruchy doc

# Open in browser
ruchy doc --open

# Include private items
ruchy doc --private

# Generate markdown
ruchy doc --format markdown
```

#### `ruchy bench` - Benchmarking
```bash
# Run all benchmarks
ruchy bench

# Run specific benchmark
ruchy bench bench_sorting

# Compare with baseline
ruchy bench --baseline main

# Save results
ruchy bench --save results.json
```

Example benchmark:
```ruchy
#[bench]
fn bench_quicksort(b: &mut Bencher) {
    let data = random_array(1000)
    b.iter(|| {
        quicksort(data.clone())
    })
}
```

### Command Integration with Book Examples

The book will teach these commands progressively:

1. **Chapter 1**: `ruchy run` - Running your first program
2. **Chapter 3**: `ruchy fmt` - Keeping code clean
3. **Chapter 5**: `ruchy check` - Understanding types
4. **Chapter 7**: `ruchy test` - Writing tests
5. **Chapter 9**: `ruchy lint` - Code quality
6. **Chapter 12**: `ruchy bench` - Performance
7. **Chapter 15**: `ruchy build --release` - Production builds

## Testing Philosophy

### Principles

1. **Fast Feedback**: Tests should run in <5 seconds for typical projects
2. **Clear Errors**: Test failures should pinpoint the exact issue
3. **Progressive Disclosure**: Simple cases simple, complex cases possible
4. **Book Integration**: Every book example is a test case

### Test Categories

1. **Unit Tests**: Test individual functions
2. **Integration Tests**: Test module interactions
3. **Property Tests**: Generative testing with random inputs
4. **Snapshot Tests**: Compare output against saved snapshots
5. **Benchmark Tests**: Performance regression prevention
6. **Doc Tests**: Examples in documentation are tested

## Implementation Timeline

### Phase 1 (Current - v0.4.x)
- ✅ Basic test harness for book validation
- ✅ LLVM compilation pipeline
- ✅ Integration with cargo test
- 🚧 Property-based testing
- 🚧 Benchmark suite

### Phase 2 (v0.5.x)
- [ ] Native `ruchy test` command
- [ ] Native `ruchy check` command
- [ ] Native `ruchy fmt` command
- [ ] Basic `ruchy lint` rules

### Phase 3 (v0.6.x)
- [ ] Full `ruchy lint` with custom rules
- [ ] `ruchy bench` with statistical analysis
- [ ] `ruchy doc` generation
- [ ] IDE integration APIs

### Phase 4 (v1.0)
- [ ] Self-hosting: Ruchy compiler written in Ruchy
- [ ] Full test coverage tools
- [ ] Mutation testing support
- [ ] Fuzzing integration

## Usage Examples

### Current: Testing Book Examples (Rust/Cargo)

```bash
# In ruchy-book repository
cargo test --test validate_examples
```

### Future: Native Ruchy Testing

```bash
# In any Ruchy project
ruchy test                 # Run all tests
ruchy fmt --check && ruchy lint && ruchy test  # Full CI pipeline
ruchy build --release      # Production build
```

### Book Example Validation Flow

```mermaid
graph LR
    A[.ruchy file] --> B[Parse AST]
    B --> C[Type Check]
    C --> D[Transpile to Rust]
    D --> E[Compile via LLVM]
    E --> F[Execute Binary]
    F --> G[Compare Output]
    G --> H{Match?}
    H -->|Yes| I[✅ Pass]
    H -->|No| J[❌ Fail with Diff]
```

## Error Reporting

Test failures provide clear, actionable feedback:

```
❌ Test failed: examples/fibonacci.ruchy

Expected output:
  55

Actual output:
  89

Compilation details:
  Parse: ✅ Success (12ms)
  Transpile: ✅ Success (8ms)
  LLVM Compile: ✅ Success (243ms)
  Execution: ✅ Success (3ms)
  Output: ❌ Mismatch

Hint: Check the fibonacci logic in lines 3-5
```

## Performance Targets

- **Parse**: >50MB/s throughput
- **Transpile**: <15ms for typical program
- **LLVM Compile**: <5s for book examples
- **Test Execution**: <100ms per test
- **Full Test Suite**: <60s for entire book

## Conclusion

This testing infrastructure ensures:
1. Every book example compiles and runs correctly
2. Users have a smooth learning experience
3. The language evolves toward self-hosting
4. Quality is maintained through automated testing

The progression from cargo-based testing to native Ruchy commands mirrors the language's evolution from transpiler to self-hosted compiler.