windjammer 0.47.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
//! 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;
use tempfile::TempDir;
use windjammer::compiler::build_project;
use windjammer::CompilationTarget;

// =============================================================================
// 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 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"))
}