reluxscript 0.1.4

Write AST transformations once. Compile to Babel, SWC, and beyond.
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! ReluxScript Compiler CLI

use clap::{Parser as ClapParser, Subcommand};
use std::fs;
use std::path::PathBuf;

use reluxscript::{Lexer, Parser, analyze_with_base_dir, TokenRewriter};

#[cfg(feature = "codegen")]
use reluxscript::{generate, Target, lower};

#[derive(ClapParser)]
#[command(name = "reluxscript")]
#[command(about = "ReluxScript compiler - compile to Babel and SWC plugins")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a new ReluxScript plugin
    New {
        /// Plugin name
        name: String,
    },
    /// Tokenize a ReluxScript file (for debugging)
    Lex {
        /// Input file
        file: PathBuf,
    },
    /// Parse a ReluxScript file (for debugging)
    Parse {
        /// Input file
        file: PathBuf,
    },
    /// Check a ReluxScript file for errors
    Check {
        /// Input file
        file: PathBuf,
        /// Automatically fix common issues (path-qualified if-let patterns)
        #[arg(long, default_value = "true")]
        autofix: bool,
    },
    /// Build a ReluxScript project
    #[cfg(feature = "codegen")]
    Build {
        /// Input file
        file: PathBuf,
        /// Target platform (babel, swc, both)
        #[arg(short, long, default_value = "both")]
        target: String,
        /// Output directory
        #[arg(short, long, default_value = "dist")]
        output: PathBuf,
        /// Automatically fix common issues (path-qualified if-let patterns)
        #[arg(long, default_value = "true")]
        autofix: bool,
        /// Dump decorated AST for SWC (debug mode - before rewriting)
        #[arg(long)]
        dump_decorated_ast: bool,
        /// Dump rewritten AST for SWC (debug mode - after rewriting)
        #[arg(long)]
        dump_rewritten_ast: bool,
    },
    /// Build a standalone module file (like a C# DLL - just functions, structs, no plugin wrapper)
    #[cfg(feature = "codegen")]
    BuildModule {
        /// Input file
        file: PathBuf,
        /// Target platform (swc only for now)
        #[arg(short, long, default_value = "swc")]
        target: String,
        /// Output directory
        #[arg(short, long, default_value = "dist")]
        output: PathBuf,
        /// Dump decorated AST (debug mode)
        #[arg(long)]
        dump_ast: bool,
    },
    /// Fix common issues in ReluxScript files (rewrites in-place)
    Fix {
        /// Input file(s)
        files: Vec<PathBuf>,
        /// Show what would be changed without writing
        #[arg(long)]
        dry_run: bool,
    },
    /// Build a project from a manifest file (builds modules in dependency order, then plugin/writer)
    #[cfg(feature = "codegen")]
    BuildProject {
        /// Path to lux.manifest.json
        manifest: PathBuf,
        /// Target platform
        #[arg(short, long, default_value = "swc")]
        target: String,
    },
}

fn main() {
    let cli = <Cli as ClapParser>::parse();

    match cli.command {
        Commands::New { name } => {
            // Create plugin file
            let plugin_file = PathBuf::from(format!("{}.lux", name));

            if plugin_file.exists() {
                eprintln!("Error: {} already exists", plugin_file.display());
                std::process::exit(1);
            }

            // Create a basic plugin template
            let template = format!(r#"// {name} - A ReluxScript plugin
// Edit this file to implement your AST transformation

plugin {name} {{
    fn visit_call_expression(node: &mut CallExpression, ctx: &Context) {{
        // Example: Remove console.log calls
        // if matches!(node.callee, "console.log") {{
        //     *node = Statement::empty();
        // }}
    }}
}}
"#, name = name);

            if let Err(e) = fs::write(&plugin_file, template) {
                eprintln!("Error creating plugin file: {}", e);
                std::process::exit(1);
            }

            println!("Created new plugin: {}", plugin_file.display());
            println!("\nNext steps:");
            println!("  1. Edit {} to implement your transformation", plugin_file.display());
            println!("  2. Build to Babel: relux build {} --target babel", plugin_file.display());
            println!("  3. Build to SWC: relux build {} --target swc", plugin_file.display());
        }
        Commands::Lex { file } => {
            let source = match fs::read_to_string(&file) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("Error reading file: {}", e);
                    std::process::exit(1);
                }
            };

            let mut lexer = Lexer::new(&source);
            let tokens = lexer.tokenize();

            println!("Tokens for {:?}:", file);
            println!("{:-<60}", "");
            for token in &tokens {
                println!(
                    "{:>4}:{:<3} {:?}",
                    token.span.line,
                    token.span.column,
                    token.kind
                );
            }
            println!("{:-<60}", "");
            println!("Total tokens: {}", tokens.len());
        }
        Commands::Parse { file } => {
            let source = match fs::read_to_string(&file) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("Error reading file: {}", e);
                    std::process::exit(1);
                }
            };

            let mut lexer = Lexer::new(&source);
            let tokens = lexer.tokenize();
            let mut parser = Parser::new_with_source(tokens, source.clone());

            match parser.parse() {
                Ok(program) => {
                    println!("Successfully parsed {:?}", file);
                    println!("{:-<60}", "");
                    println!("{:#?}", program);
                }
                Err(e) => {
                    eprintln!("Parse error at {}:{}: {}", e.span.line, e.span.column, e.message);
                    std::process::exit(1);
                }
            }
        }
        Commands::Check { file, autofix } => {
            let source = match fs::read_to_string(&file) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("Error reading file: {}", e);
                    std::process::exit(1);
                }
            };

            let mut lexer = Lexer::new(&source);
            let mut tokens = lexer.tokenize();

            // Apply autofix if requested
            if autofix {
                let rewriter = TokenRewriter::new(tokens);
                let (fixed_tokens, fixes_applied) = rewriter.rewrite();
                tokens = fixed_tokens;
                if fixes_applied > 0 {
                    println!("Autofix: Applied {} fix(es)", fixes_applied);
                }
            }

            let mut parser = Parser::new_with_source(tokens, source.clone());

            let mut program = match parser.parse() {
                Ok(p) => p,
                Err(e) => {
                    eprintln!("Parse error at {}:{}: {}", e.span.line, e.span.column, e.message);
                    std::process::exit(1);
                }
            };

            // AST lowering (transform matches! and deep chains to pattern matching)
            // This MUST run before semantic analysis so pattern bindings are visible
            lower(&mut program);

            // Get base directory from file path
            let base_dir = file.parent().unwrap_or_else(|| std::path::Path::new(".")).to_path_buf();
            let result = analyze_with_base_dir(&program, base_dir);

            // Print errors
            for error in &result.errors {
                eprintln!(
                    "error[{}]: {} at {}:{}",
                    error.code, error.message, error.span.line, error.span.column
                );
                if let Some(ref hint) = error.hint {
                    eprintln!("  help: {}", hint);
                }
            }

            // Print warnings
            for warning in &result.warnings {
                eprintln!(
                    "warning[{}]: {} at {}:{}",
                    warning.code, warning.message, warning.span.line, warning.span.column
                );
                if let Some(ref hint) = warning.hint {
                    eprintln!("  help: {}", hint);
                }
            }

            if result.errors.is_empty() {
                println!("Check passed: {:?}", file);
                if !result.warnings.is_empty() {
                    println!("  {} warning(s)", result.warnings.len());
                }
            } else {
                eprintln!("Check failed: {} error(s)", result.errors.len());
                std::process::exit(1);
            }
        }
        #[cfg(feature = "codegen")]
        Commands::Build { file, target, output, autofix, dump_decorated_ast, dump_rewritten_ast } => {
            let source = match fs::read_to_string(&file) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("Error reading file: {}", e);
                    std::process::exit(1);
                }
            };

            // Parse
            let mut lexer = Lexer::new(&source);
            let mut tokens = lexer.tokenize();

            // Apply autofix if requested
            if autofix {
                let rewriter = TokenRewriter::new(tokens);
                let (fixed_tokens, fixes_applied) = rewriter.rewrite();
                tokens = fixed_tokens;
                if fixes_applied > 0 {
                    println!("Autofix: Applied {} fix(es)", fixes_applied);
                }
            }

            let mut parser = Parser::new_with_source(tokens, source.clone());

            let mut program = match parser.parse() {
                Ok(p) => p,
                Err(e) => {
                    eprintln!("Parse error at {}:{}: {}", e.span.line, e.span.column, e.message);
                    std::process::exit(1);
                }
            };

            // AST lowering (transform matches! and deep chains to pattern matching)
            // This MUST run before semantic analysis so pattern bindings are visible
            lower(&mut program);

            // Semantic analysis
            let base_dir = file.parent().unwrap_or_else(|| std::path::Path::new(".")).to_path_buf();
            let result = analyze_with_base_dir(&program, base_dir.clone());
            if !result.errors.is_empty() {
                for error in &result.errors {
                    eprintln!(
                        "error[{}]: {} at {}:{}",
                        error.code, error.message, error.span.line, error.span.column
                    );
                }
                eprintln!("Build failed: {} error(s)", result.errors.len());
                std::process::exit(1);
            }

            // Determine target
            let target_enum = match target.as_str() {
                "babel" => Target::Babel,
                "swc" => Target::Swc,
                "both" => Target::Both,
                _ => {
                    eprintln!("Unknown target: {}. Use 'babel', 'swc', or 'both'", target);
                    std::process::exit(1);
                }
            };

            // Dump decorated AST if requested (SWC only) - skip codegen
            if dump_decorated_ast {
                if target_enum == Target::Babel {
                    eprintln!("Error: --dump-decorated-ast only works with --target swc");
                    std::process::exit(1);
                }

                use reluxscript::SwcDecorator;
                // Use semantic type environment for decoration
                let mut decorator = SwcDecorator::with_semantic_types(result.type_env);
                let decorated = decorator.decorate_program(&program);

                println!("\n=== DECORATED AST FOR SWC (BEFORE REWRITING) ===");
                println!("{:#?}", decorated);
                println!("=== END DECORATED AST ===\n");

                // Exit early - don't run codegen
                return;
            }

            // Dump rewritten AST if requested (SWC only) - skip codegen
            if dump_rewritten_ast {
                if target_enum == Target::Babel {
                    eprintln!("Error: --dump-rewritten-ast only works with --target swc");
                    std::process::exit(1);
                }

                use reluxscript::{SwcDecorator, SwcRewriter};
                // Use semantic type environment for decoration
                let mut decorator = SwcDecorator::with_semantic_types(result.type_env);
                let decorated = decorator.decorate_program(&program);

                // Rewrite the decorated AST
                let mut rewriter = SwcRewriter::new();
                let rewritten = rewriter.rewrite_program(decorated);

                println!("\n=== REWRITTEN AST FOR SWC (AFTER PATTERN DESUGARING) ===");
                println!("{:#?}", rewritten);
                println!("=== END REWRITTEN AST ===\n");

                // Exit early - don't run codegen
                return;
            }

            // Generate code (use generate_with_types_and_base_dir to get proper module imports)
            let generated = reluxscript::codegen::generate_with_types_and_base_dir(
                &program,
                result.type_env.clone(),
                target_enum,
                base_dir.clone(),
            );

            // Create output directory
            if let Err(e) = fs::create_dir_all(&output) {
                eprintln!("Error creating output directory: {}", e);
                std::process::exit(1);
            }

            // Write generated files
            if let Some(babel_code) = generated.babel {
                let babel_path = output.join("index.js");
                if let Err(e) = fs::write(&babel_path, babel_code) {
                    eprintln!("Error writing Babel output: {}", e);
                    std::process::exit(1);
                }
                println!("Generated Babel plugin: {:?}", babel_path);

                // Validate generated JS syntax with node --check
                let node_check = std::process::Command::new("node")
                    .arg("--check")
                    .arg(&babel_path)
                    .output();

                match node_check {
                    Ok(output) if !output.status.success() => {
                        eprintln!("\n[VALIDATION ERROR] Generated Babel plugin has syntax errors:");
                        eprintln!("{}", String::from_utf8_lossy(&output.stderr));
                        eprintln!("\nCodegen produced invalid JavaScript. This is a compiler bug.");
                        std::process::exit(1);
                    }
                    Ok(_) => {
                        println!("✓ Babel output validated successfully");
                    }
                    Err(_) => {
                        // Node.js not available, skip validation with warning
                        eprintln!("Warning: Could not validate JS syntax (node not found)");
                    }
                }
            }

            if let Some(swc_code) = generated.swc {
                let swc_path = output.join("lib.rs");
                if let Err(e) = fs::write(&swc_path, &swc_code) {
                    eprintln!("Error writing SWC output: {}", e);
                    std::process::exit(1);
                }
                println!("Generated SWC plugin: {:?}", swc_path);

                // Write imported module files
                for (module_name, module_code, _imports, _is_transitive) in &generated.swc_modules {
                    let module_path = output.join(format!("{}.rs", module_name));
                    if let Err(e) = fs::write(&module_path, module_code) {
                        eprintln!("Error writing module '{}': {}", module_name, e);
                        std::process::exit(1);
                    }
                    println!("Generated module: {:?}", module_path);
                }

                // Generate a minimal Cargo.toml for validation
                let cargo_toml_path = output.join("Cargo.toml");
                let needs_cargo_toml = !cargo_toml_path.exists();

                if needs_cargo_toml {
                    let cargo_toml_content = r#"[package]
name = "swc-plugin-temp"
version = "0.1.0"
edition = "2021"

[lib]
path = "lib.rs"
crate-type = ["cdylib", "rlib"]

[dependencies]
swc_common = "17.0.1"
swc_ecma_ast = "18.0.0"
swc_ecma_visit = "18.0.1"
swc_ecma_parser = "27.0.3"
swc_ecma_codegen = "20.0.0"
regex = "1.11.1"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145"
"#;
                    if let Err(e) = fs::write(&cargo_toml_path, cargo_toml_content) {
                        eprintln!("Warning: Could not create Cargo.toml for validation: {}", e);
                    }
                }

                // Validate generated Rust code with cargo check
                // Set CFLAGS="" to bypass C compiler detection for dependencies like stacker
                let cargo_check = std::process::Command::new("cargo")
                    .arg("check")
                    .arg("--manifest-path")
                    .arg(&cargo_toml_path)
                    .arg("--lib")
                    .env("CFLAGS", "")
                    .env("CXXFLAGS", "")
                    .env("CC", "")
                    .env("CXX", "")
                    .output();

                match cargo_check {
                    Ok(output) if !output.status.success() => {
                        eprintln!("\n[VALIDATION ERROR] Generated SWC plugin has compilation errors:");
                        eprintln!("{}", String::from_utf8_lossy(&output.stderr));
                        eprintln!("\nCodegen produced invalid Rust code. This is a compiler bug.");

                        // Clean up temporary Cargo.toml if we created it
                        if needs_cargo_toml {
                            let _ = fs::remove_file(&cargo_toml_path);
                        }

                        std::process::exit(1);
                    }
                    Ok(_) => {
                        println!("✓ SWC output validated successfully");

                        // Clean up temporary Cargo.toml if we created it
                        if needs_cargo_toml {
                            let _ = fs::remove_file(&cargo_toml_path);
                        }
                    }
                    Err(_) => {
                        // Cargo not available, skip validation with warning
                        eprintln!("Warning: Could not validate Rust syntax (cargo not found)");

                        // Clean up temporary Cargo.toml if we created it
                        if needs_cargo_toml {
                            let _ = fs::remove_file(&cargo_toml_path);
                        }
                    }
                }
            }

            println!("Build complete!");
        }
        #[cfg(feature = "codegen")]
        Commands::BuildModule { file, target, output, dump_ast } => {
            // Build a standalone module file (like a DLL - just functions/structs, no plugin wrapper)
            let source = match fs::read_to_string(&file) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("Error reading file: {}", e);
                    std::process::exit(1);
                }
            };

            // Parse
            let mut lexer = Lexer::new(&source);
            let tokens = lexer.tokenize();
            let mut parser = Parser::new_with_source(tokens, source.clone());

            let mut program = match parser.parse() {
                Ok(p) => p,
                Err(e) => {
                    eprintln!("Parse error at {}:{}: {}", e.span.line, e.span.column, e.message);
                    std::process::exit(1);
                }
            };

            // AST lowering
            lower(&mut program);

            // Semantic analysis
            let base_dir = file.parent().unwrap_or_else(|| std::path::Path::new(".")).to_path_buf();
            let result = analyze_with_base_dir(&program, base_dir.clone());
            if !result.errors.is_empty() {
                for error in &result.errors {
                    eprintln!(
                        "error[{}]: {} at {}:{}",
                        error.code, error.message, error.span.line, error.span.column
                    );
                }
                eprintln!("Build failed: {} error(s)", result.errors.len());
                std::process::exit(1);
            }

            // For now, only SWC is supported for modules
            if target != "swc" {
                eprintln!("Error: build-module currently only supports --target swc");
                std::process::exit(1);
            }

            // Generate SWC module code
            use reluxscript::{SwcDecorator, SwcRewriter};
            use reluxscript::codegen::SwcEmitter;

            let mut decorator = SwcDecorator::with_semantic_types(result.type_env);
            let decorated = decorator.decorate_program(&program);

            if dump_ast {
                println!("\n=== DECORATED MODULE AST ===");
                println!("{:#?}", decorated);
                println!("=== END DECORATED AST ===\n");
                return;
            }

            // Rewrite
            let mut rewriter = SwcRewriter::new();
            let rewritten = rewriter.rewrite_program(decorated);

            // Emit with base_dir so modules can import other compiled modules
            let mut emitter = SwcEmitter::with_base_dir(base_dir.clone());
            let swc_code = emitter.emit_program(&rewritten);

            // Create output directory
            if let Err(e) = fs::create_dir_all(&output) {
                eprintln!("Error creating output directory: {}", e);
                std::process::exit(1);
            }

            // Write generated file
            let swc_path = output.join("lib.rs");
            if let Err(e) = fs::write(&swc_path, &swc_code) {
                eprintln!("Error writing SWC output: {}", e);
                std::process::exit(1);
            }
            println!("Generated SWC module: {:?}", swc_path);

            // Write any imported module files (transitive dependencies)
            for (module_name, module_code, _imports, _is_transitive) in emitter.get_imported_modules() {
                let module_path = output.join(format!("{}.rs", module_name));
                if let Err(e) = fs::write(&module_path, module_code) {
                    eprintln!("Error writing module file: {}", e);
                    std::process::exit(1);
                }
                println!("Generated module dependency: {:?}", module_path);
            }

            // Generate .luxon manifest (with base_dir for re-exports)
            let module_name = file.file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("module")
                .to_string();
            let manifest = reluxscript::luxon::extract_manifest_with_base_dir(&program, module_name, &base_dir);
            let luxon_path = output.join("lib.luxon");
            if let Err(e) = manifest.save(&luxon_path) {
                eprintln!("Warning: Failed to write .luxon manifest: {}", e);
            } else {
                println!("Generated manifest: {:?}", luxon_path);
            }

            println!("Build complete!");
        }
        Commands::Fix { files, dry_run } => {
            let mut total_fixes = 0;
            let mut files_changed = 0;

            for file in &files {
                let source = match fs::read_to_string(file) {
                    Ok(s) => s,
                    Err(e) => {
                        eprintln!("Error reading {:?}: {}", file, e);
                        continue;
                    }
                };

                // Tokenize
                let mut lexer = Lexer::new(&source);
                let tokens = lexer.tokenize();

                // Apply fixes
                let rewriter = TokenRewriter::new(tokens);
                let (fixed_tokens, fixes_applied) = rewriter.rewrite();

                if fixes_applied == 0 {
                    if files.len() == 1 {
                        println!("No fixes needed for {:?}", file);
                    }
                    continue;
                }

                files_changed += 1;
                total_fixes += fixes_applied;

                println!("{:?}: {} fix(es) applied", file, fixes_applied);

                if !dry_run {
                    // We need to regenerate source from tokens
                    // For now, we'll use a simple approach that works for our use case
                    // In a production system, you'd want a proper token-to-source converter

                    // Since we're rewriting if-let to match, we need to actually parse and
                    // verify it works, then write it back
                    // For simplicity, let's parse with the fixed tokens to verify it works
                    let mut parser = Parser::new_with_source(fixed_tokens, source.clone());

                    match parser.parse() {
                        Ok(_) => {
                            // The fix worked! But we can't write it back yet because
                            // we need a token-to-source converter
                            println!("  Warning: File NOT rewritten - token-to-source conversion not yet implemented");
                            println!("  The fixes would have been applied, but source regeneration is needed");
                        }
                        Err(e) => {
                            eprintln!("  Error: Fix validation failed: {}", e.message);
                            eprintln!("  File NOT modified");
                        }
                    }
                } else {
                    println!("  (dry-run: file not modified)");
                }
            }

            println!("\n{} file(s) processed, {} total fix(es)", files.len(), total_fixes);
            if files_changed > 0 {
                if dry_run {
                    println!("Run without --dry-run to apply changes");
                } else {
                    println!("Note: Actual file rewriting requires token-to-source conversion (not yet implemented)");
                    println!("Use --autofix with check/build commands to apply fixes during compilation");
                }
            }
        }
        #[cfg(feature = "codegen")]
        Commands::BuildProject { manifest, target } => {
            use reluxscript::manifest::LuxManifest;

            // Load and validate manifest
            let manifest_path = manifest.clone();
            let manifest_dir = manifest_path.parent().unwrap_or_else(|| std::path::Path::new("."));

            let lux_manifest = match LuxManifest::load(&manifest_path) {
                Ok(m) => m,
                Err(e) => {
                    eprintln!("Error loading manifest: {}", e);
                    std::process::exit(1);
                }
            };

            if let Err(e) = lux_manifest.validate() {
                eprintln!("Manifest validation error: {}", e);
                std::process::exit(1);
            }

            // Get sorted modules
            let sorted_modules = match lux_manifest.sorted_modules() {
                Ok(m) => m,
                Err(e) => {
                    eprintln!("Dependency error: {}", e);
                    std::process::exit(1);
                }
            };

            println!("Building project from {:?}", manifest_path);
            println!("Build order: {}", sorted_modules.iter().map(|m| m.name.as_str()).collect::<Vec<_>>().join(" → "));

            // Build each module in order
            for module in &sorted_modules {
                let module_path = manifest_dir.join(&module.path);
                let output_path = manifest_dir.join(&module.output);

                println!("\n[{}] Building module...", module.name);

                if let Err(e) = build_module_internal(&module_path, &output_path, &target) {
                    eprintln!("Error building module '{}': {}", module.name, e);
                    std::process::exit(1);
                }

                println!("[{}] ✓ Built successfully", module.name);
            }

            // Build plugin or writer if specified
            if let Some(ref plugin) = lux_manifest.plugin {
                let plugin_path = manifest_dir.join(&plugin.path);
                let output_path = manifest_dir.join(&plugin.output);

                println!("\n[plugin] Building plugin...");

                if let Err(e) = build_plugin_internal(&plugin_path, &output_path, &target) {
                    eprintln!("Error building plugin: {}", e);
                    std::process::exit(1);
                }

                println!("[plugin] ✓ Built successfully");
            }

            if let Some(ref writer) = lux_manifest.writer {
                let writer_path = manifest_dir.join(&writer.path);
                let output_path = manifest_dir.join(&writer.output);

                println!("\n[writer] Building writer...");

                if let Err(e) = build_plugin_internal(&writer_path, &output_path, &target) {
                    eprintln!("Error building writer: {}", e);
                    std::process::exit(1);
                }

                println!("[writer] ✓ Built successfully");
            }

            println!("\n✓ Project build complete!");
        }
    }
}

/// Internal function to build a module (extracted from BuildModule command)
#[cfg(feature = "codegen")]
fn build_module_internal(file: &std::path::Path, output: &std::path::Path, target: &str) -> Result<(), String> {
    use reluxscript::{Lexer, Parser, lower, analyze_with_base_dir};
    use reluxscript::codegen::SwcEmitter;
    use reluxscript::{SwcDecorator, SwcRewriter};

    let source = fs::read_to_string(file)
        .map_err(|e| format!("Failed to read file: {}", e))?;

    let mut lexer = Lexer::new(&source);
    let tokens = lexer.tokenize();
    let mut parser = Parser::new_with_source(tokens, source.clone());

    let mut program = parser.parse()
        .map_err(|e| format!("Parse error at {}:{}: {}", e.span.line, e.span.column, e.message))?;

    lower(&mut program);

    let base_dir = file.parent().unwrap_or_else(|| std::path::Path::new(".")).to_path_buf();
    let result = analyze_with_base_dir(&program, base_dir.clone());

    if !result.errors.is_empty() {
        let errors: Vec<_> = result.errors.iter()
            .map(|e| format!("{}:{}: {}", e.span.line, e.span.column, e.message))
            .collect();
        return Err(format!("Semantic errors:\n{}", errors.join("\n")));
    }

    if target != "swc" {
        return Err("build-module currently only supports --target swc".to_string());
    }

    let mut decorator = SwcDecorator::with_semantic_types(result.type_env);
    let decorated = decorator.decorate_program(&program);

    let mut rewriter = SwcRewriter::new();
    let rewritten = rewriter.rewrite_program(decorated);

    let mut emitter = SwcEmitter::with_base_dir(base_dir.clone());
    let swc_code = emitter.emit_program(&rewritten);

    fs::create_dir_all(output)
        .map_err(|e| format!("Failed to create output directory: {}", e))?;

    let swc_path = output.join("lib.rs");
    fs::write(&swc_path, &swc_code)
        .map_err(|e| format!("Failed to write output: {}", e))?;

    // Write imported module files
    for (module_name, module_code, _imports, _is_transitive) in emitter.get_imported_modules() {
        let module_path = output.join(format!("{}.rs", module_name));
        fs::write(&module_path, module_code)
            .map_err(|e| format!("Failed to write module '{}': {}", module_name, e))?;
    }

    // Generate .luxon manifest
    let module_name = file.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("module")
        .to_string();
    let manifest = reluxscript::luxon::extract_manifest_with_base_dir(&program, module_name, &base_dir);
    let luxon_path = output.join("lib.luxon");
    if let Err(e) = manifest.save(&luxon_path) {
        eprintln!("Warning: Failed to write .luxon manifest: {}", e);
    }

    Ok(())
}

/// Internal function to build a plugin/writer (extracted from Build command)
#[cfg(feature = "codegen")]
fn build_plugin_internal(file: &std::path::Path, output: &std::path::Path, target: &str) -> Result<(), String> {
    use reluxscript::{Lexer, Parser, lower, analyze_with_base_dir};
    use reluxscript::codegen::{BabelGenerator, SwcEmitter, generate_with_types_and_base_dir};
    use reluxscript::{SwcDecorator, SwcRewriter, Target};

    let source = fs::read_to_string(file)
        .map_err(|e| format!("Failed to read file: {}", e))?;

    let mut lexer = Lexer::new(&source);
    let tokens = lexer.tokenize();
    let mut parser = Parser::new_with_source(tokens, source.clone());

    let mut program = parser.parse()
        .map_err(|e| format!("Parse error at {}:{}: {}", e.span.line, e.span.column, e.message))?;

    lower(&mut program);

    let base_dir = file.parent().unwrap_or_else(|| std::path::Path::new(".")).to_path_buf();
    let result = analyze_with_base_dir(&program, base_dir.clone());

    if !result.errors.is_empty() {
        let errors: Vec<_> = result.errors.iter()
            .map(|e| format!("{}:{}: {}", e.span.line, e.span.column, e.message))
            .collect();
        return Err(format!("Semantic errors:\n{}", errors.join("\n")));
    }

    fs::create_dir_all(output)
        .map_err(|e| format!("Failed to create output directory: {}", e))?;

    let build_target = match target {
        "babel" => Target::Babel,
        "swc" => Target::Swc,
        "both" => Target::Both,
        _ => return Err(format!("Unknown target: {}", target)),
    };

    let generated = generate_with_types_and_base_dir(&program, result.type_env, build_target, base_dir);

    // Write Babel output
    if let Some(ref babel) = generated.babel {
        let babel_path = output.join("index.js");
        fs::write(&babel_path, babel)
            .map_err(|e| format!("Failed to write Babel output: {}", e))?;
    }

    // Write SWC output
    if let Some(ref swc) = generated.swc {
        let swc_path = output.join("lib.rs");
        fs::write(&swc_path, swc)
            .map_err(|e| format!("Failed to write SWC output: {}", e))?;

        // Write imported module files
        for (module_name, module_code, _imports, _is_transitive) in &generated.swc_modules {
            let module_path = output.join(format!("{}.rs", module_name));
            fs::write(&module_path, module_code)
                .map_err(|e| format!("Failed to write module '{}': {}", module_name, e))?;
        }
    }

    Ok(())
}