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
//! Centralized test utilities for Windjammer compiler tests.
//!
//! Include in your test crate with a path relative to `tests/common/`:
//! ```rust
//! // From tests/<suite>/foo_test.rs:
//! #[path = "../common/test_utils.rs"]
//! mod test_utils;
//! use test_utils::*;
//!
//! // From tests/codegen/<backend>/foo_test.rs:
//! #[path = "../../common/test_utils.rs"]
//! mod test_utils;
//! ```
//!
//! Provides common compilation helpers that properly isolate temp directories,
//! eliminating race conditions in parallel test execution.
#![allow(dead_code)]

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use tempfile::TempDir;
use windjammer::compiler::build_project;
use windjammer::CompilationTarget;

/// Default timeout for subprocess calls (cargo check, cargo build, cargo test).
const SUBPROCESS_TIMEOUT: Duration = Duration::from_secs(180);

/// Run a `Command` with a timeout. Kills the child and returns an error if the
/// deadline is exceeded. This prevents the test suite from hanging indefinitely
/// when a cargo subprocess gets stuck on a lock file or compilation loop.
fn run_with_timeout(mut cmd: Command, timeout: Duration) -> std::io::Result<Output> {
    let mut child = cmd
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()?;

    let deadline = Instant::now() + timeout;
    loop {
        match child.try_wait()? {
            Some(_status) => return child.wait_with_output(),
            None => {
                if Instant::now() >= deadline {
                    let _ = child.kill();
                    let _ = child.wait();
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::TimedOut,
                        format!("subprocess timed out after {}s", timeout.as_secs()),
                    ));
                }
                std::thread::sleep(Duration::from_millis(250));
            }
        }
    }
}

/// Serializes cargo invocations so parallel test threads don't fight over
/// the shared target directory's lock file.
static CARGO_LOCK: Mutex<()> = Mutex::new(());

/// Serializes `wj build` subprocesses — concurrent compiler runs share process-global
/// state (e.g. current_exe identity reads) and can false-trigger stale-output checks.
static WJ_BUILD_LOCK: Mutex<()> = Mutex::new(());

/// Run the `wj` CLI with args, serialized across test threads.
pub fn run_wj_command<I, S>(args: I) -> Output
where
    I: IntoIterator<Item = S>,
    S: AsRef<std::ffi::OsStr>,
{
    let _guard = WJ_BUILD_LOCK.lock().unwrap_or_else(|p| p.into_inner());
    run_with_timeout(
        {
            let mut cmd = Command::new(wj_binary());
            cmd.args(args);
            cmd
        },
        SUBPROCESS_TIMEOUT,
    )
    .expect("run wj")
}

/// Shared target directory for integration tests that spawn `cargo`.
/// Caching deps here avoids recompiling `windjammer-runtime`, `serde`, etc.
/// from scratch in every fresh temp directory.
fn shared_cargo_target_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("target")
        .join("wj_integration_verify")
}

/// Type-check generated Rust code via `cargo check` with a shared dependency cache.
///
/// The `build_dir` must contain a `Cargo.toml` (the Windjammer compiler generates one
/// when `--no-cargo` is NOT passed, or the test can write one manually).
///
/// Panics with the compiler's stderr on failure.
pub fn cargo_check_generated(build_dir: &Path) {
    let _guard = CARGO_LOCK.lock().unwrap_or_else(|p| p.into_inner());
    let shared_target = shared_cargo_target_dir();

    let mut cmd = Command::new("cargo");
    cmd.current_dir(build_dir)
        .env("CARGO_TARGET_DIR", &shared_target)
        .args(["check", "--quiet"]);

    let output = run_with_timeout(cmd, SUBPROCESS_TIMEOUT)
        .unwrap_or_else(|e| panic!("cargo check failed to run: {}", e));

    assert!(
        output.status.success(),
        "cargo check failed in {}.\nstderr:\n{}",
        build_dir.display(),
        String::from_utf8_lossy(&output.stderr),
    );
}

/// Full `cargo build` of generated Rust code with a shared dependency cache.
///
/// Use when the test needs to **run** the resulting binary (e.g. `voxel_octree_test`).
/// Returns the shared target directory so callers can find the binary at
/// `<returned_path>/debug/<crate_name>`.
pub fn cargo_build_generated(build_dir: &Path) -> PathBuf {
    let _guard = CARGO_LOCK.lock().unwrap_or_else(|p| p.into_inner());
    let shared_target = shared_cargo_target_dir();

    let mut cmd = Command::new("cargo");
    cmd.current_dir(build_dir)
        .env("CARGO_TARGET_DIR", &shared_target)
        .args(["build", "--quiet"]);

    let output = run_with_timeout(cmd, SUBPROCESS_TIMEOUT)
        .unwrap_or_else(|e| panic!("cargo build failed to run: {}", e));

    assert!(
        output.status.success(),
        "cargo build failed in {}.\nstderr:\n{}",
        build_dir.display(),
        String::from_utf8_lossy(&output.stderr),
    );

    shared_target
}

// =============================================================================
// Single-file compilation (library API — fast, no subprocess)
// =============================================================================

/// Compile a single `.wj` source string to Rust and return the generated code.
/// Panics if compilation fails.
pub fn compile_single(source: &str) -> String {
    compile_single_result(source).unwrap_or_else(|e| panic!("Compilation failed:\n{}", e))
}

/// Compile a single `.wj` source string to Rust, returning Result.
pub fn compile_single_result(source: &str) -> Result<String, String> {
    let tmp = TempDir::new().expect("tempdir");
    let wj_file = tmp.path().join("test.wj");
    fs::write(&wj_file, source).unwrap();
    let out_dir = tmp.path().join("build");

    build_project(&wj_file, &out_dir, CompilationTarget::Rust, false).map_err(|e| e.to_string())?;

    fs::read_to_string(out_dir.join("test.rs"))
        .map_err(|e| format!("Failed to read generated file: {}", e))
}

/// Compile with a pre-populated signature registry (cross-file / collision tests).
pub fn compile_with_external_sigs(
    source: &str,
    external_sigs: &windjammer::analyzer::SignatureRegistry,
) -> String {
    use windjammer::analyzer::Analyzer;
    use windjammer::codegen::rust::CodeGenerator;
    use windjammer::lexer::Lexer;
    use windjammer::parser::Parser;

    let mut lexer = Lexer::new(source);
    let tokens = lexer.tokenize_with_locations();
    let parser = Box::leak(Box::new(Parser::new(tokens)));
    let program = parser.parse().unwrap();
    let mut analyzer = Analyzer::new();
    let (analyzed_fns, registry, _) = analyzer
        .analyze_program_with_global_signatures(&program, external_sigs)
        .unwrap();
    let mut codegen = CodeGenerator::new_for_module(registry, CompilationTarget::Rust);
    codegen.generate_program(&program, &analyzed_fns)
}

/// Compile a single `.wj` source string and return (generated_rust, success).
/// Does NOT panic on compilation failure — returns empty string with success=false.
pub fn compile_single_check(source: &str) -> (String, bool) {
    let tmp = TempDir::new().expect("tempdir");
    let wj_file = tmp.path().join("test.wj");
    fs::write(&wj_file, source).unwrap();
    let out_dir = tmp.path().join("build");

    let success = build_project(&wj_file, &out_dir, CompilationTarget::Rust, false).is_ok();

    let generated = fs::read_to_string(out_dir.join("test.rs")).unwrap_or_default();
    (generated, success)
}

// =============================================================================
// Single-file compilation (CLI — subprocess, tests CLI behavior)
// =============================================================================

/// Compile using the `wj` binary (CLI) and return (success, stdout, stderr).
pub fn compile_via_cli(source: &str) -> (bool, String, String) {
    let tmp = TempDir::new().expect("tempdir");
    let wj_file = tmp.path().join("test.wj");
    fs::write(&wj_file, source).unwrap();
    let out_dir = tmp.path().join("build");

    let output = Command::new(env!("CARGO_BIN_EXE_wj"))
        .args([
            "build",
            wj_file.to_str().unwrap(),
            "--output",
            out_dir.to_str().unwrap(),
            "--no-cargo",
        ])
        .output()
        .expect("Failed to run wj binary");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    (output.status.success(), stdout, stderr)
}

/// Compile using the `wj` binary and return (exit_code, stdout, stderr).
pub fn compile_via_cli_exit(source: &str) -> (i32, String, String) {
    let tmp = TempDir::new().expect("tempdir");
    let wj_file = tmp.path().join("test.wj");
    fs::write(&wj_file, source).unwrap();
    let out_dir = tmp.path().join("build");

    let output = Command::new(env!("CARGO_BIN_EXE_wj"))
        .args([
            "build",
            wj_file.to_str().unwrap(),
            "--output",
            out_dir.to_str().unwrap(),
            "--no-cargo",
        ])
        .output()
        .expect("Failed to run wj binary");

    let exit_code = output.status.code().unwrap_or(-1);
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    (exit_code, stdout, stderr)
}

/// Compile using the `wj` binary and return the generated Rust code.
/// Returns (generated_rust, success).
pub fn compile_via_cli_read(source: &str) -> (String, bool) {
    let tmp = TempDir::new().expect("tempdir");
    let wj_file = tmp.path().join("test.wj");
    fs::write(&wj_file, source).unwrap();
    let out_dir = tmp.path().join("build");

    let output = Command::new(env!("CARGO_BIN_EXE_wj"))
        .args([
            "build",
            wj_file.to_str().unwrap(),
            "--output",
            out_dir.to_str().unwrap(),
            "--no-cargo",
        ])
        .output()
        .expect("Failed to run wj binary");

    let generated = fs::read_to_string(out_dir.join("test.rs")).unwrap_or_default();
    (generated, output.status.success())
}

/// Compile via CLI and return (generated_rust, stderr).
/// Panics if compilation fails. Use when you need both generated code and warnings.
pub fn compile_via_cli_with_stderr(source: &str) -> (String, String) {
    let tmp = TempDir::new().expect("tempdir");
    let wj_file = tmp.path().join("test.wj");
    fs::write(&wj_file, source).unwrap();
    let out_dir = tmp.path().join("build");

    let output = Command::new(env!("CARGO_BIN_EXE_wj"))
        .args([
            "build",
            wj_file.to_str().unwrap(),
            "--output",
            out_dir.to_str().unwrap(),
            "--no-cargo",
        ])
        .output()
        .expect("Failed to run wj binary");

    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let generated = fs::read_to_string(out_dir.join("test.rs")).unwrap_or_else(|_| {
        panic!(
            "Failed to read generated file. Compiler stderr:\n{}",
            stderr
        )
    });

    (generated, stderr)
}

/// Compile via CLI and return (generated_rust, stdout, stderr).
/// Returns empty generated code if compilation fails.
pub fn compile_via_cli_full(source: &str) -> (String, String, String) {
    let tmp = TempDir::new().expect("tempdir");
    let wj_file = tmp.path().join("test.wj");
    fs::write(&wj_file, source).unwrap();
    let out_dir = tmp.path().join("build");

    let output = Command::new(env!("CARGO_BIN_EXE_wj"))
        .args([
            "build",
            wj_file.to_str().unwrap(),
            "--output",
            out_dir.to_str().unwrap(),
            "--no-cargo",
        ])
        .output()
        .expect("Failed to run wj binary");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let generated = fs::read_to_string(out_dir.join("test.rs")).unwrap_or_default();
    (generated, stdout, stderr)
}

// =============================================================================
// Named-file compilation
// =============================================================================

/// Compile a named `.wj` file (useful when testing specific filename handling).
pub fn compile_named(source: &str, filename: &str) -> String {
    let tmp = TempDir::new().expect("tempdir");
    let wj_file = tmp.path().join(filename);
    fs::write(&wj_file, source).unwrap();
    let out_dir = tmp.path().join("build");

    build_project(&wj_file, &out_dir, CompilationTarget::Rust, false)
        .unwrap_or_else(|e| panic!("Compilation of {} failed:\n{}", filename, e));

    let rs_name = filename.replace(".wj", ".rs");
    fs::read_to_string(out_dir.join(&rs_name))
        .unwrap_or_else(|e| panic!("Failed to read {}: {}", rs_name, e))
}

/// Compile a named `.wj` file and return (generated_rust, success).
pub fn compile_named_check(source: &str, filename: &str) -> (String, bool) {
    let tmp = TempDir::new().expect("tempdir");
    let wj_file = tmp.path().join(filename);
    fs::write(&wj_file, source).unwrap();
    let out_dir = tmp.path().join("build");

    let success = build_project(&wj_file, &out_dir, CompilationTarget::Rust, false).is_ok();

    let rs_name = filename.replace(".wj", ".rs");
    let generated = fs::read_to_string(out_dir.join(&rs_name)).unwrap_or_default();
    (generated, success)
}

// =============================================================================
// Multi-file project compilation
// =============================================================================

/// Create a temporary project directory with source files and return (TempDir, project_path).
/// The TempDir must be kept alive for the duration of the test.
pub fn create_temp_project(files: &[(&str, &str)]) -> (TempDir, PathBuf) {
    let tmp = TempDir::new().expect("tempdir");
    let project = tmp.path().to_path_buf();

    for (name, content) in files {
        let path = project.join(name);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, content).unwrap();
    }

    (tmp, project)
}

/// Compile a multi-file project and return a map of filename → generated Rust code.
/// Panics if compilation fails.
pub fn compile_project(files: &[(&str, &str)]) -> HashMap<String, String> {
    compile_project_result(files).unwrap_or_else(|e| panic!("Project compilation failed:\n{}", e))
}

/// Compile a multi-file project, returning Result with map of filename → generated code.
pub fn compile_project_result(files: &[(&str, &str)]) -> Result<HashMap<String, String>, String> {
    let tmp = TempDir::new().expect("tempdir");
    let src_dir = tmp.path().join("src");
    let out_dir = tmp.path().join("build");
    fs::create_dir_all(&src_dir).unwrap();

    for (name, content) in files {
        let path = src_dir.join(name);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, content).unwrap();
    }

    build_project(&src_dir, &out_dir, CompilationTarget::Rust, false).map_err(|e| e.to_string())?;

    let mut results = HashMap::new();
    for (name, _) in files {
        let rs_name = name.replace(".wj", ".rs");
        if let Ok(content) = fs::read_to_string(out_dir.join(&rs_name)) {
            results.insert(rs_name, content);
        }
    }
    Ok(results)
}

/// Compile a multi-file project using directory-based compilation.
/// Returns (HashMap of filename→code, success).
pub fn compile_project_dir(files: &[(&str, &str)]) -> (HashMap<String, String>, bool) {
    let tmp = TempDir::new().expect("tempdir");
    let src_dir = tmp.path().join("src");
    let out_dir = tmp.path().join("build");
    fs::create_dir_all(&src_dir).unwrap();

    for (name, content) in files {
        let path = src_dir.join(name);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, content).unwrap();
    }

    let output = Command::new(env!("CARGO_BIN_EXE_wj"))
        .args([
            "build",
            "--output",
            out_dir.to_str().unwrap(),
            src_dir.to_str().unwrap(),
            "--no-cargo",
        ])
        .output()
        .expect("Failed to run wj binary");

    let mut results = HashMap::new();
    if output.status.success() {
        for (name, _) in files {
            let rs_name = name.replace(".wj", ".rs");
            if let Ok(content) = fs::read_to_string(out_dir.join(&rs_name)) {
                results.insert(rs_name, content);
            }
        }
    }
    (results, output.status.success())
}

// =============================================================================
// Verification helpers
// =============================================================================

/// Verify generated Rust code compiles with rustc (type-checking only, no binary output).
pub fn verify_rust_compiles(rust_code: &str) -> Result<(), String> {
    let tmp = TempDir::new().expect("tempdir");
    let rs_file = tmp.path().join("verify.rs");
    fs::write(&rs_file, rust_code).unwrap();

    let output = Command::new("rustc")
        .arg("--edition=2021")
        .arg("--crate-type=lib")
        .arg("--emit=metadata")
        .arg("-o")
        .arg(tmp.path().join("verify.rmeta"))
        .arg(&rs_file)
        .output()
        .map_err(|e| format!("failed to run rustc: {}", e))?;

    if output.status.success() {
        Ok(())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).to_string())
    }
}

/// Verify generated Rust code compiles with external crate dependencies.
pub fn verify_rust_compiles_with_deps(
    rust_code: &str,
    deps: &[(&str, &Path)],
) -> Result<(), String> {
    let tmp = TempDir::new().expect("tempdir");
    let rs_file = tmp.path().join("verify.rs");
    fs::write(&rs_file, rust_code).unwrap();

    let mut cmd = Command::new("rustc");
    cmd.arg("--edition=2021")
        .arg("--crate-type=lib")
        .arg("--emit=metadata")
        .arg("-o")
        .arg(tmp.path().join("verify.rmeta"));

    for (name, path) in deps {
        cmd.arg("--extern")
            .arg(format!("{}={}", name, path.display()));
    }

    cmd.arg(&rs_file);

    let output = cmd
        .output()
        .map_err(|e| format!("failed to run rustc: {}", e))?;

    if output.status.success() {
        Ok(())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).to_string())
    }
}

// =============================================================================
// Fixture-based compilation (reads .wj file from tests/fixtures/)
// =============================================================================

/// Compile a test fixture file by name (without .wj extension).
/// Reads from tests/fixtures/{name}.wj and compiles it.
pub fn compile_fixture(fixture_name: &str) -> Result<String, String> {
    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join(format!("{}.wj", fixture_name));

    let tmp = TempDir::new().expect("tempdir");
    let out_dir = tmp.path().join("build");

    build_project(&fixture_path, &out_dir, CompilationTarget::Rust, false)
        .map_err(|e| e.to_string())?;

    let rs_name = format!("{}.rs", fixture_name);
    fs::read_to_string(out_dir.join(&rs_name))
        .map_err(|e| format!("Failed to read generated {}: {}", rs_name, e))
}

// =============================================================================
// Path helpers
// =============================================================================

/// Convert a path to TOML-safe string (forward slashes, no Windows \\?\ prefix).
pub fn path_to_toml_string(path: &Path) -> String {
    let s = path.display().to_string();
    let s = s.strip_prefix(r"\\?\").unwrap_or(&s);
    s.replace('\\', "/")
}

/// Get the path to the `wj` compiler binary.
pub fn wj_binary() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_wj"))
}