windjammer 0.48.0

A simple language inspired by Go, Ruby, and Elixir that transpiles to Rust - 80% of Rust's power with 20% of the complexity
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
#![cfg(any(
    not(any(
        feature = "parser_tests",
        feature = "analyzer_tests",
        feature = "codegen_tests",
        feature = "interpreter_tests",
        feature = "conformance_tests",
        feature = "integration_tests",
    )),
    feature = "analyzer_tests",
))]

// Pattern Matching Tests
// Automated tests for pattern matching features

#[path = "common/test_utils.rs"]
mod test_utils;

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use tempfile::tempdir;

/// Locate `name` (e.g. `foo.rs`) anywhere under `root` after `wj build`.
fn find_generated_rs_under(root: &Path, name: &str) -> Option<PathBuf> {
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let read = fs::read_dir(&dir).ok()?;
        for entry in read.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if path.file_name().and_then(|n| n.to_str()) == Some(name) {
                return Some(path);
            }
        }
    }
    None
}

fn compile_should_succeed(code: &str, test_name: &str) {
    match test_utils::compile_single_result(code) {
        Ok(_) => println!("✓ {} passed", test_name),
        Err(e) => panic!("✗ {} failed: {}", test_name, e),
    }
}

fn compile_and_check_rust_compiles(wj_file: &str, test_name: &str) {
    let wj_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join(wj_file);

    // One temp dir for wj output + rustc metadata (avoids mixing two TempDirs)
    let work = tempdir().expect("tempdir");

    // First, compile the Windjammer code (isolated output — safe under parallel tests)
    let output = Command::new(test_utils::wj_binary())
        .args([
            "build",
            wj_path.to_str().unwrap(),
            "-o",
            work.path().to_str().unwrap(),
            "--no-cargo",
        ])
        .output()
        .expect("Failed to execute compiler");

    if !output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        panic!(
            "✗ {} failed to compile Windjammer: {}{}",
            test_name, stdout, stderr
        );
    }

    // Get the generated Rust file name (remove .wj extension, add .rs)
    let rust_file = wj_file.replace(".wj", ".rs");
    let rs_name = Path::new(&rust_file)
        .file_name()
        .and_then(|n| n.to_str())
        .expect("rs file name");
    let rust_path = find_generated_rs_under(work.path(), rs_name).unwrap_or_else(|| {
        panic!(
            "✗ {}: no {} under {:?}",
            test_name,
            rs_name,
            fs::read_dir(work.path())
                .map(|d| d
                    .filter_map(|e| e.ok())
                    .map(|e| e.path())
                    .collect::<Vec<_>>())
                .unwrap_or_default()
        )
    });

    // Type-check generated Rust (metadata only; explicit -o)
    let rust_output = Command::new("rustc")
        .arg("--crate-type=lib")
        .arg("--emit=metadata")
        .arg("--edition=2021")
        .arg("-O")
        .arg("-o")
        .arg(work.path().join("verify.rmeta"))
        .arg(rust_path.as_os_str())
        .output()
        .expect("Failed to execute rustc");

    if !rust_output.status.success() {
        let stdout = String::from_utf8_lossy(&rust_output.stdout);
        let stderr = String::from_utf8_lossy(&rust_output.stderr);
        panic!(
            "✗ {} failed to compile Rust: {}{}",
            test_name, stdout, stderr
        );
    }

    println!("✓ {} passed (Windjammer + Rust compilation)", test_name);
}

fn compile_and_check_generated_rust(wj_file: &str, expected_imports: &[&str], test_name: &str) {
    let wj_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join(wj_file);

    let work = tempdir().expect("tempdir");

    let output = Command::new(test_utils::wj_binary())
        .args([
            "build",
            wj_path.to_str().unwrap(),
            "-o",
            work.path().to_str().unwrap(),
            "--no-cargo",
        ])
        .output()
        .expect("Failed to execute compiler");

    if !output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        panic!("✗ {} failed to compile: {}{}", test_name, stdout, stderr);
    }

    // Read the generated Rust file
    let rust_file = wj_file.replace(".wj", ".rs");
    let rs_name = Path::new(&rust_file)
        .file_name()
        .and_then(|n| n.to_str())
        .expect("rs file name");
    let rust_path = find_generated_rs_under(work.path(), rs_name).unwrap_or_else(|| {
        panic!(
            "✗ {}: no {} under {:?}",
            test_name,
            rs_name,
            fs::read_dir(work.path())
                .map(|d| d
                    .filter_map(|e| e.ok())
                    .map(|e| e.path())
                    .collect::<Vec<_>>())
                .unwrap_or_default()
        )
    });
    let generated_rust = fs::read_to_string(&rust_path)
        .unwrap_or_else(|_| panic!("Failed to read generated Rust file: {:?}", rust_path));

    // Check that all expected imports are present
    for expected_import in expected_imports {
        if !generated_rust.contains(expected_import) {
            panic!(
                "✗ {} failed: Expected import '{}' not found in generated Rust:\n{}",
                test_name, expected_import, generated_rust
            );
        }
    }

    println!("✓ {} passed", test_name);
}

fn compile_should_fail(code: &str, expected_error: &str, test_name: &str) {
    match test_utils::compile_single_result(code) {
        Ok(_) => panic!("✗ {} should have failed but succeeded", test_name),
        Err(e) => {
            if e.contains(expected_error) {
                println!("✓ {} passed (correctly rejected)", test_name);
            } else {
                panic!(
                    "✗ {} failed with wrong error.\nExpected: {}\nGot: {}",
                    test_name, expected_error, e
                );
            }
        }
    }
}

// ============================================================================
// TEST 1: Tuple Enum Variants - Definition
// ============================================================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_tuple_enum_definition_single_field() {
    let code = r#"
enum Option<T> {
    Some(T),
    None,
}
"#;
    compile_should_succeed(code, "tuple_enum_single_field");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_tuple_enum_definition_multiple_fields() {
    let code = r#"
enum Color {
    Rgb(i32, i32, i32),
    Rgba(i32, i32, i32, i32),
}
"#;
    compile_should_succeed(code, "tuple_enum_multiple_fields");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_tuple_enum_definition_mixed() {
    let code = r#"
enum Shape {
    Circle(f32),
    Rectangle(f32, f32),
    Point,
}
"#;
    compile_should_succeed(code, "tuple_enum_mixed");
}

// ============================================================================
// TEST 2: Tuple Enum Variants - Pattern Matching
// ============================================================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_tuple_enum_match_single_binding() {
    let code = r#"
enum Option<T> {
    Some(T),
    None,
}

fn unwrap(opt: Option<i32>) -> i32 {
    match opt {
        Option::Some(x) => { return x }
        Option::None => { return 0 }
    }
}
"#;
    compile_should_succeed(code, "tuple_enum_match_single");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_tuple_enum_match_multiple_bindings() {
    let code = r#"
enum Color {
    Rgb(i32, i32, i32),
}

fn sum_rgb(color: Color) -> i32 {
    match color {
        Color::Rgb(r, g, b) => { return r + g + b }
    }
}
"#;
    compile_should_succeed(code, "tuple_enum_match_multiple");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_tuple_enum_match_wildcards() {
    let code = r#"
enum Color {
    Rgb(i32, i32, i32),
}

fn get_red(color: Color) -> i32 {
    match color {
        Color::Rgb(r, _, _) => { return r }
    }
}
"#;
    compile_should_succeed(code, "tuple_enum_match_wildcards");
}

// ============================================================================
// TEST 3: Let Patterns - Irrefutable (Should Work)
// ============================================================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_let_tuple_destructuring() {
    let code = r#"
fn test() -> i32 {
    let (x, y) = (10, 20)
    x + y
}
"#;
    compile_should_succeed(code, "let_tuple_destructuring");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_let_nested_tuple_destructuring() {
    let code = r#"
fn test() -> i32 {
    let ((a, b), (c, d)) = ((1, 2), (3, 4))
    a + b + c + d
}
"#;
    compile_should_succeed(code, "let_nested_tuple");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_let_wildcard() {
    let code = r#"
fn test() -> i32 {
    let _ = 100
    let (x, _) = (10, 20)
    return x
}
"#;
    compile_should_succeed(code, "let_wildcard");
}

// ============================================================================
// TEST 4: Let Patterns - Refutable (Should Fail)
// ============================================================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_let_enum_variant_rejected() {
    let code = r#"
enum Option<T> {
    Some(T),
    None,
}

fn test() -> i32 {
    let opt = Option::Some(42)
    let Option::Some(x) = opt
    return x
}
"#;
    compile_should_fail(code, "Refutable pattern", "let_enum_variant_rejected");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_let_literal_rejected() {
    let code = r#"
fn test() -> i32 {
    let x = 42
    let 42 = x
    return x
}
"#;
    compile_should_fail(code, "Refutable pattern", "let_literal_rejected");
}

// ============================================================================
// TEST 5: Consistency - Number Literals
// ============================================================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_hex_literals() {
    let code = r#"
fn test() -> i64 {
    let x = 0xFF
    let y = 0xDEADBEEF
    return x + y
}
"#;
    compile_should_succeed(code, "hex_literals");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_binary_literals() {
    let code = r#"
fn test() -> i64 {
    let x = 0b1010
    let y = 0b1111_0000
    return x + y
}
"#;
    compile_should_succeed(code, "binary_literals");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_octal_literals() {
    let code = r#"
fn test() -> i64 {
    let x = 0o755
    let y = 0o644
    return x + y
}
"#;
    compile_should_succeed(code, "octal_literals");
}

// ============================================================================
// TEST 6: Consistency - Module Paths
// ============================================================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_module_path_double_colon() {
    let code = r#"
use std::fs::File
"#;
    compile_should_succeed(code, "module_path_double_colon");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_module_path_slash_rejected() {
    let code = r#"
use std/fs
"#;
    compile_should_fail(
        code,
        "Use '::' for module paths",
        "module_path_slash_rejected",
    );
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_module_path_dot_rejected() {
    let code = r#"
use std.fs
"#;
    compile_should_fail(
        code,
        "Use '::' for module paths",
        "module_path_dot_rejected",
    );
}

// ============================================================================
// TEST 7: Consistency - Qualified Paths
// ============================================================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_qualified_path_in_type() {
    let code = r#"
struct Event {
    pub value: i32,
}
"#;
    compile_should_succeed(code, "qualified_path_in_type");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_qualified_path_in_match() {
    let code = r#"
enum Color {
    Red,
    Green,
}

fn test(c: Color) -> i32 {
    match c {
        Color::Red => { return 1 }
        Color::Green => { return 2 }
    }
}
"#;
    compile_should_succeed(code, "qualified_path_in_match");
}

// ============================================================================
// ============================================================================
// STRUCT PATTERN TESTS
// ============================================================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_struct_pattern_basic() {
    let code = r#"
enum Shape {
    Circle { radius: f32 },
    Rectangle { width: f32, height: f32 },
}

fn calculate_area(shape: Shape) -> f32 {
    match shape {
        Shape::Circle { radius: r } => {
            return 3.14159 * r * r
        }
        Shape::Rectangle { width: w, height: h } => {
            return w * h
        }
    }
}
"#;
    compile_should_succeed(code, "struct_pattern_basic");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_struct_pattern_with_wildcard() {
    let code = r#"
enum Shape {
    Rectangle { width: f32, height: f32 },
}

fn has_large_width(shape: Shape) -> bool {
    match shape {
        Shape::Rectangle { width: w, height: _ } => w > 10.0,
    }
}
"#;
    compile_should_succeed(code, "struct_pattern_with_wildcard");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_struct_pattern_multiple_variants() {
    let code = r#"
enum Shape {
    Circle { radius: f32 },
    Rectangle { width: f32, height: f32 },
    Triangle { base: f32, height: f32 },
}

fn get_first_dimension(shape: Shape) -> f32 {
    match shape {
        Shape::Circle { radius: r } => r,
        Shape::Rectangle { width: w, height: _ } => w,
        Shape::Triangle { base: b, height: _ } => b,
    }
}
"#;
    compile_should_succeed(code, "struct_pattern_multiple_variants");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_module_import_resolution() {
    // This test verifies that when multiple types are imported from the same module,
    // the compiler correctly resolves which module file each type is defined in.
    // Bug: Compiler was generating "use super::collider2d::Collider2D" when it should
    // generate "use super::module_import_resolution::Collider2D" because Collider2D
    // is defined in module_import_resolution.wj, not in a separate collider2d.wj file.

    compile_and_check_generated_rust(
        "module_import_resolution_user.wj",
        &[
            "use super::module_import_resolution::RigidBody2D",
            "use super::module_import_resolution::Collider2D", // NOT collider2d!
        ],
        "module_import_resolution",
    );
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_operator_precedence_negation() {
    // Test that !(a || b) generates correct Rust with parentheses preserved
    // Bug: Compiler was generating !a || b instead of !(a || b)

    compile_and_check_generated_rust(
        "operator_precedence.wj",
        &[
            "!(a || b)", // Must have parentheses around the OR
            "!(a && b)", // Must have parentheses around the AND
        ],
        "operator_precedence",
    );
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_array_indexing_with_int() {
    // Test that array indexing with 'int' type automatically casts to usize
    // Bug: arr[index] where index: int generates arr[index as i64] which fails
    // Expected: arr[index as usize] or automatic conversion

    compile_and_check_rust_compiles("array_indexing.wj", "array_indexing_with_int");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_param_mutability_inference() {
    // Test that function parameters are automatically inferred as &mut when mutated
    // Bug: fn move_point(p: Point, dx: f32) { p.x = ... } generates p: Point instead of p: &mut Point
    // Expected: Automatic inference of &mut for mutated parameters

    compile_and_check_rust_compiles(
        "param_mutability_inference.wj",
        "param_mutability_inference",
    );
}

#[test]
fn test_trait_impl_stdlib() {
    // Test that trait implementations match trait signatures exactly
    // Bug: fn add(self, other: Point) was generating other: &Point
    // Expected: Trait method parameters should NOT be inferred, use trait signature

    compile_and_check_rust_compiles("trait_impl_stdlib.wj", "trait_impl_stdlib");
}

#[test]
fn test_copy_type_ownership() {
    // Test that Copy types used in operator expressions remain owned
    // Bug: fn distance(a: Vec2, b: Vec2) with a - b generates a: &Vec2, b: &Vec2
    // This breaks operator overloading because Sub is not implemented for &Vec2
    // Expected: Copy types should remain owned for operator compatibility

    compile_and_check_rust_compiles("copy_type_ownership.wj", "copy_type_ownership");
}

// ============================================================================
// MAIN TEST RUNNER
// ============================================================================

#[test]
fn run_all_pattern_tests() {
    println!("\n=== Running Pattern Matching Tests ===\n");

    // Note: Individual tests run via cargo test
    // This is just a summary
    println!("Run with: cargo test --test pattern_matching_tests");
}