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
#![cfg(any(
    not(any(
        feature = "parser_tests",
        feature = "analyzer_tests",
        feature = "codegen_tests",
        feature = "interpreter_tests",
        feature = "conformance_tests",
        feature = "integration_tests",
    )),
    feature = "codegen_tests",
))]

/// Integration tests for the JavaScript backend (TDD)
///
/// Tests impl block → class method generation, match expressions,
/// and ensures the JS backend produces valid Node.js-executable code.
use std::fs;
use std::process::Command;
use tempfile::TempDir;

/// Compile .wj source to JavaScript and return the generated JS code
fn compile_to_js(source: &str) -> String {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.wj");
    fs::write(&test_file, source).unwrap();

    let output_dir = temp_dir.path().join("build");
    fs::create_dir_all(&output_dir).unwrap();

    let wj_output = Command::new(env!("CARGO_BIN_EXE_wj"))
        .arg("build")
        .arg("--target")
        .arg("javascript")
        .arg("--no-cargo")
        .arg(&test_file)
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute wj compiler");

    if !wj_output.status.success() {
        panic!(
            "JS compilation failed:\n{}",
            String::from_utf8_lossy(&wj_output.stderr)
        );
    }

    // Find the generated JS file (the backend names it output.js)
    for name in &["output.js", "main.js", "test.js"] {
        let generated_file = output_dir.join(name);
        if generated_file.exists() {
            return fs::read_to_string(&generated_file).unwrap();
        }
    }

    // List what's in the output directory
    let entries: Vec<String> = fs::read_dir(&output_dir)
        .map(|dir| {
            dir.filter_map(|e| e.ok())
                .map(|e| e.file_name().to_string_lossy().to_string())
                .collect()
        })
        .unwrap_or_default();

    panic!(
        "No JS file found in output dir. Files: {:?}\nStderr:\n{}",
        entries,
        String::from_utf8_lossy(&wj_output.stderr)
    );
}

/// Compile .wj to JS and run with Node.js. Returns stdout.
fn compile_and_run_js(source: &str) -> String {
    let temp_dir = TempDir::new().unwrap();
    let test_file = temp_dir.path().join("test.wj");
    fs::write(&test_file, source).unwrap();

    let output_dir = temp_dir.path().join("build");
    fs::create_dir_all(&output_dir).unwrap();

    let wj_output = Command::new(env!("CARGO_BIN_EXE_wj"))
        .arg("build")
        .arg("--target")
        .arg("javascript")
        .arg("--no-cargo")
        .arg(&test_file)
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute wj compiler");

    if !wj_output.status.success() {
        panic!(
            "JS codegen failed:\n{}",
            String::from_utf8_lossy(&wj_output.stderr)
        );
    }

    // Find JS file (the backend names it output.js)
    let js_file = ["output.js", "main.js", "test.js"]
        .iter()
        .map(|n| output_dir.join(n))
        .find(|p| p.exists())
        .unwrap_or_else(|| {
            let entries: Vec<String> = fs::read_dir(&output_dir)
                .map(|dir| {
                    dir.filter_map(|e| e.ok())
                        .map(|e| e.file_name().to_string_lossy().to_string())
                        .collect()
                })
                .unwrap_or_default();
            panic!(
                "No JS file found. Files: {:?}\nStderr:\n{}",
                entries,
                String::from_utf8_lossy(&wj_output.stderr)
            );
        });

    // The generated JS has an auto-run guard (`import.meta.url` check) that may
    // or may not fire depending on the Node.js version and how the file is invoked.
    // To avoid double-execution, we strip the auto-run block and add our own call.
    let js_code = fs::read_to_string(&js_file).unwrap();
    // Remove `export` keyword so it works as a standalone script
    let mut cleaned = js_code
        .replace("export function", "function")
        .replace("export class", "class")
        .replace("export const", "const")
        .replace("export let", "let");
    // Remove the auto-run block to prevent double main() calls
    if let Some(pos) = cleaned.find("// Auto-run main") {
        cleaned.truncate(pos);
    }
    // Write a .mjs file with the code + single unconditional main() call
    let test_js = output_dir.join("_test.mjs");
    let test_code = format!(
        "{}\n\n// Test runner: unconditional main() call\nif (typeof main === 'function') main();\n",
        cleaned.trim()
    );
    fs::write(&test_js, &test_code).unwrap();

    let node_output = Command::new("node")
        .arg(&test_js)
        .current_dir(&output_dir)
        .output()
        .expect("Failed to execute node");

    if !node_output.status.success() {
        let generated = fs::read_to_string(&js_file).unwrap_or_default();
        panic!(
            "Node.js execution failed:\n{}\n\nGenerated code:\n{}",
            String::from_utf8_lossy(&node_output.stderr),
            generated
        );
    }

    String::from_utf8(node_output.stdout).unwrap()
}

// ==========================================
// Basic JS generation tests
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_hello_world() {
    let output = compile_and_run_js(
        r#"
fn main() {
    println("Hello from JS!")
}
"#,
    );
    assert_eq!(output.trim(), "Hello from JS!");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_arithmetic() {
    let output = compile_and_run_js(
        r#"
fn main() {
    let a = 2 + 3
    println("{}", a)
}
"#,
    );
    assert_eq!(output.trim(), "5");
}

// ==========================================
// Impl block → class method tests (THE KEY FIX)
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_impl_generates_methods() {
    // Impl blocks should add methods to the corresponding class.
    // Currently they are dropped entirely — this test should FAIL (RED phase).
    let code = compile_to_js(
        r#"
struct Point {
    x: int,
    y: int
}

impl Point {
    fn sum(self) -> int {
        self.x + self.y
    }
}

fn main() {
    println("ok")
}
"#,
    );
    assert!(
        code.contains("sum(") || code.contains("sum ("),
        "Impl method 'sum' should appear in generated class. Got:\n{}",
        code
    );
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_impl_methods_callable() {
    // Methods should be callable on instances
    let output = compile_and_run_js(
        r#"
struct Point {
    x: int,
    y: int
}

impl Point {
    fn sum(self) -> int {
        self.x + self.y
    }
}

fn main() {
    let p = Point { x: 3, y: 4 }
    println("{}", p.sum())
}
"#,
    );
    assert_eq!(output.trim(), "7");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_impl_multiple_methods() {
    // Multiple methods in an impl block should all be generated
    let code = compile_to_js(
        r#"
struct Rect {
    w: float,
    h: float
}

impl Rect {
    fn area(self) -> float {
        self.w * self.h
    }

    fn perimeter(self) -> float {
        2.0 * (self.w + self.h)
    }
}

fn main() {
    println("ok")
}
"#,
    );
    assert!(
        code.contains("area(") || code.contains("area ("),
        "Should contain area method. Got:\n{}",
        code
    );
    assert!(
        code.contains("perimeter(") || code.contains("perimeter ("),
        "Should contain perimeter method. Got:\n{}",
        code
    );
}

// ==========================================
// Match expression tests
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_match_as_expression() {
    // Match used as an expression should work in JS
    let output = compile_and_run_js(
        r#"
fn describe(x: int) -> string {
    match x {
        1 => "one",
        2 => "two",
        _ => "other"
    }
}

fn main() {
    println("{}", describe(1))
    println("{}", describe(3))
}
"#,
    );
    assert_eq!(output.trim(), "one\nother");
}

// ==========================================
// Struct with constructor tests
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_struct_generates_class() {
    let code = compile_to_js(
        r#"
struct Player {
    name: string,
    score: int
}

fn main() {
    println("ok")
}
"#,
    );
    assert!(
        code.contains("class Player"),
        "Struct should generate class. Got:\n{}",
        code
    );
    assert!(
        code.contains("constructor("),
        "Class should have constructor. Got:\n{}",
        code
    );
}

// ==========================================
// Control flow tests
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_if_else() {
    let output = compile_and_run_js(
        r#"
fn main() {
    let x = 10
    if x > 5 {
        println("big")
    } else {
        println("small")
    }
}
"#,
    );
    assert_eq!(output.trim(), "big");
}

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_while_loop() {
    let output = compile_and_run_js(
        r#"
fn main() {
    let mut i = 0
    while i < 3 {
        println("{}", i)
        i += 1
    }
}
"#,
    );
    assert_eq!(output.trim(), "0\n1\n2");
}

// ==========================================
// Function tests
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_function_with_return() {
    let output = compile_and_run_js(
        r#"
fn double(n: int) -> int {
    n * 2
}

fn main() {
    println("{}", double(21))
}
"#,
    );
    assert_eq!(output.trim(), "42");
}

// ==========================================
// Enum tests
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_enum_generation() {
    // Enums should generate Object.freeze or similar construct
    let code = compile_to_js(
        r#"
enum Direction {
    Up,
    Down,
    Left,
    Right
}

fn main() {
    println("ok")
}
"#,
    );
    assert!(
        code.contains("Direction") && (code.contains("Object.freeze") || code.contains("Symbol")),
        "Enum should generate JS enum pattern. Got:\n{}",
        code
    );
}

// ==========================================
// Coverage gap: Recursion (runtime)
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_recursion() {
    let output = compile_and_run_js(
        r#"
fn fibonacci(n: int) -> int {
    if n <= 1 {
        return n
    }
    fibonacci(n - 1) + fibonacci(n - 2)
}

fn main() {
    println("{}", fibonacci(10))
}
"#,
    );
    assert_eq!(output.trim(), "55");
}

// ==========================================
// Coverage gap: Struct mutation (runtime)
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_struct_mutation() {
    let output = compile_and_run_js(
        r#"
struct Counter {
    value: int
}

impl Counter {
    fn get(self) -> int {
        self.value
    }

    fn increment(self) {
        self.value += 1
    }
}

fn main() {
    let mut c = Counter { value: 0 }
    println("{}", c.get())
    c.increment()
    println("{}", c.get())
    c.increment()
    println("{}", c.get())
}
"#,
    );
    assert_eq!(output.trim(), "0\n1\n2");
}

// ==========================================
// Coverage gap: For-range (runtime)
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_for_range() {
    let output = compile_and_run_js(
        r#"
fn main() {
    let mut sum = 0
    for i in 0..5 {
        sum += i
    }
    println("{}", sum)
}
"#,
    );
    assert_eq!(output.trim(), "10");
}

// ==========================================
// Coverage gap: Continue statement (runtime)
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_continue() {
    let output = compile_and_run_js(
        r#"
fn main() {
    let mut i = 0
    while i < 6 {
        i += 1
        if i % 2 == 0 {
            continue
        }
        println("{}", i)
    }
}
"#,
    );
    assert_eq!(output.trim(), "1\n3\n5");
}

// ==========================================
// Coverage gap: Loop/break (runtime)
// ==========================================

#[test]
#[cfg_attr(tarpaulin, ignore)]
fn test_js_loop_break() {
    let output = compile_and_run_js(
        r#"
fn main() {
    let mut count = 0
    loop {
        if count >= 3 {
            break
        }
        println("{}", count)
        count += 1
    }
}
"#,
    );
    assert_eq!(output.trim(), "0\n1\n2");
}