windjammer 0.47.0

A simple language inspired by Go, Ruby, and Elixir that transpiles to Rust - 80% of Rust's power with 20% of the complexity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
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
//! Multi-file library build with global multi-pass analysis.

use crate::analyzer::{Analyzer, SignatureRegistry};
use crate::codegen::rust::CodeGenerator;
use crate::lexer::Lexer;
use crate::linter::rust_leakage::RustLeakageLinter;
use crate::metadata::{
    meta_cache_path, metadata_function_sig_from_analyzer, CrateMetadata, FunctionSignature,
    ModuleMetadata,
};
use crate::parser::ast::core::Item;
use crate::parser::Parser;
use crate::type_inference::{FloatInference, IntInference};
use crate::CompilationTarget;
use anyhow::Result;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// TDD FIX: Build library with global multi-pass analysis
/// Solves cross-file transitive mutability inference
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_library_multipass(
    wj_files: &[PathBuf],
    base_path: &Path,
    output: &Path,
    target: CompilationTarget,
    library: bool,
    enable_lint: bool,
    external_paths: &HashMap<String, PathBuf>,
    mut crate_metadata: CrateMetadata,
) -> Result<()> {
    // Step 1: Read all source files (keep sources alive for lifetime safety)
    let mut sources: Vec<(PathBuf, String)> = Vec::new();

    for file in wj_files {
        let canon = std::fs::canonicalize(file).unwrap_or_else(|_| file.to_path_buf());
        let source = std::fs::read_to_string(&canon)?;
        sources.push((canon, source));
    }

    // Filter out shader files (detected by @vertex/@fragment/@compute decorators).
    // These target the WJSL→WGSL pipeline, not Rust codegen.
    //
    // Two-pass filter:
    //   Pass 1: Remove files with shader entry-point decorators
    //   Pass 2: Remove mod.wj files whose sub-modules were ALL filtered
    //
    // For mod.wj files that survive pass 2 (some children filtered, some not),
    // we collect the filtered child module names per directory so we can strip
    // them from the AST before codegen — preventing wrong code from ever being
    // generated.
    let mut removed_stems: HashSet<PathBuf> = HashSet::new();
    let mut shader_count = 0usize;
    // Map: directory path → set of module names that were filtered in that dir
    let mut filtered_modules_by_dir: HashMap<PathBuf, HashSet<String>> = HashMap::new();

    sources.retain(|(file, source)| {
        let mut lexer = Lexer::new(source);
        let tokens = lexer.tokenize_with_locations();
        let mut parser =
            Parser::new_with_source(tokens, file.to_string_lossy().to_string(), source.clone());
        if let Ok(program) = parser.parse() {
            if super::is_shader_file(&program) {
                removed_stems.insert(file.clone());
                // Record the module name for its parent directory
                if let Some(parent) = file.parent() {
                    if let Some(stem) = file.file_stem().and_then(|s| s.to_str()) {
                        filtered_modules_by_dir
                            .entry(parent.to_path_buf())
                            .or_default()
                            .insert(stem.to_string());
                    }
                }
                shader_count += 1;
                return false;
            }
        }
        true
    });

    // Pass 2: mod.wj files whose only items are `pub mod` declarations
    // referencing filtered shader files should also be skipped.
    if !removed_stems.is_empty() {
        sources.retain(|(file, source)| {
            let is_mod = file
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n == "mod.wj")
                .unwrap_or(false);
            if !is_mod {
                return true;
            }
            let parent = match file.parent() {
                Some(p) => p,
                None => return true,
            };
            let mut lexer = Lexer::new(source);
            let tokens = lexer.tokenize_with_locations();
            let mut parser =
                Parser::new_with_source(tokens, file.to_string_lossy().to_string(), source.clone());
            let program = match parser.parse() {
                Ok(p) => p,
                Err(_) => return true,
            };
            let has_non_mod_items = program
                .items
                .iter()
                .any(|item| !matches!(item, Item::Mod { .. }));
            if has_non_mod_items {
                return true;
            }
            let all_subs_removed = program.items.iter().all(|item| {
                if let Item::Mod { name, .. } = item {
                    let sub_file = parent.join(format!("{}.wj", name));
                    let sub_dir_mod = parent.join(name.as_str()).join("mod.wj");
                    removed_stems.contains(&sub_file) || removed_stems.contains(&sub_dir_mod)
                } else {
                    true
                }
            });
            if all_subs_removed {
                // Record filtered directory module name for its grandparent
                if let Some(dir_name) = parent.file_name().and_then(|n| n.to_str()) {
                    if let Some(grandparent) = parent.parent() {
                        filtered_modules_by_dir
                            .entry(grandparent.to_path_buf())
                            .or_default()
                            .insert(dir_name.to_string());
                    }
                }
                shader_count += 1;
                false
            } else {
                true
            }
        });
    }
    if shader_count > 0 {
        eprintln!(
            "  Skipped {} shader file(s) from Rust pipeline (use WJSL target for GPU shaders)",
            shader_count
        );
    }

    if sources.is_empty() {
        return Ok(());
    }

    let src_base: PathBuf = {
        let raw = if base_path.is_file() {
            base_path.parent().unwrap_or(base_path).to_path_buf()
        } else {
            base_path.to_path_buf()
        };
        std::fs::canonicalize(&raw).unwrap_or(raw)
    };

    let (mut global_copy_structs, local_struct_names) =
        super::library_copy_registry::collect_global_copy_structs_for_library(&sources);

    // Load Copy structs AND function signatures from dependency crate metadata.
    // Function signatures provide ownership info for cross-crate calls (e.g.,
    // voxelgrid_to_svo64_flat from windjammer-game-core). The metadata includes
    // module-qualified names for unambiguous lookup.
    let dep_roots =
        super::dependency_resolution::find_dependency_metadata_roots(&src_base, external_paths);
    let mut dep_registry = SignatureRegistry::new();
    {
        let mut dep_copy_structs = Vec::new();
        let mut dep_struct_fields: HashMap<String, Vec<Vec<String>>> = HashMap::new();
        for root in &dep_roots {
            crate::metadata::merge_wj_meta_signatures_from_dir_inner_pub(
                root,
                &mut dep_registry,
                &mut dep_copy_structs,
                &mut dep_struct_fields,
            );
        }
        crate::metadata::infer_copy_from_metadata_structs_pub(
            &dep_struct_fields,
            &mut dep_copy_structs,
        );
        // Only import dep Copy status for struct names that do NOT have a local
        // definition. When the current crate defines a struct with the same name
        // as a dep struct, the local definition's Copy status (already computed
        // by collect_global_copy_structs_for_library) takes precedence.
        // Without this filter, a Copy `PlayerState` from an engine crate would
        // poison a non-Copy `PlayerState` in the game crate, causing E0382.
        for name in dep_copy_structs {
            if !local_struct_names.contains(&name) {
                global_copy_structs.insert(name);
            }
        }
    }

    // Step 2: Build initial registries from ALL files (first pass)
    // - global_registry: For ownership inference (SignatureRegistry)
    // - global_float_signatures: For float inference (function param types)
    // - global_struct_fields: For float inference (struct field types)
    // Seed with dependency crate signatures (ownership from .wj.meta files).
    // Also load the project's own .wj.meta files from prior builds so that
    // module-qualified ownership info (e.g., draw::draw_text → Borrowed) is
    // available from the very first analysis pass.
    let mut global_registry = dep_registry;
    crate::metadata::merge_wj_meta_signatures_from_dir(&src_base, &mut global_registry);
    let mut global_float_signatures: HashMap<
        String,
        (
            Vec<crate::parser::ast::types::Type>,
            Option<crate::parser::ast::types::Type>,
        ),
    > = HashMap::new();
    let mut global_struct_fields: HashMap<
        String,
        HashMap<String, crate::parser::ast::types::Type>,
    > = HashMap::new();
    let mut struct_defining_module_paths: HashMap<String, Vec<Vec<String>>> = HashMap::new();

    for (file, source) in &sources {
        // Parse with proper lifetime (program borrows source)
        let mut lexer = Lexer::new(source);
        let tokens = lexer.tokenize_with_locations();
        let mut parser =
            Parser::new_with_source(tokens, file.to_string_lossy().to_string(), source.clone());
        let program = parser
            .parse()
            .map_err(|e| anyhow::anyhow!("Parse error in {}: {}", file.display(), e))?;

        // Collect metadata for library emission
        let mut module_meta = ModuleMetadata::new(
            file.file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_string(),
        );
        for item in &program.items {
            match item {
                Item::Struct { decl, .. } => {
                    let mut fields = HashMap::new();
                    for field in &decl.fields {
                        fields.insert(
                            field.name.clone(),
                            ModuleMetadata::serialize_type(&field.field_type),
                        );
                    }
                    module_meta.structs.insert(decl.name.clone(), fields);
                }
                Item::Function { decl, .. } => {
                    module_meta.functions.insert(
                        decl.name.clone(),
                        FunctionSignature {
                            params: decl
                                .parameters
                                .iter()
                                .map(|p| ModuleMetadata::serialize_type(&p.type_))
                                .collect(),
                            return_type: decl
                                .return_type
                                .as_ref()
                                .map(ModuleMetadata::serialize_type),
                            is_associated: false,
                            parent_type: None,
                            param_ownership: vec![],
                            has_self_receiver: false,
                            is_extern: decl.is_extern,
                        },
                    );
                }
                Item::Impl { block, .. } => {
                    for func_decl in &block.functions {
                        let full_name = format!("{}::{}", block.type_name, func_decl.name);
                        module_meta.functions.insert(
                            full_name,
                            FunctionSignature {
                                params: func_decl
                                    .parameters
                                    .iter()
                                    .map(|p| ModuleMetadata::serialize_type(&p.type_))
                                    .collect(),
                                return_type: func_decl
                                    .return_type
                                    .as_ref()
                                    .map(ModuleMetadata::serialize_type),
                                is_associated: true,
                                parent_type: Some(block.type_name.clone()),
                                param_ownership: vec![],
                                has_self_receiver: false,
                                is_extern: false,
                            },
                        );
                    }
                }
                _ => {}
            }
        }
        crate_metadata.merge_module(&module_meta);

        // Collect function signatures for float inference
        for item in &program.items {
            match item {
                Item::Function { decl, .. } => {
                    let param_types: Vec<crate::parser::ast::types::Type> =
                        decl.parameters.iter().map(|p| p.type_.clone()).collect();
                    global_float_signatures
                        .insert(decl.name.clone(), (param_types, decl.return_type.clone()));
                }
                Item::Impl { block, .. } => {
                    for func_decl in &block.functions {
                        let param_types: Vec<crate::parser::ast::types::Type> = func_decl
                            .parameters
                            .iter()
                            .map(|p| p.type_.clone())
                            .collect();
                        let full_name = format!("{}::{}", block.type_name, func_decl.name);
                        global_float_signatures
                            .insert(full_name, (param_types, func_decl.return_type.clone()));
                    }
                }
                _ => {}
            }
        }

        // Collect struct field types for float/int inference (module-qualified keys).
        fn merge_struct_fields_from_items(
            items: &[crate::parser::ast::core::Item<'_>],
            module_prefix: &[String],
            global_struct_fields: &mut HashMap<
                String,
                HashMap<String, crate::parser::ast::types::Type>,
            >,
            struct_defining_module_paths: &mut HashMap<String, Vec<Vec<String>>>,
        ) {
            use crate::parser::ast::core::Item;
            use crate::type_inference::struct_field_registry;
            for item in items {
                match item {
                    Item::Struct { decl, .. } => {
                        let qualified =
                            struct_field_registry::qualify_struct_key(module_prefix, &decl.name);
                        let mut fields = HashMap::new();
                        for field in &decl.fields {
                            fields.insert(field.name.clone(), field.field_type.clone());
                        }
                        global_struct_fields.insert(qualified, fields);
                        struct_defining_module_paths
                            .entry(decl.name.clone())
                            .or_default()
                            .push(module_prefix.to_vec());
                    }
                    Item::Mod { name, items, .. } => {
                        let mut next = module_prefix.to_vec();
                        next.push(name.clone());
                        merge_struct_fields_from_items(
                            items,
                            &next,
                            global_struct_fields,
                            struct_defining_module_paths,
                        );
                    }
                    _ => {}
                }
            }
        }
        let file_module = crate::analyzer::type_collector::wj_file_to_module_path(&src_base, file)
            .unwrap_or_default();
        merge_struct_fields_from_items(
            &program.items,
            &file_module,
            &mut global_struct_fields,
            &mut struct_defining_module_paths,
        );

        // First-pass analysis
        let mut analyzer = Analyzer::new_with_copy_structs(global_copy_structs.clone());
        let (_, registry, _) = analyzer
            .analyze_program(&program)
            .map_err(|e| anyhow::anyhow!("Analysis error in {}: {}", file.display(), e))?;

        // Merge into global registry using public API
        global_registry.merge(&registry);

        // Also register module-qualified names so the code generator can find the
        // correct signature for qualified function calls.
        // Uses the full module path (e.g., combat::abilities::Ability::activate)
        // to avoid collisions when two files have the same stem name.
        let file_stem = file.file_stem().and_then(|s| s.to_str()).unwrap_or("");
        let module_path = file_module.join("::");
        if !file_stem.is_empty() {
            for (name, sig) in &registry.signatures {
                // Register under file_stem::name (e.g., abilities::draw_text)
                if !name.contains("::") {
                    let qualified = format!("{}::{}", file_stem, name);
                    global_registry.add_function(qualified, sig.clone());
                }
                // Also register under full module path for disambiguation
                // (e.g., combat::abilities::Ability::activate)
                if !module_path.is_empty() {
                    let full_qualified = format!("{}::{}", module_path, name);
                    global_registry.add_function(full_qualified, sig.clone());
                }
            }
        }
    }

    // Step 3: Global multi-pass iteration until convergence
    const MAX_GLOBAL_PASSES: usize = 10;
    let mut pass_number = 1;

    loop {
        let mut new_registry = global_registry.clone();

        // Re-analyze ALL files with current global registry
        for (file, source) in &sources {
            // Re-parse (lifetime scoped to this iteration)
            let mut lexer = Lexer::new(source);
            let tokens = lexer.tokenize_with_locations();
            let mut parser =
                Parser::new_with_source(tokens, file.to_string_lossy().to_string(), source.clone());
            let program = parser
                .parse()
                .map_err(|e| anyhow::anyhow!("Parse error: {}", e))?;

            let mut analyzer = Analyzer::new_with_copy_structs(global_copy_structs.clone());
            analyzer.set_global_struct_field_types(global_struct_fields.clone());
            let (_, file_registry, _) = analyzer
                .analyze_program_with_global_signatures(&program, &global_registry)
                .map_err(|e| anyhow::anyhow!("Analysis error in pass {}: {}", pass_number, e))?;

            // FIX: Only merge entries that CHANGED from global_registry.
            // analyze_program_with_global_signatures returns a FULL registry (global clone +
            // file-specific entries). Merging all entries would let passthrough global entries
            // from later files overwrite correct values set by earlier files in this iteration.
            // Example: manager.wj correctly infers tick=MutBorrowed, but state.wj's passthrough
            // tick=Borrowed would overwrite it because state.wj analyzed with the same stale
            // global_registry.
            let file_stem = file.file_stem().and_then(|s| s.to_str()).unwrap_or("");
            let file_module =
                crate::analyzer::type_collector::wj_file_to_module_path(&src_base, file)
                    .unwrap_or_default();
            let module_path = file_module.join("::");
            for (name, sig) in &file_registry.signatures {
                match global_registry.signatures.get(name) {
                    None => {
                        new_registry.signatures.insert(name.clone(), sig.clone());
                    }
                    Some(old_sig) => {
                        if sig.param_ownership != old_sig.param_ownership
                            || sig.return_ownership != old_sig.return_ownership
                            || sig.has_self_receiver != old_sig.has_self_receiver
                        {
                            new_registry.signatures.insert(name.clone(), sig.clone());
                            // Keep ALL module-qualified aliases in sync.
                            // When a Type::method entry changes (e.g., Ability::activate
                            // gets player corrected from Owned→MutBorrowed), the
                            // module-qualified alias (combat_abilities::Ability::activate)
                            // must also be updated. Without this, the codegen's collision
                            // fallback finds the stale step 2 entry.
                            if !file_stem.is_empty() {
                                let qualified = format!("{}::{}", file_stem, name);
                                new_registry.signatures.insert(qualified, sig.clone());
                                if !module_path.is_empty() {
                                    let full_qualified = format!("{}::{}", module_path, name);
                                    new_registry.signatures.insert(full_qualified, sig.clone());
                                }
                            }
                        }
                    }
                }
            }
        }

        // Convergence check: did any signatures change in this pass?
        let mut changed = false;
        for (name, sig) in &new_registry.signatures {
            match global_registry.signatures.get(name) {
                None => {
                    changed = true;
                    break;
                }
                Some(old_sig) => {
                    if sig.param_ownership != old_sig.param_ownership
                        || sig.return_ownership != old_sig.return_ownership
                        || sig.has_self_receiver != old_sig.has_self_receiver
                    {
                        changed = true;
                        break;
                    }
                }
            }
        }

        if !changed || pass_number >= MAX_GLOBAL_PASSES {
            global_registry = new_registry;
            break;
        }

        global_registry = new_registry;
        pass_number += 1;
    }

    // Collect `pub use` re-exports from every file first so `use super::*` / `use crate::...::*`
    // can resolve struct field types (glob has no explicit type path).
    let mut module_re_exports: HashMap<String, HashMap<String, String>> = HashMap::new();
    for (file, source) in &sources {
        let mut lexer = Lexer::new(source);
        let tokens = lexer.tokenize_with_locations();
        let mut parser =
            Parser::new_with_source(tokens, file.to_string_lossy().to_string(), source.clone());
        let program = parser
            .parse()
            .map_err(|e| anyhow::anyhow!("Parse error in {}: {}", file.display(), e))?;
        let file_module = crate::analyzer::type_collector::wj_file_to_module_path(&src_base, file)
            .unwrap_or_default();
        crate::type_inference::struct_field_registry::merge_module_reexports_from_items(
            &program.items,
            &file_module,
            &global_struct_fields,
            &struct_defining_module_paths,
            &mut module_re_exports,
        );
        if crate::type_inference::struct_field_registry::debug_struct_import_trace()
            && file.to_string_lossy().contains("dialogue")
        {
            eprintln!(
                "=== WJ_DEBUG: file={} file_module_path={:?}",
                file.display(),
                file_module
            );
        }
    }

    if crate::type_inference::struct_field_registry::debug_struct_import_trace() {
        eprintln!("=== GLOBAL MODULE_RE_EXPORTS (post pre-pass) ===");
        let mut mods: Vec<_> = module_re_exports.keys().cloned().collect();
        mods.sort();
        for m in &mods {
            if !m.contains("dialogue") && !m.is_empty() {
                continue;
            }
            let exports = &module_re_exports[m];
            eprintln!("  module {:?}: {} exports", m, exports.len());
            for (name, key) in exports {
                if name.contains("Dialogue") {
                    eprintln!("    {}{}", name, key);
                }
            }
        }
    }

    // Step 4A: Global float inference pass (collect constraints from ALL files first)
    let mut global_float_inference = FloatInference::new();
    if !external_paths.is_empty() {
        global_float_inference.set_external_crate_metadata_paths(external_paths);
    }
    global_float_inference.set_global_function_signatures(global_float_signatures.clone());
    global_float_inference.set_global_struct_field_types(&global_struct_fields);
    global_float_inference.set_struct_defining_module_paths(struct_defining_module_paths.clone());
    global_float_inference.set_module_re_exports(module_re_exports.clone());

    // Collect constraints from ALL files into one FloatInference instance
    for (file, source) in &sources {
        let mut lexer = Lexer::new(source);
        let tokens = lexer.tokenize_with_locations();
        let mut parser =
            Parser::new_with_source(tokens, file.to_string_lossy().to_string(), source.clone());
        let program = parser
            .parse()
            .map_err(|e| anyhow::anyhow!("Parse error in {}: {}", file.display(), e))?;
        let file_module = crate::analyzer::type_collector::wj_file_to_module_path(&src_base, file)
            .unwrap_or_default();
        global_float_inference.set_current_file_module_path(file_module);
        global_float_inference.infer_program(&program);
    }

    // Check for float inference errors
    if !global_float_inference.errors.is_empty() {
        for error in &global_float_inference.errors {
            eprintln!("Float inference error: {}", error);
        }
        return Err(anyhow::anyhow!(
            "Float type inference failed: {} error(s)",
            global_float_inference.errors.len()
        ));
    }

    // Step 4A2: Global int inference pass (same architecture as float)
    let mut global_int_inference = IntInference::new();
    global_int_inference.set_global_function_signatures(global_float_signatures.clone());
    global_int_inference.set_global_struct_field_types(&global_struct_fields);
    global_int_inference.set_struct_defining_module_paths(struct_defining_module_paths);
    global_int_inference.set_module_re_exports(module_re_exports);

    for (file, source) in &sources {
        let mut lexer = Lexer::new(source);
        let tokens = lexer.tokenize_with_locations();
        let mut parser =
            Parser::new_with_source(tokens, file.to_string_lossy().to_string(), source.clone());
        let program = parser
            .parse()
            .map_err(|e| anyhow::anyhow!("Parse error in {}: {}", file.display(), e))?;
        let file_module = crate::analyzer::type_collector::wj_file_to_module_path(&src_base, file)
            .unwrap_or_default();
        global_int_inference.set_current_file_module_path(file_module);
        global_int_inference.infer_program(&program);
    }

    if !global_int_inference.errors.is_empty() {
        for error in &global_int_inference.errors {
            eprintln!("Int inference error: {}", error);
        }
        return Err(anyhow::anyhow!(
            "Int type inference failed: {} error(s)",
            global_int_inference.errors.len()
        ));
    }

    let type_defining_modules =
        super::dependency_resolution::build_type_defining_modules_for_library(&sources, &src_base)?;
    let extern_submodule_qualifiers =
        super::dependency_resolution::build_extern_submodule_qualifier_map(&sources, &src_base)?;

    // Step 4B-pre: Build GLOBAL analyzed_trait_methods across ALL files.
    // Each file's Analyzer is fresh, so cross-file trait info (e.g. RenderPort defined
    // in render_port.wj but implemented in voxel_gpu_renderer.wj) would be missing
    // if we only used per-file analysis. This step mirrors main.rs's finalize_trait_inference.
    //
    // Runs on a separate thread with a large stack because the merged program (~3000 items)
    // can produce deep recursive analysis.
    let global_analyzed_trait_methods = {
        let global_copy_structs_clone = global_copy_structs.clone();
        let sources_for_thread: Vec<(std::path::PathBuf, String)> = sources
            .iter()
            .map(|(p, s)| (p.clone(), s.clone()))
            .collect();

        let handle = std::thread::Builder::new()
            .name("trait-inference".to_string())
            .stack_size(64 * 1024 * 1024)
            .spawn(move || -> Result<HashMap<String, HashMap<String, crate::analyzer::AnalyzedFunction<'static>>>, String> {
                let mut shared_analyzer = Analyzer::new_with_copy_structs(global_copy_structs_clone);

                // Parse ALL files upfront and keep parsers alive. The parser's arena owns AST
                // nodes; dropping a parser frees its arena, invalidating any `&'ast` references.
                // Previously, parsers were created in a loop and dropped each iteration, causing
                // use-after-free (SIGSEGV) when `all_items` held dangling arena references.
                let mut parsers: Vec<Parser> = Vec::with_capacity(sources_for_thread.len());
                let mut programs: Vec<crate::parser::Program<'_>> = Vec::with_capacity(sources_for_thread.len());

                for (_file, source) in &sources_for_thread {
                    let mut lexer = Lexer::new(source);
                    let tokens = lexer.tokenize_with_locations();
                    let parser = Parser::new_with_source(
                        tokens,
                        String::new(),
                        source.clone(),
                    );
                    parsers.push(parser);
                }

                for parser in &mut parsers {
                    if let Ok(program) = parser.parse() {
                        programs.push(program);
                    }
                }

                for program in &programs {
                    shared_analyzer.register_traits_from_program(program)
                        .unwrap_or_else(|e| eprintln!("Trait registration warning: {}", e));
                }

                let mut all_items = Vec::new();
                for program in programs {
                    all_items.extend(program.items);
                }

                let merged_program = crate::parser::Program { items: all_items };
                shared_analyzer.infer_trait_signatures_from_impls(&merged_program)?;
                // parsers (and their arenas) are dropped here, AFTER analysis is complete
                Ok(shared_analyzer.analyzed_trait_methods.clone())
            })
            .map_err(|e| anyhow::anyhow!("Failed to spawn trait inference thread: {}", e))?;

        match handle.join() {
            Ok(Ok(methods)) => methods,
            Ok(Err(e)) => {
                eprintln!("Cross-file trait inference warning: {}", e);
                HashMap::new()
            }
            Err(_) => {
                eprintln!("⚠️  Global trait inference thread panicked (stack overflow?) — skipping cross-file trait methods.");
                HashMap::new()
            }
        }
    };

    // Step 4B: Final analysis + code generation (using shared global_float_inference)
    for (file, source) in sources.iter() {
        // Final parse
        let mut lexer = Lexer::new(source);
        let tokens = lexer.tokenize_with_locations();
        let mut parser =
            Parser::new_with_source(tokens, file.to_string_lossy().to_string(), source.clone());
        let mut program = parser
            .parse()
            .map_err(|e| anyhow::anyhow!("Parse error: {}", e))?;

        // Strip Item::Mod entries for modules that were filtered out (e.g., shaders).
        // This prevents generating invalid `pub mod X;` declarations in the first
        // place, rather than cleaning them up post-hoc.
        if let Some(parent_dir) = file.parent() {
            if let Some(filtered_names) = filtered_modules_by_dir.get(parent_dir) {
                program.items = super::strip_filtered_mod_items(program.items, filtered_names);
            }
        }

        let mut analyzer = Analyzer::new_with_copy_structs(global_copy_structs.clone());
        analyzer.set_global_struct_field_types(global_struct_fields.clone());

        // Rust leakage linter
        if enable_lint {
            let file_name = file.to_string_lossy().to_string();
            let mut rust_leakage = RustLeakageLinter::new(&file_name);
            rust_leakage.lint_program(&program);
            for diag in rust_leakage.diagnostics() {
                eprintln!("{}", diag);
            }
        }

        // Register traits so per-file analysis can resolve trait contracts
        analyzer
            .register_traits_from_program(&program)
            .unwrap_or_else(|e| eprintln!("Trait registration warning: {}", e));

        // Final analysis with converged registry
        let (analyzed_functions, registry, _) = analyzer
            .analyze_program_with_global_signatures(&program, &global_registry)
            .map_err(|e| anyhow::anyhow!("Final analysis error: {}", e))?;

        analyzer
            .infer_trait_signatures_from_impls(&program)
            .map_err(|e| anyhow::anyhow!("{}", e))?;

        // Merge per-file trait analysis with global cross-file trait methods.
        // Global takes priority (it has the merged view from ALL implementations).
        let mut merged_trait_methods = analyzer.analyzed_trait_methods.clone();
        for (trait_name, methods) in &global_analyzed_trait_methods {
            let entry = merged_trait_methods.entry(trait_name.clone()).or_default();
            for (method_name, method_analysis) in methods {
                entry.insert(method_name.clone(), method_analysis.clone());
            }
        }

        // Preserve directory structure (directory-module layout when `foo.wj` + `foo/*.wj` co-exist).
        // In library mode, mod.wj output goes to _mod_items.rs so --module-file doesn't overwrite it.
        let output_file =
            crate::project_paths::resolve_wj_output_path_library(&src_base, file, output)?;
        if let Some(parent) = output_file.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Library-style modules: `use super::*` + automatic sibling `use super::Type` imports.
        // Use the global registry (all cross-file signatures) merged with the per-file registry
        // so that method calls to other files' types resolve correctly for auto-borrowing.
        let mut full_registry = global_registry.clone();
        full_registry.merge(&registry);
        let registry_snapshot = full_registry.clone();
        let mut codegen = CodeGenerator::new_for_module(full_registry, target);
        codegen.set_copy_types_registry(global_copy_structs.clone());
        codegen.set_global_struct_field_types(global_struct_fields.clone());
        codegen.set_output_file(&output_file);
        codegen.set_source_file(file);
        codegen.set_library_source_root(src_base.clone());
        codegen.set_type_defining_modules(type_defining_modules.clone());
        codegen.set_extern_submodule_qualifiers(extern_submodule_qualifiers.clone());
        codegen.set_analyzed_trait_methods(merged_trait_methods);
        codegen.set_float_inference(global_float_inference.clone());
        codegen.set_int_inference(global_int_inference.clone());

        // Trait bound inference for this file's functions
        let mut trait_inference = crate::inference::InferenceEngine::new();
        let mut inferred_bounds_map = std::collections::HashMap::new();
        for item in &program.items {
            if let Item::Function { decl: func, .. } = item {
                let bounds = trait_inference.infer_function_bounds(func);
                if !bounds.is_empty() {
                    inferred_bounds_map.insert(func.name.clone(), bounds);
                }
            }
            if let Item::Impl { block, .. } = item {
                for func in &block.functions {
                    let bounds = trait_inference.infer_function_bounds(func);
                    if !bounds.is_empty() {
                        inferred_bounds_map.insert(func.name.clone(), bounds);
                    }
                }
            }
        }
        codegen.set_inferred_bounds(inferred_bounds_map);

        let rust_code = codegen.generate_program(&program, &analyzed_functions);
        super::cache_management::write_if_changed(&output_file, &rust_code)?;

        // Write .wj.meta with inferred ownership for cross-file calls
        if target == CompilationTarget::Rust {
            let module_name = file
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("unknown");
            let mut meta = ModuleMetadata::new(module_name.to_string());
            for item in &program.items {
                match item {
                    Item::Function { decl, .. } => {
                        if let Some(sig) = registry_snapshot.get_signature(&decl.name) {
                            meta.functions.insert(
                                decl.name.clone(),
                                metadata_function_sig_from_analyzer(sig, false, None),
                            );
                        }
                    }
                    Item::Impl { block, .. } => {
                        for func_decl in &block.functions {
                            let full_name = format!("{}::{}", block.type_name, func_decl.name);
                            if let Some(sig) = registry_snapshot.get_signature(&full_name) {
                                meta.functions.insert(
                                    full_name,
                                    metadata_function_sig_from_analyzer(
                                        sig,
                                        true,
                                        Some(block.type_name.clone()),
                                    ),
                                );
                            }
                        }
                    }
                    Item::Struct { decl, .. } => {
                        let mut fields = std::collections::HashMap::new();
                        for field in &decl.fields {
                            fields.insert(
                                field.name.clone(),
                                ModuleMetadata::serialize_type(&field.field_type),
                            );
                        }
                        meta.structs.insert(decl.name.clone(), fields);
                    }
                    _ => {}
                }
            }
            meta.copy_structs = analyzer.get_copy_structs();
            let meta_path = meta_cache_path(file);
            if let Some(parent) = meta_path.parent() {
                let _ = std::fs::create_dir_all(parent);
            }
            if let Ok(json) = serde_json::to_string_pretty(&meta) {
                let _ = super::cache_management::write_if_changed(&meta_path, &json);
            }
        }
    }

    // Emit metadata.json
    if library && (!crate_metadata.structs.is_empty() || !crate_metadata.functions.is_empty()) {
        let metadata_path = output.join("metadata.json");
        let metadata_json = serde_json::to_string_pretty(&crate_metadata)?;
        super::cache_management::write_if_changed(&metadata_path, &metadata_json)?;
    }

    // Generate mod.rs (and lib.rs) so individual module files are tied
    // together as submodules. Without this, `use super::*;` in generated
    // files would fail because Cargo wouldn't know about the crate structure.
    if target == CompilationTarget::Rust {
        crate::build_utils::generate_mod_file_with_layout(
            output,
            Some((output, src_base.as_path())),
        )?;
    }

    // Always (re)generate Cargo.toml in the output directory for Rust builds.
    if target == CompilationTarget::Rust {
        // Clean stale nested Cargo.toml files left by older compiler versions.
        // Only the root Cargo.toml is valid; nested ones confuse Cargo into
        // treating subdirectories as separate packages (cyclic dependency errors).
        super::cache_management::clean_nested_cargo_toml(output);

        let source_dir = if base_path.is_file() {
            base_path.parent().unwrap_or(base_path)
        } else {
            base_path
        };
        crate::cargo_toml::generate_single_file_cargo_toml(output, source_dir, target)?;
    }

    if target == CompilationTarget::Wasm {
        let source_dir = if base_path.is_file() {
            base_path.parent().unwrap_or(base_path)
        } else {
            base_path
        };
        crate::cargo_toml::generate_wasm_cargo_toml(output, source_dir)?;
    }

    Ok(())
}