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
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
//! Top-level program emission: imports, items, FFI, implicit `use`, and import deduplication.

#![allow(clippy::collapsible_if)]
#![allow(clippy::collapsible_match)]

use crate::analyzer::*;
use crate::codegen::rust::expression_helpers;
use crate::codegen::rust::generator::CodeGenerator;
use crate::parser::*;
use crate::CompilationTarget;

impl<'ast> CodeGenerator<'ast> {
    fn dedupe_rust_import_lines(block: &str) -> String {
        let mut seen_private: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut seen_pub: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut out_lines: Vec<String> = Vec::new();
        for line in block.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with("//") {
                out_lines.push(line.to_string());
                continue;
            }
            if trimmed.starts_with("#[") {
                out_lines.push(line.to_string());
                continue;
            }
            let (is_pub, after_use) = if let Some(r) = trimmed.strip_prefix("pub use ") {
                (true, r)
            } else if let Some(r) = trimmed.strip_prefix("use ") {
                (false, r)
            } else {
                out_lines.push(line.to_string());
                continue;
            };
            let seen = if is_pub {
                &mut seen_pub
            } else {
                &mut seen_private
            };
            let rest = after_use.trim().trim_end_matches(';').trim();
            if rest.contains("::*") {
                out_lines.push(line.to_string());
                continue;
            }
            if let Some(open) = rest.find("::{") {
                if let Some(close) = rest.rfind('}') {
                    let path_part = rest[..open].trim();
                    let inner = &rest[open + 3..close];
                    let mut kept: Vec<String> = Vec::new();
                    for part in inner.split(',') {
                        let p = part.trim();
                        if p.is_empty() {
                            continue;
                        }
                        let name = p.split(" as ").next().unwrap_or("").trim();
                        if name.is_empty() {
                            continue;
                        }
                        if seen.insert(name.to_string()) {
                            kept.push(p.to_string());
                        }
                    }
                    if kept.is_empty() {
                        continue;
                    }
                    let stmt = format!(
                        "{}use {}::{{{}}};",
                        if is_pub { "pub " } else { "" },
                        path_part,
                        kept.join(", ")
                    );
                    out_lines.push(stmt);
                    continue;
                }
            }
            if let Some(last) = rest.rsplit("::").next() {
                let name = last.trim();
                if name.is_empty() {
                    out_lines.push(line.to_string());
                    continue;
                }
                if seen.insert(name.to_string()) {
                    out_lines.push(line.to_string());
                }
                continue;
            }
            out_lines.push(line.to_string());
        }
        out_lines.join("\n")
    }

    pub fn generate_program(
        &mut self,
        program: &Program<'ast>,
        analyzed: &[AnalyzedFunction<'ast>],
    ) -> String {
        let mut imports = String::new();
        let mut body = String::new();

        // PRE-PASS: Structs that transitively contain trait objects must not auto-derive Debug/Clone.
        // Must run before `collect_partial_eq_types` (which calls `infer_derivable_traits`).
        self.collect_trait_object_types(program);

        // PRE-PASS: Collect which custom types support PartialEq
        // This enables smart enum derive that only adds PartialEq if all variants support it
        self.collect_partial_eq_types(program);

        // PRE-PASS: Collect types that implement Drop (cannot derive Copy, Rust E0184)
        for item in &program.items {
            if let Item::Impl { block, .. } = item {
                if block.trait_name.as_deref() == Some("Drop") {
                    self.types_with_drop.insert(block.type_name.clone());
                }
            }
        }

        // PRE-PASS: Collect structs that explicitly opt out of Copy via @derive() without Copy.
        // When a user writes @derive(Debug, Clone) without Copy, that's an intentional opt-out.
        for item in &program.items {
            if let Item::Struct { decl: s, .. } = item {
                let has_derive_without_copy = s.decorators.iter().any(|d| {
                    d.name == "derive" && !d.arguments.iter().any(|(_, arg)| {
                        matches!(arg, Expression::Identifier { name, .. } if name == "Copy")
                    })
                });
                if has_derive_without_copy {
                    self.non_copy_types_registry.insert(s.name.clone());
                }
            }
        }

        // PRE-PASS: Populate copy_types_registry for all structs/enums whose fields
        // are all Copy. Iterates until stable so transitive dependencies resolve
        // regardless of declaration order. Respects explicit non-Copy opt-outs.
        {
            let mut changed = true;
            while changed {
                changed = false;
                for item in &program.items {
                    match item {
                        Item::Struct { decl: s, .. } => {
                            if self.copy_types_registry.contains(&s.name)
                                || self.types_with_drop.contains(&s.name)
                                || self.non_copy_types_registry.contains(&s.name)
                            {
                                continue;
                            }
                            let all_types: Vec<&Type> = if let Some(ref tf) = s.tuple_fields {
                                tf.iter().collect()
                            } else {
                                s.fields.iter().map(|f| &f.field_type).collect()
                            };
                            if all_types.iter().all(|t| self.is_copy_type_with_registry(t)) {
                                self.copy_types_registry.insert(s.name.clone());
                                changed = true;
                            }
                        }
                        Item::Enum { decl: e, .. } => {
                            if self.copy_types_registry.contains(&e.name) {
                                continue;
                            }
                            if self.all_enum_variants_are_copy(&e.variants) {
                                self.copy_types_registry.insert(e.name.clone());
                                changed = true;
                            }
                        }
                        _ => {}
                    }
                }
            }
        }

        // Collect bound aliases first (bound Name = Trait + Trait)
        for item in &program.items {
            if let Item::BoundAlias { name, traits, .. } = item {
                self.bound_aliases.insert(name.clone(), traits.clone());
            }
        }

        // Collect struct definitions for implicit self support
        let mut struct_fields: std::collections::HashMap<String, Vec<String>> =
            std::collections::HashMap::new();
        for item in &program.items {
            if let Item::Struct { decl: s, .. } = item {
                let field_names: Vec<String> = s.fields.iter().map(|f| f.name.clone()).collect();
                struct_fields.insert(s.name.clone(), field_names);
            }
        }

        // Track explicitly imported traits to avoid duplication with auto-imports
        let mut explicitly_imported_traits: std::collections::HashSet<String> =
            std::collections::HashSet::new();

        // PRE-PASS: Collect import aliases so type_to_rust skips stdlib mappings
        // when the user has defined their own alias (e.g., `use std::collections::HashMap as Map`)
        for item in &program.items {
            if let Item::Use {
                alias: Some(alias_name),
                path,
                ..
            } = item
            {
                self.import_aliases.insert(alias_name.clone());
                if let Some(last_segment) = path.last() {
                    self.module_alias_map
                        .insert(alias_name.clone(), last_segment.clone());
                }
            }
            if let Item::Use { path, .. } = item {
                if path.len() == 2 && path[0] == "std" {
                    if crate::codegen::rust::stdlib_method_traits::is_runtime_std_module(&path[1]) {
                        self.runtime_std_module_imports.insert(path[1].clone());
                    }
                }
            }
        }

        // Check for stdlib modules that need special imports
        for item in &program.items {
            if let Item::Use { path, .. } = item {
                // Path is ["std", "json"] for "use std::json"
                let path_str = path.join("::");
                if (path_str.starts_with("std::") || path_str == "std") && path_str.contains("json")
                {
                    self.needs_serde_imports = true;
                }
                // If user already imports HashMap/HashSet from std::collections, mark them
                if path_str.contains("HashMap") {
                    self.needs_hashmap_import = true;
                }
                if path_str.contains("HashSet") {
                    self.needs_hashset_import = true;
                }
                // Track explicit std::ops imports to prevent duplication
                if path_str.starts_with("std::ops::") {
                    if let Some(trait_name) = path_str.strip_prefix("std::ops::") {
                        explicitly_imported_traits.insert(trait_name.to_string());
                    }
                }
                // Track explicit std::fmt imports to prevent duplication
                if path_str.starts_with("std::fmt::") {
                    if let Some(trait_name) = path_str.strip_prefix("std::fmt::") {
                        explicitly_imported_traits.insert(trait_name.to_string());
                    }
                }
                // http, time, crypto modules don't need special imports (used directly)
            }
        }

        // THE WINDJAMMER WAY: Auto-detect usage of common stdlib types and traits
        // Walk the AST properly to find HashMap/HashSet usage in types and expressions
        // (NOT debug text, which includes comments and causes false positives)
        {
            if !self.needs_hashmap_import
                && (Self::program_references_collection(program, "HashMap")
                    || Self::program_references_collection(program, "Map"))
            {
                self.needs_hashmap_import = true;
            }
            if !self.needs_hashset_import && Self::program_references_collection(program, "HashSet")
            {
                self.needs_hashset_import = true;
            }
        }

        // Auto-detect operator trait implementations (impl Add, impl Sub, etc.)
        // and add the necessary std::ops imports (only if not already explicitly imported)
        for item in &program.items {
            if let Item::Impl { block, .. } = item {
                if let Some(ref trait_name) = block.trait_name {
                    // Skip if the user already has an explicit import for this trait
                    if explicitly_imported_traits.contains(trait_name.as_str()) {
                        continue;
                    }
                    match trait_name.as_str() {
                        "Add" | "Sub" | "Mul" | "Div" | "Neg" | "Rem" | "AddAssign"
                        | "SubAssign" | "MulAssign" | "DivAssign" => {
                            self.needs_trait_imports.insert(trait_name.clone());
                        }
                        "Display" | "Debug" => {
                            self.needs_trait_imports.insert(trait_name.clone());
                        }
                        _ => {}
                    }
                }
            }
        }

        // Collect inline module names for self:: prefix generation in pub use
        self.inline_module_names.clear();
        for item in &program.items {
            if let Item::Mod { name, .. } = item {
                self.inline_module_names.insert(name.clone());
            }
        }

        // Generate explicit use statements
        let mut has_explicit_pub_use = false;
        for item in &program.items {
            if let Item::Use {
                path,
                alias,
                is_pub,
                ..
            } = item
            {
                if *is_pub {
                    has_explicit_pub_use = true;
                }
                let use_stmt = self.generate_use(path, alias.as_deref(), *is_pub);
                if !use_stmt.trim().is_empty() {
                    // Don't prepend pub - it's already in use_stmt
                    imports.push_str(&use_stmt);
                }
            }
        }

        // Auto-generate pub use re-exports for mod.rs files without explicit pub use.
        // When a mod.wj declares `pub mod submod` but no `pub use submod::Type`,
        // users expect `use crate::mymod::Type` to work. This requires re-exports.
        if self.is_output_mod_rs() && !has_explicit_pub_use {
            for item in &program.items {
                if let Item::Mod {
                    name,
                    is_public: true,
                    ..
                } = item
                {
                    // TDD FIX: Skip glob re-exports for test modules to avoid E0659 ambiguity
                    // Bug: Multiple test modules with same type names (e.g., PlayerState) cause
                    // "ambiguous name" errors when both are glob re-exported in lib.rs
                    // Root Cause: `pub use test_foo::*; pub use test_bar::*;` brings all types
                    // into scope, creating conflicts when type names overlap
                    // Fix: Test modules don't need glob re-exports - tests can use explicit imports
                    // like `use crate::test_foo::Type;` or `use super::test_foo::Type;`
                    let is_test_module = name.starts_with("test_");
                    if !is_test_module {
                        imports.push_str(&format!("pub use self::{}::*;\n", name));
                    }
                }
            }
        }

        // Generate const and static declarations
        for item in &program.items {
            match item {
                Item::Const {
                    name,
                    is_pub,
                    type_,
                    value,
                    ..
                } => {
                    let pub_prefix = if *is_pub { "pub " } else { "" };

                    // Special case: string constants should use &'static str, not String
                    let rust_type = if matches!(type_, Type::String)
                        && matches!(
                            value,
                            Expression::Literal {
                                value: Literal::String(_),
                                ..
                            }
                        ) {
                        "&'static str".to_string()
                    } else {
                        self.type_to_rust(type_)
                    };

                    body.push_str(&format!(
                        "{}const {}: {} = {};\n",
                        pub_prefix,
                        name,
                        rust_type,
                        self.generate_expression_immut(value)
                    ));
                }
                Item::Static {
                    name,
                    mutable,
                    type_,
                    value,
                    ..
                } => {
                    if *mutable {
                        body.push_str(&format!(
                            "static mut {}: {} = {};\n",
                            name,
                            self.type_to_rust(type_),
                            self.generate_expression_immut(value)
                        ));
                    } else {
                        // PHASE 7: Promote static to const if value is compile-time evaluable
                        let keyword = if expression_helpers::is_const_evaluable(value) {
                            "const" // Zero runtime overhead!
                        } else {
                            "static"
                        };

                        body.push_str(&format!(
                            "{} {}: {} = {};\n",
                            keyword,
                            name,
                            self.type_to_rust(type_),
                            self.generate_expression_immut(value)
                        ));
                    }
                }
                Item::TypeAlias {
                    name,
                    target,
                    is_pub,
                    ..
                } => {
                    let pub_prefix = if *is_pub { "pub " } else { "" };
                    body.push_str(&format!(
                        "{}type {} = {};\n",
                        pub_prefix,
                        name,
                        self.type_to_rust(target)
                    ));
                }
                _ => {}
            }
        }

        if !body.is_empty() {
            body.push('\n');
        }

        // Collect names of functions in impl blocks and trait methods to avoid generating them twice
        let mut impl_methods = std::collections::HashSet::new();
        for item in &program.items {
            if let Item::Impl {
                block: impl_block, ..
            } = item
            {
                for func in &impl_block.functions {
                    impl_methods.insert(func.name.clone());
                }
            }
            // Also collect trait method names
            if let Item::Trait { decl, .. } = item {
                for method in &decl.methods {
                    impl_methods.insert(method.name.clone());
                }
            }
        }

        // Generate structs, enums, and traits
        for item in &program.items {
            match item {
                Item::Struct { decl: s, .. } => {
                    body.push_str(&self.generate_struct(s));
                    body.push_str("\n\n");

                    // Check for @component or @game decorators and generate trait implementations
                    if s.decorators.iter().any(|d| d.name == "component") {
                        body.push_str(&self.generate_component_impl(s));
                        body.push_str("\n\n");
                    }
                    if s.decorators.iter().any(|d| d.name == "game") {
                        body.push_str(&self.generate_game_impl(s));
                        body.push_str("\n\n");
                    }
                }
                Item::Enum { decl: e, .. } => {
                    body.push_str(&self.generate_enum(e));
                    body.push_str("\n\n");
                }
                Item::Trait { decl: t, .. } => {
                    body.push_str(&self.generate_trait_with_analysis(t, analyzed));
                    body.push_str("\n\n");
                }
                Item::Impl {
                    block: impl_block, ..
                } => {
                    // Set the struct name, fields, and method names for implicit self support
                    self.current_struct_name = Some(impl_block.type_name.clone());
                    if let Some(fields) = struct_fields.get(&impl_block.type_name) {
                        self.current_struct_fields = fields.iter().cloned().collect();
                    } else {
                        self.current_struct_fields.clear();
                    }
                    self.current_impl_methods = impl_block
                        .functions
                        .iter()
                        .map(|f| f.name.clone())
                        .collect();
                    self.in_impl_block = true;

                    body.push_str(&self.generate_impl(impl_block, analyzed));
                    body.push_str("\n\n");

                    self.in_impl_block = false;
                    self.current_struct_name = None;
                    self.current_struct_fields.clear();
                    self.current_impl_methods.clear();
                    self.current_impl_instance_methods.clear();
                }
                Item::Mod {
                    name,
                    items,
                    is_public,
                    ..
                } => {
                    // THE WINDJAMMER WAY: In multi-file projects, NEVER inline modules
                    // Even if the AST has items (from cross-file trait inference),
                    // we should generate external declarations (mod name;)
                    // Inline modules are ONLY for single-file compilation

                    // CRITICAL FIX: Prioritize self.is_module over items.is_empty()
                    // During trait inference regeneration, items may be populated even for external modules
                    if self.is_module || items.is_empty() {
                        // External module declaration: mod math;
                        // Use this in multi-file projects (when is_module=true)
                        // OR when items is empty (explicit external mod)
                        if *is_public {
                            body.push_str(&format!("pub mod {};\n", name));
                        } else {
                            body.push_str(&format!("mod {};\n", name));
                        }
                    } else {
                        // Inline module: mod math { ... }
                        // ONLY used in single-file projects (when is_module=false AND items not empty)
                        if *is_public {
                            body.push_str(&format!("pub mod {} {{\n", name));
                        } else {
                            body.push_str(&format!("mod {} {{\n", name));
                        }

                        // Increase indentation for nested items
                        self.indent_level += 1;

                        // Generate all items inside the module
                        for item in items {
                            body.push_str(&self.indent());
                            body.push_str(&self.generate_inline_module_item(item, analyzed));
                        }

                        // Decrease indentation
                        self.indent_level -= 1;
                        body.push_str("}\n\n");
                    }
                }
                _ => {}
            }
        }

        // Generate extern functions (FFI declarations)
        let extern_funcs: Vec<_> = analyzed
            .iter()
            .filter(|af| af.decl.is_extern && !impl_methods.contains(&af.decl.name))
            .collect();

        if !extern_funcs.is_empty() {
            body.push_str("extern \"C\" {\n");
            for extern_func in extern_funcs {
                body.push_str(&self.generate_extern_function(&extern_func.decl));
            }
            body.push_str("}\n\n");
        }

        // Generate top-level functions (skip impl methods and extern functions)
        for analyzed_func in analyzed {
            if !impl_methods.contains(&analyzed_func.decl.name) && !analyzed_func.decl.is_extern {
                // Skip main() function in modules - it should only be in the entry point
                if self.is_module && analyzed_func.decl.name == "main" {
                    continue;
                }
                // Generate the function
                body.push_str(&self.generate_function(analyzed_func));
                body.push_str("\n\n");
            }
        }

        // Check for test decorators or test_ prefix functions (for test runtime import)
        let filename_str = self.current_wj_file.to_string_lossy();
        let is_test_file = filename_str.ends_with("_test.wj") || filename_str.contains("_test.wj");
        let has_test_functions = analyzed.iter().any(|af| {
            // Check for explicit decorators (@test, @property_test, @test_cases)
            let has_test_decorator =
                af.decl.decorators.iter().any(|d| {
                    d.name == "test" || d.name == "property_test" || d.name == "test_cases"
                });

            // Check for implicit test_ prefix naming convention (only in test files)
            let has_test_prefix = is_test_file && af.decl.name.starts_with("test_");

            has_test_decorator || has_test_prefix
        });

        // Check for property testing decorators and collect max parameter count
        let mut max_property_test_params = 0;
        for analyzed_func in analyzed {
            if analyzed_func
                .decl
                .decorators
                .iter()
                .any(|d| d.name == "property_test")
            {
                let param_count = analyzed_func.decl.parameters.len();
                if param_count > max_property_test_params {
                    max_property_test_params = param_count;
                }
            }
        }

        // Inject implicit imports if needed
        let mut implicit_imports = String::new();

        // Cross-module type references: only when we do NOT inject `use super::*` below.
        // Injected `use super::*` already pulls in sibling types re-exported from the parent `mod.rs`;
        // extra `use super::Type` lines are often wrong (Type lives in `super::other_module::Type`)
        // and duplicate globs (E0252). If the user already wrote `use super::*`, we also skip (see
        // `auto_super_type_import_paths`).
        let has_explicit_glob_imports = imports.lines().any(|line| {
            let trimmed = line.trim();
            trimmed.ends_with("::*;") && !trimmed.starts_with("//")
        });
        let will_inject_super_glob = self.is_module && !has_explicit_glob_imports;
        let auto_super_type_imports = if will_inject_super_glob {
            String::new()
        } else {
            self.format_auto_super_type_imports(program)
        };
        if !auto_super_type_imports.is_empty() {
            implicit_imports.push_str(&auto_super_type_imports);
        }

        // Add trait imports for inferred bounds
        if !self.needs_trait_imports.is_empty() {
            let mut sorted_traits: Vec<_> = self.needs_trait_imports.iter().collect();
            sorted_traits.sort();
            for trait_name in sorted_traits {
                match trait_name.as_str() {
                    "Display" | "Debug" => {
                        implicit_imports.push_str(&format!("use std::fmt::{};\n", trait_name));
                    }
                    "Clone" => {
                        // Clone is in prelude, no import needed
                    }
                    "Add" | "Sub" | "Mul" | "Div" | "Neg" | "Rem" | "AddAssign" | "SubAssign"
                    | "MulAssign" | "DivAssign" => {
                        implicit_imports.push_str(&format!("use std::ops::{};\n", trait_name));
                    }
                    "PartialEq" | "Eq" | "PartialOrd" | "Ord" => {
                        // These are in prelude, no import needed
                    }
                    "IntoIterator" | "Iterator" => {
                        // These are in prelude, no import needed
                    }
                    _ => {
                        // Custom trait, assume it's already in scope
                    }
                }
            }
        }

        if self.needs_wasm_imports {
            implicit_imports.push_str("use wasm_bindgen::prelude::*;\n");
        }
        if self.needs_web_imports {
            implicit_imports.push_str("use web_sys::*;\n");
        }
        if self.needs_js_imports {
            implicit_imports.push_str("use js_sys::*;\n");
        }
        if self.needs_serde_imports {
            implicit_imports.push_str("use serde::{Serialize, Deserialize};\n");
        }
        if self.needs_smallvec_import {
            implicit_imports.push_str("use smallvec::{SmallVec, smallvec};\n");
        }
        if self.needs_cow_import {
            implicit_imports.push_str("use std::borrow::Cow;\n");
        }
        if self.needs_write_import {
            implicit_imports.push_str("use std::fmt::Write;\n");
        }
        if self.needs_hashmap_import && !imports.contains("std::collections::HashMap") {
            implicit_imports.push_str("use std::collections::HashMap;\n");
        }
        if self.needs_hashset_import && !imports.contains("std::collections::HashSet") {
            implicit_imports.push_str("use std::collections::HashSet;\n");
        }

        // THE WINDJAMMER WAY: Auto-import sibling types in module directories
        // When compiling a multi-file project, each file in a module directory
        // should have access to sibling types re-exported by the parent mod.rs.
        // This prevents the need for explicit imports of types within the same module.
        // Example: quest/manager.rs gets `use super::*;` which imports QuestId, Quest, etc.
        // from quest/mod.rs's re-exports.
        // For root-level modules, `super` refers to the crate root (lib.rs), which is harmless.
        //
        // IMPORTANT: When the file has explicit glob imports (use crate::X::*), we must NOT
        // add `use super::*` because two glob imports bringing the same name into scope causes
        // Rust error E0659 ("ambiguous name"). For example, if mod.rs re-exports GizmoMode
        // from scene_view, and the file also has `use crate::gizmos::*` which exports its own
        // GizmoMode, both globs would bring GizmoMode into scope, making it ambiguous.
        // Don't inject `use super::*;` for the crate lib root (mod.rs that IS lib.rs).
        // super has no parent at the crate root → E0433.
        let is_lib_root = self.is_output_mod_rs()
            && self
                .current_output_file
                .parent()
                .map(|d| d.join("Cargo.toml").exists())
                .unwrap_or(false);
        if self.is_module && !has_explicit_glob_imports && !is_lib_root {
            implicit_imports.push_str("#[allow(unused_imports)]\nuse super::*;\n");
        }

        // TDD FIX: Auto-import test runtime for files with test functions
        // THE WINDJAMMER WAY: Files with @test decorators should auto-import test utilities
        // Bug: Test functions can't find assert_eq, assert_gt, etc.
        // Root Cause: Codegen doesn't auto-import windjammer_runtime::test::*
        // Fix: Check if module has ANY functions with @test/@property_test/@test_cases decorators
        // NOTE: Uses AST analysis, not filename (prevents false positives like "hashmap_test.wj")
        if has_test_functions {
            implicit_imports.push_str("use windjammer_runtime::test::*;\n");
        }

        // Add property testing imports if needed
        if max_property_test_params > 0 {
            // Import the specific property_test_with_genN functions needed
            for param_count in 1..=max_property_test_params {
                implicit_imports.push_str(&format!(
                    "use windjammer_runtime::property::property_test_with_gen{};\n",
                    param_count
                ));
            }
            // Add rand re-export from windjammer_runtime for random value generation in property tests
            implicit_imports.push_str("use windjammer_runtime::rand;\n");
        }

        // Add Tauri invoke helper for WASM target if needed
        let mut tauri_helper = String::new();
        if self.target == CompilationTarget::Wasm && self.needs_serde_imports {
            tauri_helper.push_str(r#"
// Tauri invoke helper for WASM
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = ["window", "__TAURI__", "core"], js_name = invoke)]
    async fn tauri_invoke_js(cmd: &str, args: JsValue) -> JsValue;
}

async fn tauri_invoke<T: serde::de::DeserializeOwned>(cmd: &str, args: serde_json::Value) -> Result<T, String> {
    let js_args = serde_wasm_bindgen::to_value(&args).map_err(|e| e.to_string())?;
    let result = tauri_invoke_js(cmd, js_args).await;
    serde_wasm_bindgen::from_value(result).map_err(|e| e.to_string())
}

"#);
        }

        // Combine: implicit imports + explicit imports + tauri helper + body
        let mut combined_imports = String::new();
        if !implicit_imports.is_empty() {
            combined_imports.push_str(&implicit_imports);
        }
        if !imports.is_empty() {
            if !combined_imports.is_empty() {
                combined_imports.push('\n');
            }
            combined_imports.push_str(&imports);
        }
        let combined_imports = Self::dedupe_rust_import_lines(&combined_imports);

        let mut output = String::new();
        if !combined_imports.is_empty() {
            output.push_str(&combined_imports);
        }
        if !tauri_helper.is_empty() {
            output.push('\n');
            output.push_str(&tauri_helper);
        }
        if !output.is_empty() && !body.is_empty() {
            output.push('\n');
        }
        output.push_str(&body);

        if std::env::var("WJ_EMIT_AOSOA_HINTS").ok().as_deref() == Some("1") {
            let hints = crate::codegen::rust::aosoa_transform::emit_aosoa_hints(program, analyzed);
            if !hints.is_empty() {
                output
                    .push_str("\n\n// --- Windjammer cache locality (WJ_EMIT_AOSOA_HINTS=1) ---\n");
                output.push_str(&hints);
            }
        }

        if let Ok(report_path) = std::env::var("WJ_CACHE_LOCALITY_JSON") {
            let json = crate::analyzer::cache_locality_json_report(analyzed);
            if let Err(e) = std::fs::write(&report_path, json) {
                eprintln!(
                    "windjammer: WJ_CACHE_LOCALITY_JSON failed to write {}: {}",
                    report_path, e
                );
            }
        }

        output
    }
}