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
// wj build - Build Windjammer project
//
// This command compiles Windjammer source files to Rust.

use anyhow::Result;
use colored::*;
use std::path::Path;

/// Build options for JavaScript target
pub struct BuildOptions {
    pub minify: bool,
    pub tree_shake: bool,
    pub source_maps: bool,
    pub polyfills: bool,
    pub v8_optimize: bool,
}

#[allow(clippy::too_many_arguments)]
pub fn execute(
    path: &Path,
    output: Option<&Path>,
    _release: bool,
    target_str: &str,
    options: BuildOptions,
    check: bool,
    raw_errors: bool,
    fix: bool,
    verbose: bool,
    quiet: bool,
    filter_file: Option<&Path>,
    filter_type: Option<&str>,
    library: bool,
    module_file: bool,
    run_cargo: bool,
    enable_lint: bool,
    no_generate_cargo_toml: bool,
    metadata: &[String],
) -> Result<()> {
    let output_dir = output.unwrap_or_else(|| Path::new("./build"));

    println!(
        "{} Windjammer project from {:?} (target: {})",
        "Building".green().bold(),
        path,
        target_str
    );
    println!("Output: {:?}", output_dir);

    // Parse target string
    let target = match target_str.to_lowercase().as_str() {
        "rust" => crate::CompilationTarget::Rust,
        "javascript" | "js" => {
            // Use new JavaScript backend
            use crate::codegen::backend::{CodegenConfig, Target};
            let config = CodegenConfig {
                target: Target::JavaScript,
                output_dir: output_dir.to_path_buf(),
                minify: options.minify,
                tree_shake: options.tree_shake,
                source_maps: options.source_maps,
                polyfills: options.polyfills,
                v8_optimize: options.v8_optimize,
                ..Default::default()
            };
            return build_javascript(path, &config);
        }
        "go" | "golang" => {
            use crate::codegen::backend::{CodegenConfig, Target};
            let config = CodegenConfig {
                target: Target::Go,
                output_dir: output_dir.to_path_buf(),
                ..Default::default()
            };
            return build_go(path, &config);
        }
        "wasm" | "webassembly" => crate::CompilationTarget::Wasm,
        "wgsl" => {
            // Use WGSL backend for GPU shaders
            use crate::codegen::backend::{CodegenConfig, Target};
            let config = CodegenConfig {
                target: Target::Wgsl,
                output_dir: output_dir.to_path_buf(),
                ..Default::default()
            };
            return build_wgsl(path, &config);
        }
        _ => {
            anyhow::bail!(
                "Unknown target: {}. Use 'rust', 'go', 'javascript', 'wasm', or 'wgsl'",
                target_str
            );
        }
    };

    // Parse --metadata NAME=PATH into (name, path) pairs
    let external_metadata: Vec<(&str, &Path)> = metadata
        .iter()
        .filter_map(|s| {
            let (name, path_str) = s.split_once('=')?;
            Some((name, Path::new(path_str)))
        })
        .collect();

    crate::cargo_toml::set_skip_cargo_toml_generation(no_generate_cargo_toml);
    crate::build_project_ext(
        path,
        output_dir,
        target,
        enable_lint,
        library,
        &external_metadata,
    )?;

    // Generate mod.rs if requested
    if module_file {
        crate::build_utils::generate_mod_file(output_dir)?;
    }

    // Strip main() functions if library mode
    if library {
        crate::build_utils::strip_main_functions(output_dir)?;
    }

    println!("\n{} Transpilation complete!", "Success!".green().bold());

    // Run cargo check if requested
    if check {
        check_with_cargo(
            output_dir,
            raw_errors,
            fix,
            verbose,
            quiet,
            filter_file,
            filter_type,
        )?;
    }

    // Run cargo build automatically for Rust target (unless disabled)
    if (target_str == "rust") && run_cargo && !check {
        println!("\n{} Running cargo build...", "⚙️".bold());

        let cargo_status = std::process::Command::new("cargo")
            .arg("build")
            .current_dir(output_dir)
            .status();

        match cargo_status {
            Ok(status) if status.success() => {
                println!("{} Cargo build complete!", "".green().bold());
                println!(
                    "\n{} Your Windjammer project is ready!",
                    "Success!".green().bold()
                );
                println!("Run your project with:");
                println!("  cd {:?} && cargo run", output_dir);
            }
            Ok(status) => {
                println!(
                    "{} Cargo build failed with exit code: {:?}",
                    "".red().bold(),
                    status.code()
                );
                println!("\nYou can:");
                println!("  • Fix the errors and run: cargo build");
                println!("  • Or use: wj build --no-run-cargo to skip cargo build");
                return Err(anyhow::anyhow!("Cargo build failed"));
            }
            Err(e) => {
                println!("{} Failed to run cargo: {}", "".red().bold(), e);
                println!("\nMake sure cargo is installed:");
                println!("  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh");
                return Err(anyhow::anyhow!("Failed to execute cargo: {}", e));
            }
        }
    } else if target_str == "javascript" || target_str == "js" {
        println!(
            "\n{} Your JavaScript project is ready!",
            "Success!".green().bold()
        );
        println!("Run your project with:");
        println!("  node {:?}/output.js", output_dir);
    } else if !run_cargo && target_str == "rust" {
        println!(
            "\n{} Transpilation complete (cargo build skipped)!",
            "Success!".green().bold()
        );
        println!("Run cargo build manually:");
        println!("  cd {:?} && cargo build", output_dir);
    }

    Ok(())
}

fn build_javascript(path: &Path, config: &crate::codegen::backend::CodegenConfig) -> Result<()> {
    use crate::codegen;
    use crate::lexer::Lexer;
    use crate::parser::Parser;
    use std::fs;

    // Read source file
    let source = fs::read_to_string(path)?;

    // Lex and parse
    let mut lexer = Lexer::new(&source);
    let tokens = lexer.tokenize_with_locations();
    let mut parser = Parser::new(tokens);
    let program = parser
        .parse()
        .map_err(|e| anyhow::anyhow!("Parse error: {}", e))?;

    // Generate JavaScript
    let output = codegen::generate(&program, config.target, Some(config.clone()))?;

    // Create output directory
    fs::create_dir_all(&config.output_dir)?;

    // Write main output
    let output_path = config.output_dir.join("output.js");
    fs::write(&output_path, &output.source)?;
    println!("  {} {:?}", "Generated".green(), output_path);

    // Write TypeScript definitions if available
    if let Some(ref type_defs) = output.type_definitions {
        let types_path = config.output_dir.join("output.d.ts");
        fs::write(&types_path, type_defs)?;
        println!("  {} {:?}", "Generated".green(), types_path);
    }

    // Write additional files (package.json, etc.)
    for (filename, content) in &output.additional_files {
        let file_path = config.output_dir.join(filename);
        fs::write(&file_path, content)?;
        println!("  {} {:?}", "Generated".green(), file_path);
    }

    Ok(())
}

fn build_go(path: &Path, config: &crate::codegen::backend::CodegenConfig) -> Result<()> {
    use crate::codegen;
    use crate::lexer::Lexer;
    use crate::parser::Parser;
    use std::fs;

    let source = fs::read_to_string(path)?;

    let mut lexer = Lexer::new(&source);
    let tokens = lexer.tokenize_with_locations();
    let mut parser = Parser::new(tokens);
    let program = parser
        .parse()
        .map_err(|e| anyhow::anyhow!("Parse error: {}", e))?;

    let output = codegen::generate(&program, config.target, Some(config.clone()))?;

    fs::create_dir_all(&config.output_dir)?;

    let output_path = config.output_dir.join("main.go");
    fs::write(&output_path, &output.source)?;
    println!("  {} {:?}", "Generated".green(), output_path);

    for (filename, content) in &output.additional_files {
        let file_path = config.output_dir.join(filename);
        fs::write(&file_path, content)?;
        println!("  {} {:?}", "Generated".green(), file_path);
    }

    println!("\n{} Go compilation complete!", "Success!".green().bold());

    Ok(())
}

fn build_wgsl(path: &Path, config: &crate::codegen::backend::CodegenConfig) -> Result<()> {
    use std::fs;

    // Read source file
    let source = fs::read_to_string(path)?;

    // Detect .wjsl files - use WJSL transpiler (RFC syntax: @vertex, @fragment, etc.)
    // Note: .wjsl uses array<T, N> syntax; main Windjammer parser expects .wj syntax
    let (wgsl_source, additional_files) =
        if path.extension().and_then(|e| e.to_str()) == Some("wjsl") {
            let wgsl = crate::wjsl::transpile_wjsl(&source)?;
            (wgsl, Vec::new())
        } else {
            // Use Windjammer parser for .wj files
            use crate::codegen;
            use crate::lexer::Lexer;
            use crate::parser::Parser;

            let mut lexer = Lexer::new(&source);
            let tokens = lexer.tokenize_with_locations();
            let mut parser = Parser::new(tokens);
            let program = parser
                .parse()
                .map_err(|e| anyhow::anyhow!("Parse error: {}", e))?;

            let output = codegen::generate(&program, config.target, Some(config.clone()))?;
            (output.source, output.additional_files)
        };

    // Create output directory
    fs::create_dir_all(&config.output_dir)?;

    // Determine output filename from input
    let input_stem = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("shader");
    let output_path = config.output_dir.join(format!("{}.wgsl", input_stem));

    // Write WGSL output
    fs::write(&output_path, &wgsl_source)?;
    println!("  {} {:?}", "Generated".green(), output_path);

    // Write additional files if any
    for (filename, content) in &additional_files {
        let file_path = config.output_dir.join(filename);
        fs::write(&file_path, content)?;
        println!("  {} {:?}", "Generated".green(), file_path);
    }

    println!(
        "\n{} WGSL shader compilation complete!",
        "Success!".green().bold()
    );

    Ok(())
}

/// Run cargo build on the generated Rust code and display errors with source mapping
fn check_with_cargo(
    output_dir: &Path,
    show_raw_errors: bool,
    apply_fixes: bool,
    verbose: bool,
    quiet: bool,
    filter_file: Option<&Path>,
    filter_type: Option<&str>,
) -> Result<()> {
    use std::process::Command;

    // Error recovery loop: try up to 3 times if auto-fix is enabled
    let max_attempts = if apply_fixes { 3 } else { 1 };
    let mut last_error_count = 0;

    for attempt in 1..=max_attempts {
        if attempt > 1 {
            println!(
                "\n{} Retry {} of {}...",
                "Retrying".yellow().bold(),
                attempt,
                max_attempts
            );
        } else {
            println!("\n{} Rust compilation...", "Checking".cyan().bold());
        }

        let output = Command::new("cargo")
            .arg("build")
            .arg("--message-format=json")
            .current_dir(output_dir)
            .output()?;

        if output.status.success() {
            if attempt > 1 {
                println!(
                    "{} All errors fixed after {} attempt(s)!",
                    "Success!".green().bold(),
                    attempt
                );
            } else {
                println!("{} No Rust compilation errors!", "Success!".green().bold());
            }
            return Ok(());
        }

        // Combine stderr and stdout (cargo outputs to both)
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let combined_output = format!("{}{}", stderr, stdout);

        // If raw errors requested, show them and exit
        if show_raw_errors {
            println!("{} Rust compilation errors (raw):", "Error:".red().bold());
            println!("{}", combined_output);
            return Err(anyhow::anyhow!("Rust compilation failed"));
        }

        // Load all source maps from the output directory
        let source_maps = load_source_maps(output_dir)?;

        // Create error mapper with merged source maps
        let error_mapper = crate::error_mapper::ErrorMapper::new(source_maps);

        // Map rustc output to Windjammer diagnostics
        let mut wj_diagnostics = error_mapper.map_rustc_output(&combined_output);

        if wj_diagnostics.is_empty() {
            // Fallback: show raw output if we couldn't parse any diagnostics
            println!(
                "{} Could not parse Rust compilation errors. Showing raw output:",
                "Warning:".yellow().bold()
            );
            println!("{}", combined_output);
            return Err(anyhow::anyhow!("Rust compilation failed"));
        }

        // Apply filters
        if let Some(file_filter) = filter_file {
            wj_diagnostics.retain(|d| d.location.file == file_filter);
        }

        if let Some(type_filter) = filter_type {
            let filter_lower = type_filter.to_lowercase();
            wj_diagnostics.retain(|d| {
                matches!(
                    (&d.level, filter_lower.as_str()),
                    (crate::error_mapper::DiagnosticLevel::Error, "error")
                        | (crate::error_mapper::DiagnosticLevel::Warning, "warning")
                )
            });
        }

        // Group diagnostics by file
        let mut diagnostics_by_file: std::collections::HashMap<_, Vec<_>> =
            std::collections::HashMap::new();
        for diagnostic in &wj_diagnostics {
            diagnostics_by_file
                .entry(diagnostic.location.file.clone())
                .or_insert_with(Vec::new)
                .push(diagnostic);
        }

        // Count errors and warnings
        last_error_count = wj_diagnostics
            .iter()
            .filter(|d| matches!(d.level, crate::error_mapper::DiagnosticLevel::Error))
            .count();

        let warning_count = wj_diagnostics
            .iter()
            .filter(|d| matches!(d.level, crate::error_mapper::DiagnosticLevel::Warning))
            .count();

        // Display summary
        if quiet {
            // Quiet mode: only show counts
            if last_error_count > 0 {
                println!(
                    "\n{} {} error(s), {} warning(s)",
                    "Compilation failed:".red().bold(),
                    last_error_count,
                    warning_count
                );
            } else {
                println!(
                    "\n{} {} warning(s)",
                    "Compilation succeeded with warnings:".yellow().bold(),
                    warning_count
                );
            }
        } else {
            // Normal or verbose mode: show detailed output
            println!(
                "\n{} {} error(s), {} warning(s) found:\n",
                "Compilation failed:".red().bold(),
                last_error_count,
                warning_count
            );

            // Display diagnostics grouped by file
            for (file, file_diagnostics) in &diagnostics_by_file {
                println!("{} {}:", "In file".cyan().bold(), file.display());
                println!();

                for diagnostic in file_diagnostics {
                    let formatted = if verbose {
                        // Verbose mode: include all details
                        diagnostic.format()
                    } else {
                        // Normal mode: format as usual
                        diagnostic.format()
                    };
                    let colorized = colorize_diagnostic(&formatted, &diagnostic.level);
                    println!("{}", colorized);
                    println!(); // Blank line between errors
                }
            }
        }

        // Apply fixes if requested and not on last attempt
        if apply_fixes && attempt < max_attempts {
            println!("\n{} Applying automatic fixes...", "Fixing".green().bold());

            let fixes: Vec<_> = wj_diagnostics.iter().filter_map(|d| d.get_fix()).collect();

            if fixes.is_empty() {
                println!("{} No automatic fixes available", "Info:".cyan());
                // No fixes available, no point in retrying
                break;
            } else {
                println!("{} Found {} fixable error(s)", "Info:".cyan(), fixes.len());

                let applicator = crate::auto_fix::FixApplicator::new();
                match applicator.apply_fixes(&fixes) {
                    Ok(_) => {
                        println!(
                            "\n{} Applied {} fix(es)!",
                            "Success!".green().bold(),
                            fixes.len()
                        );
                        // Continue to next iteration to retry compilation
                        continue;
                    }
                    Err(e) => {
                        println!(
                            "{} Failed to apply some fixes: {}",
                            "Warning:".yellow().bold(),
                            e
                        );
                        // Failed to apply fixes, no point in retrying
                        break;
                    }
                }
            }
        } else {
            // No auto-fix or last attempt, break out of loop
            break;
        }
    }

    // If we get here, compilation failed
    Err(anyhow::anyhow!(
        "Rust compilation failed with {} error(s)",
        last_error_count
    ))
}

/// Load and merge all source maps from the output directory
fn load_source_maps(output_dir: &Path) -> Result<crate::source_map::SourceMap> {
    use std::fs;

    let mut merged_map = crate::source_map::SourceMap::new();
    let mut map_count = 0;
    let mut mapping_count = 0;

    // Find all .rs.map files in the output directory
    if let Ok(entries) = fs::read_dir(output_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("map") {
                // Check if this is a .rs.map file (not just any .map file)
                if let Some(stem) = path.file_stem() {
                    if let Some(stem_str) = stem.to_str() {
                        if !stem_str.ends_with(".rs") {
                            continue;
                        }
                    }
                }

                // Load this source map
                if let Ok(map) = crate::source_map::SourceMap::load_from_file(&path) {
                    // Get the corresponding .rs file path
                    let rust_file = path.with_extension("").with_extension("rs");

                    // Merge all mappings from this source map
                    let mappings = map.mappings_for_rust_file(&rust_file);
                    for mapping in mappings {
                        merged_map.add_mapping(
                            mapping.rust_file.clone(),
                            mapping.rust_line,
                            mapping.rust_column,
                            mapping.wj_file.clone(),
                            mapping.wj_line,
                            mapping.wj_column,
                        );
                        mapping_count += 1;
                    }
                    map_count += 1;
                }
            }
        }
    }

    if map_count == 0 {
        println!(
            "{} No source maps found. Error locations may be inaccurate.",
            "Warning:".yellow().bold()
        );
    } else {
        println!(
            "{} Loaded {} source map(s) with {} mapping(s)",
            "Info:".cyan(),
            map_count,
            mapping_count
        );
    }

    Ok(merged_map)
}

/// Colorize diagnostic output based on level
fn colorize_diagnostic(text: &str, _level: &crate::error_mapper::DiagnosticLevel) -> String {
    use colored::*;

    let mut result = String::new();
    for line in text.lines() {
        if line.starts_with("error:") || line.starts_with("Error:") {
            result.push_str(&line.red().bold().to_string());
        } else if line.starts_with("warning:") || line.starts_with("Warning:") {
            result.push_str(&line.yellow().bold().to_string());
        } else if line.starts_with("help:") || line.starts_with("Help:") {
            result.push_str(&line.cyan().to_string());
        } else if line.starts_with("note:") || line.starts_with("Note:") {
            result.push_str(&line.blue().to_string());
        } else if line.contains("^") {
            // Error pointer line
            result.push_str(&line.red().to_string());
        } else if line.starts_with("  -->") || line.starts_with(" -->") {
            // Location line
            result.push_str(&line.cyan().to_string());
        } else {
            result.push_str(line);
        }
        result.push('\n');
    }

    // Remove trailing newline if present
    if result.ends_with('\n') {
        result.pop();
    }

    result
}