ruchy 4.1.2

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
412
413
414
415
416
417
418
419
#![allow(non_snake_case)]
//! TRANSPILER-DEFECT-015: Mutable String Inference (Function Scope)
//!
//! **Issue**: Mutable string variables in function scope not detected as needing String type
//!
//! **Root Cause**: v3.163.0's `is_variable_mutated()` doesn't detect string accumulator pattern
//! in function bodies (only works at top-level).
//!
//! **Impact**: 9 errors in reaper project (60% of remaining errors)
//! - 8 × E0308: format!() returns String, assigned to &str
//! - 1 × E0369: cannot add String to &str
//!
//! **Real-world Example** (reaper main.ruchy:357-366):
//! ```ruchy
//! fun format_process(proc: Process) -> String {
//!     let formatted = "Process[PID=";           // ❌ Should be String::from("...")
//!     formatted = formatted + proc.pid.to_string();  // ❌ Assignment fails
//!     formatted = formatted + ", name='";
//!     formatted
//! }
//! ```
//!
//! **Expected Transpilation**:
//! ```rust
//! fn format_process(proc: Process) -> String {
//!     let mut formatted = String::from("Process[PID=");  // ✅ Mutable String
//!     formatted = format!("{}{}", formatted, proc.pid.to_string());
//!     formatted = format!("{}{}", formatted, ", name='");
//!     formatted
//! }
//! ```
//!
//! **Test Strategy**: EXTREME TDD (RED → GREEN → REFACTOR)
//! - RED: These tests MUST fail with E0308/E0369
//! - GREEN: Fix `is_variable_mutated()` to detect function-scope mutations
//! - REFACTOR: Property tests with 10K+ inputs

use std::fs;
use tempfile::TempDir;

/// Test 1: Function-scope string accumulator pattern (ACTUAL reaper pattern)
///
/// This is the EXACT pattern from reaper's `format_process()` function.
/// Ruchy code uses string concatenation in function body.
#[test]
fn test_defect_015_01_function_scope_string_accumulator_RED() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.ruchy");

    // ACTUAL pattern from reaper main.ruchy:352-368
    let ruchy_code = r#"
struct Process {
    pid: i32,
    name: String,
    cpu_usage: f64,
}

fun format_process(proc: Process) -> String {
    let formatted = "Process[PID=";
    formatted = formatted + proc.pid.to_string();
    formatted = formatted + ", name='";
    formatted = formatted + proc.name;
    formatted = formatted + "', CPU=";
    formatted = formatted + proc.cpu_usage.to_string();
    formatted = formatted + "%]";
    formatted
}

let proc = Process { pid: 123, name: "test", cpu_usage: 45.5 };
let result = format_process(proc);
println(result);
"#;

    fs::write(&test_file, ruchy_code).unwrap();

    // Run ruchy compile - should succeed after fix
    let output = assert_cmd::cargo::cargo_bin_cmd!("ruchy")
        .arg("compile")
        .arg(&test_file)
        .output()
        .unwrap();

    if output.status.success() {
        // After fix is applied, this should compile and run successfully
        eprintln!("✅ GREEN: Test passes after fix applied");
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // This test is RED - we EXPECT these errors before fix
        assert!(
            stderr.contains("E0308") || stderr.contains("E0369"),
            "Expected E0308 or E0369 errors (mutable string not detected). Got:\n{stderr}"
        );
        eprintln!("✅ RED TEST: E0308/E0369 errors confirmed (as expected before fix)");
        eprintln!("Error details:\n{stderr}");
    }
}

/// Test 2: format!() macro returns String, assigned to &str
///
/// This is the SPECIFIC error pattern from reaper line 83.
#[test]
#[ignore = "transpiler defect 015 not fixed yet"]
fn test_defect_015_02_format_macro_returns_string_RED() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.ruchy");

    let ruchy_code = r#"
fun build_message(id: i32, name: String) -> String {
    let msg = "ID: ";
    msg = msg + id.to_string();  // After transpilation: format!("{}{}", msg, id.to_string())
    msg = msg + ", Name: ";
    msg = msg + name;
    msg
}

let result = build_message(42, "test");
println(result);
"#;

    fs::write(&test_file, ruchy_code).unwrap();

    let output = assert_cmd::cargo::cargo_bin_cmd!("ruchy")
        .arg("compile")
        .arg(&test_file)
        .output()
        .unwrap();

    if output.status.success() {
        eprintln!("✅ GREEN: format!() pattern fixed");
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("E0308"),
            "Expected E0308: format!() returns String, msg is &str. Got:\n{stderr}"
        );
        eprintln!("✅ RED TEST: format!() type mismatch confirmed");
    }
}

/// Test 3: Multiple concatenations in sequence
///
/// Pattern from reaper's `format_rule` function.
#[test]
#[ignore = "transpiler defect 015 not fixed yet"]
fn test_defect_015_03_multiple_concatenations_RED() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.ruchy");

    let ruchy_code = r#"
fun build_long_string(a: String, b: String, c: String) -> String {
    let result = "Start: ";
    result = result + a;
    result = result + ", Middle: ";
    result = result + b;
    result = result + ", End: ";
    result = result + c;
    result
}

let output = build_long_string("foo", "bar", "baz");
println(output);
"#;

    fs::write(&test_file, ruchy_code).unwrap();

    let output = assert_cmd::cargo::cargo_bin_cmd!("ruchy")
        .arg("compile")
        .arg(&test_file)
        .output()
        .unwrap();

    if output.status.success() {
        eprintln!("✅ GREEN: Multiple concatenations fixed");
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("E0308") || stderr.contains("E0369"),
            "Expected type errors from multiple concatenations. Got:\n{stderr}"
        );
        eprintln!("✅ RED TEST: Multiple concatenation errors confirmed");
    }
}

/// Test 4: String field concatenation (ACTUAL reaper pattern line 183)
///
/// This pattern appears 4 times in reaper (lines 183, 185, 197, 244).
#[test]
fn test_defect_015_04_string_field_concatenation_RED() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.ruchy");

    let ruchy_code = r#"
struct Config {
    name: String,
    path: String,
}

fun format_config(cfg: Config) -> String {
    let output = "Config: ";
    output = output + cfg.name;    // cfg.name is String
    output = output + " at ";
    output = output + cfg.path;    // cfg.path is String
    output
}

let config = Config { name: "test.conf", path: "/etc/test" };
let result = format_config(config);
println(result);
"#;

    fs::write(&test_file, ruchy_code).unwrap();

    let output = assert_cmd::cargo::cargo_bin_cmd!("ruchy")
        .arg("compile")
        .arg(&test_file)
        .output()
        .unwrap();

    if output.status.success() {
        eprintln!("✅ GREEN: String field concatenation fixed");
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("E0308"),
            "Expected E0308: output is &str, cfg.name is String. Got:\n{stderr}"
        );
        eprintln!("✅ RED TEST: String field concatenation error confirmed");
    }
}

/// Test 5: Baseline - Immutable string should remain &str
///
/// This test ensures fix doesn't break existing behavior.
#[test]
#[ignore = "transpiler defect 015 not fixed yet"]
fn test_defect_015_05_immutable_string_baseline() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.ruchy");

    let ruchy_code = r#"
fun get_message() -> String {
    let msg = "Hello, World!";  // Immutable, never reassigned
    msg.to_string()              // Explicit conversion
}

let result = get_message();
println(result);
"#;

    fs::write(&test_file, ruchy_code).unwrap();

    assert_cmd::cargo::cargo_bin_cmd!("ruchy")
        .arg("compile")
        .arg(&test_file)
        .assert()
        .success();
}

/// Test 6: Top-level mutable string (v3.163.0 should already handle)
///
/// This is the pattern that v3.163.0 fixed - verify it still works.
#[test]
#[ignore = "transpiler defect 015 not fixed yet"]
fn test_defect_015_06_top_level_mutable_string_baseline() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.ruchy");

    let ruchy_code = r#"
let mut formatted = "Start";
formatted = formatted + " Middle";
formatted = formatted + " End";
println(formatted);
"#;

    fs::write(&test_file, ruchy_code).unwrap();

    assert_cmd::cargo::cargo_bin_cmd!("ruchy")
        .arg("compile")
        .arg(&test_file)
        .assert()
        .success();
}

/// Test 7: Nested block string accumulator
///
/// Ensures fix works in nested scopes.
#[test]
#[ignore = "transpiler defect 015 not fixed yet"]
fn test_defect_015_07_nested_block_string_accumulator_RED() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.ruchy");

    let ruchy_code = r#"
fun build_complex_message(x: i32) -> String {
    if x > 0 {
        let msg = "Positive: ";
        msg = msg + x.to_string();
        msg
    } else {
        let msg = "Negative: ";
        msg = msg + x.to_string();
        msg
    }
}

let result = build_complex_message(42);
println(result);
"#;

    fs::write(&test_file, ruchy_code).unwrap();

    let output = assert_cmd::cargo::cargo_bin_cmd!("ruchy")
        .arg("compile")
        .arg(&test_file)
        .output()
        .unwrap();

    if output.status.success() {
        eprintln!("✅ GREEN: Nested block patterns fixed");
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("E0308") || stderr.contains("E0369"),
            "Expected type errors in nested blocks. Got:\n{stderr}"
        );
        eprintln!("✅ RED TEST: Nested block string accumulator errors confirmed");
    }
}

/// Test 8: String concatenation with method call results
///
/// Real-world pattern from reaper (`to_string()` returns String).
#[test]
#[ignore = "transpiler defect 015 not fixed yet"]
fn test_defect_015_08_method_call_concatenation_RED() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.ruchy");

    let ruchy_code = r#"
fun format_number(n: i32) -> String {
    let output = "Number: ";
    output = output + n.to_string();
    output
}

let result = format_number(123);
println(result);
"#;

    fs::write(&test_file, ruchy_code).unwrap();

    let output = assert_cmd::cargo::cargo_bin_cmd!("ruchy")
        .arg("compile")
        .arg(&test_file)
        .output()
        .unwrap();

    if output.status.success() {
        eprintln!("✅ GREEN: Method call concatenation fixed");
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("E0308") || stderr.contains("E0369"),
            "Expected type errors with method call results. Got:\n{stderr}"
        );
        eprintln!("✅ RED TEST: Method call concatenation errors confirmed");
    }
}

/// Test 9: E0369 specific - cannot add String to &str
///
/// This is the EXACT error from reaper line 85.
#[test]
#[ignore = "transpiler defect 015 not fixed yet"]
fn test_defect_015_09_e0369_string_to_str_RED() {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.ruchy");

    let ruchy_code = r#"
struct Data {
    value: String,
}

fun format_data(d: Data) -> String {
    let result = "Data: ";
    result = result + d.value;  // ❌ &str + String → E0369
    result
}

let data = Data { value: "test" };
let output = format_data(data);
println(output);
"#;

    fs::write(&test_file, ruchy_code).unwrap();

    let output = assert_cmd::cargo::cargo_bin_cmd!("ruchy")
        .arg("compile")
        .arg(&test_file)
        .output()
        .unwrap();

    if output.status.success() {
        eprintln!("✅ GREEN: E0369 pattern fixed");
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("E0369"),
            "Expected E0369: cannot add String to &str. Got:\n{stderr}"
        );
        eprintln!("✅ RED TEST: E0369 (cannot add String to &str) confirmed");
    }
}

// PROPERTY TESTS (Run after GREEN phase)
// These will be written in Phase 3 (REFACTOR) with proptest

// MUTATION TESTS (Run after GREEN phase)
// cargo mutants --file src/backend/transpiler/statements.rs --timeout 60