ruchy 4.1.1

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
//! AST Analysis and Collection Functions
//!
//! This module handles AST analysis tasks for the transpiler:
//! - Mutability analysis: detecting which variables need `mut`
//! - Const collection: tracking const declarations
//! - Function signature collection: building signature map for type coercion
//! - Module name collection: tracking module declarations
//! - Import detection and resolution
//! - AST content detection (`HashMap`, `DataFrame`, etc.)
//!
//! **EXTREME TDD Round 66**: Extracted from mod.rs for modularization.

#![allow(clippy::doc_markdown)]

use super::{FunctionSignature, Transpiler};
use crate::backend::module_resolver::ModuleResolver;
use crate::frontend::ast::{Expr, ExprKind, Type, TypeKind};
use anyhow::Result;

impl Transpiler {
    // ========================================================================
    // Mutability Analysis
    // ========================================================================

    /// Analyzes expressions to determine which variables need mutable bindings.
    ///
    /// This performs a static analysis pass over the AST to identify variables
    /// that are assigned to after their initial declaration, marking them as
    /// requiring `mut` in the generated Rust code.
    ///
    /// # Arguments
    ///
    /// * `exprs` - The expressions to analyze for mutability
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let mut transpiler = Transpiler::new();
    /// transpiler.analyze_mutability(&ast_expressions);
    /// assert!(transpiler.mutable_vars.contains("counter"));
    /// ```
    pub fn analyze_mutability(&mut self, exprs: &[Expr]) {
        for expr in exprs {
            self.analyze_expr_mutability(expr);
        }
    }

    /// Analyze mutability for a single expression (complexity: 9)
    pub fn analyze_expr_mutability(&mut self, expr: &Expr) {
        match &expr.kind {
            ExprKind::Assign { target, value } => {
                self.mark_target_mutable(target);
                self.analyze_expr_mutability(value);
            }
            ExprKind::CompoundAssign { target, value, .. } => {
                self.mark_target_mutable(target);
                self.analyze_expr_mutability(value);
            }
            ExprKind::PreIncrement { target }
            | ExprKind::PostIncrement { target }
            | ExprKind::PreDecrement { target }
            | ExprKind::PostDecrement { target } => {
                self.mark_target_mutable(target);
            }
            ExprKind::Block(exprs) => {
                self.analyze_block_mutability(exprs);
            }
            ExprKind::If {
                condition,
                then_branch,
                else_branch,
            } => {
                self.analyze_if_mutability(condition, then_branch, else_branch.as_deref());
            }
            ExprKind::While {
                condition, body, ..
            } => {
                self.analyze_two_expr_mutability(condition, body);
            }
            ExprKind::For { body, iter, .. } => {
                self.analyze_two_expr_mutability(iter, body);
            }
            ExprKind::Match { expr, arms } => {
                self.analyze_match_mutability(expr, arms);
            }
            ExprKind::Let { body, value, .. } | ExprKind::LetPattern { body, value, .. } => {
                self.analyze_two_expr_mutability(value, body);
            }
            ExprKind::Function { body, .. } | ExprKind::Lambda { body, .. } => {
                self.analyze_expr_mutability(body);
            }
            ExprKind::Binary { left, right, .. } => {
                self.analyze_two_expr_mutability(left, right);
            }
            ExprKind::Unary { operand, .. } => {
                self.analyze_expr_mutability(operand);
            }
            ExprKind::Call { func, args } => {
                self.analyze_call_mutability(func, args);
            }
            ExprKind::MethodCall { receiver, args, .. } => {
                self.analyze_call_mutability(receiver, args);
            }
            _ => {}
        }
    }

    /// Mark an expression target as mutable (complexity: 2)
    pub fn mark_target_mutable(&mut self, target: &Expr) {
        if let ExprKind::Identifier(name) = &target.kind {
            self.mutable_vars.insert(name.clone());
        }
    }

    /// Analyze mutability for block expressions (complexity: 1)
    pub fn analyze_block_mutability(&mut self, exprs: &[Expr]) {
        for e in exprs {
            self.analyze_expr_mutability(e);
        }
    }

    /// Analyze mutability for if expressions (complexity: 2)
    pub fn analyze_if_mutability(
        &mut self,
        condition: &Expr,
        then_branch: &Expr,
        else_branch: Option<&Expr>,
    ) {
        self.analyze_expr_mutability(condition);
        self.analyze_expr_mutability(then_branch);
        if let Some(else_expr) = else_branch {
            self.analyze_expr_mutability(else_expr);
        }
    }

    /// Analyze mutability for two related expressions (complexity: 1)
    pub fn analyze_two_expr_mutability(&mut self, expr1: &Expr, expr2: &Expr) {
        self.analyze_expr_mutability(expr1);
        self.analyze_expr_mutability(expr2);
    }

    /// Analyze mutability for match expressions (complexity: 1)
    pub fn analyze_match_mutability(
        &mut self,
        expr: &Expr,
        arms: &[crate::frontend::ast::MatchArm],
    ) {
        self.analyze_expr_mutability(expr);
        for arm in arms {
            self.analyze_expr_mutability(&arm.body);
        }
    }

    /// Analyze mutability for call expressions (complexity: 1)
    pub fn analyze_call_mutability(&mut self, func: &Expr, args: &[Expr]) {
        self.analyze_expr_mutability(func);
        for arg in args {
            self.analyze_expr_mutability(arg);
        }
    }

    // ========================================================================
    // Const Declaration Collection
    // ========================================================================

    /// SPEC-001-B: Collects const declarations BEFORE optimization (preserves attributes)
    ///
    /// # Purpose
    /// Const declarations have a `const` attribute that gets stripped by optimization passes.
    /// We must collect them here to generate module-level const declarations later.
    pub fn collect_const_declarations(&mut self, exprs: &[Expr]) {
        for expr in exprs {
            self.collect_const_declarations_from_expr(expr);
        }
    }

    /// SPEC-001-B: Collect const declarations from a single expression
    pub fn collect_const_declarations_from_expr(&mut self, expr: &Expr) {
        if let ExprKind::Let { name, .. } = &expr.kind {
            // Check for const attribute (before it's lost in optimization)
            let is_const = expr.attributes.iter().any(|attr| attr.name == "const");
            if is_const {
                self.const_vars
                    .write()
                    .expect("rwlock should not be poisoned")
                    .insert(name.clone());
            }
        }
        // Recursively check nested expressions
        match &expr.kind {
            ExprKind::Block(exprs) => {
                for e in exprs {
                    self.collect_const_declarations_from_expr(e);
                }
            }
            ExprKind::Function { body, .. } => {
                self.collect_const_declarations_from_expr(body);
            }
            _ => {}
        }
    }

    // ========================================================================
    // Function Signature Collection
    // ========================================================================

    /// Collects function signatures from the AST for type coercion.
    ///
    /// Scans the AST for function definitions and records their signatures
    /// to enable automatic type conversions when these functions are called
    /// with arguments of compatible but different types.
    ///
    /// # Arguments
    ///
    /// * `exprs` - The expressions to scan for function definitions
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let mut transpiler = Transpiler::new();
    /// transpiler.collect_function_signatures(&ast_expressions);
    /// // Now the transpiler knows about all function signatures
    /// ```
    pub fn collect_function_signatures(&mut self, exprs: &[Expr]) {
        for expr in exprs {
            self.collect_signatures_from_expr(expr);
        }
    }

    /// Helper to recursively collect function signatures from an expression
    pub fn collect_signatures_from_expr(&mut self, expr: &Expr) {
        match &expr.kind {
            ExprKind::Function { name, params, .. } => {
                let param_types: Vec<String> = params
                    .iter()
                    .map(|param| Self::type_to_string(&param.ty))
                    .collect();
                let signature = FunctionSignature {
                    name: name.clone(),
                    param_types,
                };
                self.function_signatures.insert(name.clone(), signature);
            }
            ExprKind::Block(exprs) => {
                for e in exprs {
                    self.collect_signatures_from_expr(e);
                }
            }
            ExprKind::Let { body, .. } => {
                self.collect_signatures_from_expr(body);
            }
            _ => {}
        }
    }

    /// Convert a Type AST node to a string representation
    pub fn type_to_string(ty: &Type) -> String {
        match &ty.kind {
            TypeKind::Named(name) => name.clone(),
            // DEFECT-024 FIX: Handle generic types like Option<i32>, Result<T, E>
            TypeKind::Generic { base, params } => {
                if params.is_empty() {
                    base.clone()
                } else {
                    let param_strs: Vec<String> = params.iter().map(Self::type_to_string).collect();
                    format!("{}<{}>", base, param_strs.join(", "))
                }
            }
            TypeKind::Reference { inner, .. } => format!("&{}", Self::type_to_string(inner)),
            // BOOK-COMPAT-017: Handle array types [T; N] for signature lookup
            TypeKind::Array { elem_type, size } => {
                format!("[{}; {}]", Self::type_to_string(elem_type), size)
            }
            // Handle list types Vec<T>
            TypeKind::List(elem_type) => {
                format!("Vec<{}>", Self::type_to_string(elem_type))
            }
            _ => "Unknown".to_string(),
        }
    }

    // ========================================================================
    // Module Name Collection
    // ========================================================================

    /// Collects module names from the AST (Issue #103).
    ///
    /// Scans the AST for module declarations and records their names
    /// so field access can use :: syntax for module paths.
    ///
    /// # Arguments
    ///
    /// * `exprs` - The expressions to scan for module declarations
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let mut transpiler = Transpiler::new();
    /// transpiler.collect_module_names(&ast_expressions);
    /// // Now the transpiler knows which identifiers are modules
    /// ```
    pub fn collect_module_names(&mut self, exprs: &[Expr]) {
        for expr in exprs {
            self.collect_module_names_from_expr(expr);
        }
    }

    /// Helper to recursively collect module names from an expression
    pub fn collect_module_names_from_expr(&mut self, expr: &Expr) {
        match &expr.kind {
            ExprKind::Module { name, body } => {
                self.module_names.insert(name.clone());
                self.collect_module_names_from_expr(body);
            }
            ExprKind::Block(exprs) => {
                for e in exprs {
                    self.collect_module_names_from_expr(e);
                }
            }
            _ => {}
        }
    }

    // ========================================================================
    // Import Resolution
    // ========================================================================

    /// Resolves file imports in the AST using `ModuleResolver`
    #[allow(dead_code)]
    pub fn resolve_imports(&self, expr: &Expr) -> Result<Expr> {
        // For now, just use default search paths since we don't have file context here
        let mut resolver = ModuleResolver::new();
        resolver.resolve_imports(expr.clone())
    }

    /// Resolves file imports with a specific file context for search paths
    pub fn resolve_imports_with_context(
        &self,
        expr: &Expr,
        file_path: Option<&std::path::Path>,
    ) -> Result<Expr> {
        // Check if expression contains any file imports that need resolution
        if !Self::contains_file_imports(expr) {
            // No file imports to resolve, return original expression to preserve attributes
            return Ok(expr.clone());
        }

        let mut resolver = ModuleResolver::new();
        // Add the file's directory to search paths if provided
        if let Some(path) = file_path {
            if let Some(dir) = path.parent() {
                resolver.add_search_path(dir);
            }
        }
        resolver.resolve_imports(expr.clone())
    }

    /// Check if an expression tree contains any import statements
    pub fn contains_imports(expr: &Expr) -> bool {
        match &expr.kind {
            ExprKind::Import { .. }
            | ExprKind::ImportAll { .. }
            | ExprKind::ImportDefault { .. } => true,
            ExprKind::Block(exprs) => exprs.iter().any(Self::contains_imports),
            _ => false,
        }
    }

    /// Check if an expression tree contains any file imports (local .ruchy files)
    pub fn contains_file_imports(expr: &Expr) -> bool {
        match &expr.kind {
            // ISSUE-106 FIX: ModuleDeclaration (mod name;) needs file resolution
            ExprKind::ModuleDeclaration { .. } => true,
            ExprKind::Import { module, .. }
            | ExprKind::ImportAll { module, .. }
            | ExprKind::ImportDefault { module, .. } => {
                // File imports typically start with ./ or ../ or are single identifiers
                // Standard library imports contain :: or are known std libs
                module.starts_with("./")
                    || module.starts_with("../")
                    || (!module.contains("::")
                        && !module.contains('.')
                        && !Self::is_standard_library(module))
            }
            ExprKind::Block(exprs) => exprs.iter().any(Self::contains_file_imports),
            _ => false,
        }
    }

    /// Check if a module is a standard library
    pub fn is_standard_library(module: &str) -> bool {
        matches!(
            module,
            "std"
                | "core"
                | "alloc"
                | "numpy"
                | "pandas"
                | "polars"
                | "serde"
                | "serde_json"
                | "tokio"
                | "async_std"
                | "futures"
                | "rayon"
                | "regex"
                | "chrono"
                | "rand"
                | "log"
                | "env_logger"
        )
    }

    // ========================================================================
    // AST Content Detection
    // ========================================================================

    /// Check if AST contains `HashMap` operations requiring `std::collections::HashMap` import
    pub fn contains_hashmap(expr: &Expr) -> bool {
        match &expr.kind {
            ExprKind::ObjectLiteral { .. } => true,
            ExprKind::Call { func, .. } => {
                // Check for HashMap methods like .get(), .insert(), etc.
                if let ExprKind::Identifier(name) = &func.kind {
                    if name.starts_with("HashMap") {
                        return true;
                    }
                }
                false
            }
            ExprKind::Block(exprs) => exprs.iter().any(Self::contains_hashmap),
            ExprKind::Let { value, body, .. } => {
                Self::contains_hashmap(value) || Self::contains_hashmap(body)
            }
            ExprKind::Function { body, .. } => Self::contains_hashmap(body),
            ExprKind::If {
                condition,
                then_branch,
                else_branch,
            } => {
                Self::contains_hashmap(condition)
                    || Self::contains_hashmap(then_branch)
                    || else_branch
                        .as_ref()
                        .is_some_and(|e| Self::contains_hashmap(e))
            }
            _ => false,
        }
    }

    /// Check if AST contains `DataFrame` operations requiring polars import
    pub fn contains_dataframe(expr: &Expr) -> bool {
        match &expr.kind {
            ExprKind::Call { func, .. } => {
                // Check for DataFrame constructors and methods
                if let ExprKind::Identifier(name) = &func.kind {
                    if name.starts_with("DataFrame") || name == "col" || name == "lit" {
                        return true;
                    }
                }
                // Check for qualified names like DataFrame::new
                if let ExprKind::QualifiedName { module, .. } = &func.kind {
                    if module == "DataFrame" {
                        return true;
                    }
                }
                false
            }
            ExprKind::MethodCall {
                receiver, method, ..
            } => {
                // DataFrame-specific methods (don't exist on iterators)
                let is_df_only_method = matches!(
                    method.as_str(),
                    "select"
                        | "groupby"
                        | "group_by"
                        | "agg"
                        | "column"
                        | "build"
                        | "rows"
                        | "columns"
                        | "lazy"
                        | "collect"
                        | "with_column"
                        | "drop"
                        | "join"
                        | "vstack"
                        | "hstack"
                );
                if is_df_only_method {
                    return true;
                }
                // Common methods (filter, sum, min, max, etc.) - only count as DataFrame
                // if the receiver is already detected as a DataFrame
                let is_common_method = matches!(
                    method.as_str(),
                    "filter"
                        | "sort"
                        | "head"
                        | "tail"
                        | "mean"
                        | "std"
                        | "min"
                        | "max"
                        | "sum"
                        | "count"
                );
                if is_common_method {
                    // Only return true if receiver is a DataFrame
                    return Self::contains_dataframe(receiver);
                }
                false
            }
            ExprKind::Block(exprs) => exprs.iter().any(Self::contains_dataframe),
            ExprKind::Let { value, body, .. } => {
                Self::contains_dataframe(value) || Self::contains_dataframe(body)
            }
            ExprKind::Function { body, .. } => Self::contains_dataframe(body),
            ExprKind::If {
                condition,
                then_branch,
                else_branch,
            } => {
                Self::contains_dataframe(condition)
                    || Self::contains_dataframe(then_branch)
                    || else_branch
                        .as_ref()
                        .is_some_and(|e| Self::contains_dataframe(e))
            }
            _ => false,
        }
    }

    /// TRANSPILER-009: Check if expression contains standalone user-defined functions
    /// Returns true if this is a Block with Function definitions (not inside impl/class)
    /// Used to skip aggressive optimizations that would inline/eliminate user functions
    pub fn has_standalone_functions(expr: &Expr) -> bool {
        match &expr.kind {
            // A Block with Function expressions => has standalone functions
            ExprKind::Block(exprs) => exprs
                .iter()
                .any(|e| matches!(&e.kind, ExprKind::Function { .. })),
            // Single top-level Function
            ExprKind::Function { .. } => true,
            _ => false,
        }
    }

    // ========================================================================
    // Call-Site Argument Type Collection (BOOK-COMPAT-017)
    // ========================================================================

    /// BOOK-COMPAT-017: Collect call-site argument types for parameter inference
    ///
    /// When functions have untyped parameters, we can infer their types from
    /// how the function is called. For example, if `divide(a, b)` is called
    /// with `divide(10.5, 2.5)`, we infer that both parameters are f64.
    pub fn collect_call_site_types(&self, exprs: &[Expr]) {
        for expr in exprs {
            self.collect_call_site_types_from_expr(expr);
        }
    }

    /// BOOK-COMPAT-017: Helper to recursively collect call-site types from an expression
    fn collect_call_site_types_from_expr(&self, expr: &Expr) {
        match &expr.kind {
            ExprKind::Call { func, args } => {
                // Check if this is a direct function call (not a method call)
                if let ExprKind::Identifier(func_name) = &func.kind {
                    let arg_types: Vec<String> = args
                        .iter()
                        .map(Self::infer_arg_type)
                        .collect();
                    // Only store if we inferred at least one concrete type
                    if arg_types.iter().any(|t| t != "_") {
                        self.call_site_arg_types
                            .borrow_mut()
                            .insert(func_name.clone(), arg_types);
                    }
                }
                // Recurse into arguments
                for arg in args {
                    self.collect_call_site_types_from_expr(arg);
                }
                self.collect_call_site_types_from_expr(func);
            }
            ExprKind::Block(exprs) => {
                for e in exprs {
                    self.collect_call_site_types_from_expr(e);
                }
            }
            ExprKind::Function { body, .. } => {
                self.collect_call_site_types_from_expr(body);
            }
            ExprKind::Let { value, body, .. } | ExprKind::LetPattern { value, body, .. } => {
                self.collect_call_site_types_from_expr(value);
                self.collect_call_site_types_from_expr(body);
            }
            ExprKind::If {
                condition,
                then_branch,
                else_branch,
            } => {
                self.collect_call_site_types_from_expr(condition);
                self.collect_call_site_types_from_expr(then_branch);
                if let Some(eb) = else_branch {
                    self.collect_call_site_types_from_expr(eb);
                }
            }
            ExprKind::While { condition, body, .. } => {
                self.collect_call_site_types_from_expr(condition);
                self.collect_call_site_types_from_expr(body);
            }
            ExprKind::For { iter, body, .. } => {
                self.collect_call_site_types_from_expr(iter);
                self.collect_call_site_types_from_expr(body);
            }
            ExprKind::Binary { left, right, .. } => {
                self.collect_call_site_types_from_expr(left);
                self.collect_call_site_types_from_expr(right);
            }
            _ => {}
        }
    }

    /// BOOK-COMPAT-017: Infer argument type from a literal expression
    fn infer_arg_type(expr: &Expr) -> String {
        match &expr.kind {
            ExprKind::Literal(crate::frontend::ast::Literal::Float(..)) => "f64".to_string(),
            ExprKind::Literal(crate::frontend::ast::Literal::Integer(_, Some(suffix))) => {
                suffix.clone()
            }
            ExprKind::Literal(crate::frontend::ast::Literal::Integer(..)) => "i32".to_string(),
            ExprKind::Literal(crate::frontend::ast::Literal::String(..)) => "String".to_string(),
            ExprKind::Literal(crate::frontend::ast::Literal::Bool(..)) => "bool".to_string(),
            ExprKind::List(elements) => {
                if elements.is_empty() {
                    "Vec<_>".to_string()
                } else {
                    let elem_type = Self::infer_arg_type(&elements[0]);
                    format!("Vec<{}>", elem_type)
                }
            }
            _ => "_".to_string(),
        }
    }

    /// BOOK-COMPAT-017: Get call-site argument type for a function parameter
    pub fn get_call_site_param_type(&self, func_name: &str, param_index: usize) -> Option<String> {
        let call_site_types = self.call_site_arg_types.borrow();
        if let Some(arg_types) = call_site_types.get(func_name) {
            arg_types.get(param_index).cloned()
        } else {
            None
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frontend::ast::{Literal, Span};

    fn make_expr(kind: ExprKind) -> Expr {
        Expr {
            kind,
            span: Span::default(),
            attributes: vec![],
            leading_comments: vec![],
            trailing_comment: None,
        }
    }

    fn ident_expr(name: &str) -> Expr {
        make_expr(ExprKind::Identifier(name.to_string()))
    }

    fn int_expr(n: i64) -> Expr {
        make_expr(ExprKind::Literal(Literal::Integer(n, None)))
    }

    fn block_expr(exprs: Vec<Expr>) -> Expr {
        make_expr(ExprKind::Block(exprs))
    }

    fn assign_expr(target: Expr, value: Expr) -> Expr {
        make_expr(ExprKind::Assign {
            target: Box::new(target),
            value: Box::new(value),
        })
    }

    // ========================================================================
    // Mutability Analysis Tests
    // ========================================================================

    #[test]
    fn test_analyze_mutability_empty() {
        let mut transpiler = Transpiler::new();
        transpiler.analyze_mutability(&[]);
        assert!(transpiler.mutable_vars.is_empty());
    }

    #[test]
    fn test_analyze_mutability_simple_assign() {
        let mut transpiler = Transpiler::new();
        let exprs = vec![assign_expr(ident_expr("x"), int_expr(5))];
        transpiler.analyze_mutability(&exprs);
        assert!(transpiler.mutable_vars.contains("x"));
    }

    #[test]
    fn test_analyze_mutability_block() {
        let mut transpiler = Transpiler::new();
        let exprs = vec![block_expr(vec![assign_expr(ident_expr("y"), int_expr(10))])];
        transpiler.analyze_mutability(&exprs);
        assert!(transpiler.mutable_vars.contains("y"));
    }

    #[test]
    fn test_mark_target_mutable() {
        let mut transpiler = Transpiler::new();
        transpiler.mark_target_mutable(&ident_expr("counter"));
        assert!(transpiler.mutable_vars.contains("counter"));
    }

    #[test]
    fn test_mark_target_mutable_non_ident() {
        let mut transpiler = Transpiler::new();
        transpiler.mark_target_mutable(&int_expr(42));
        assert!(transpiler.mutable_vars.is_empty());
    }

    #[test]
    fn test_analyze_block_mutability_empty() {
        let mut transpiler = Transpiler::new();
        transpiler.analyze_block_mutability(&[]);
        assert!(transpiler.mutable_vars.is_empty());
    }

    #[test]
    fn test_analyze_if_mutability() {
        let mut transpiler = Transpiler::new();
        let condition = int_expr(1);
        let then_branch = assign_expr(ident_expr("a"), int_expr(1));
        let else_branch = assign_expr(ident_expr("b"), int_expr(2));
        transpiler.analyze_if_mutability(&condition, &then_branch, Some(&else_branch));
        assert!(transpiler.mutable_vars.contains("a"));
        assert!(transpiler.mutable_vars.contains("b"));
    }

    #[test]
    fn test_analyze_two_expr_mutability() {
        let mut transpiler = Transpiler::new();
        let expr1 = assign_expr(ident_expr("x"), int_expr(1));
        let expr2 = assign_expr(ident_expr("y"), int_expr(2));
        transpiler.analyze_two_expr_mutability(&expr1, &expr2);
        assert!(transpiler.mutable_vars.contains("x"));
        assert!(transpiler.mutable_vars.contains("y"));
    }

    #[test]
    fn test_analyze_call_mutability() {
        let mut transpiler = Transpiler::new();
        let func = ident_expr("foo");
        let args = vec![assign_expr(ident_expr("arg"), int_expr(1))];
        transpiler.analyze_call_mutability(&func, &args);
        assert!(transpiler.mutable_vars.contains("arg"));
    }

    // ========================================================================
    // Collection Tests
    // ========================================================================

    #[test]
    fn test_collect_const_declarations_empty() {
        let mut transpiler = Transpiler::new();
        transpiler.collect_const_declarations(&[]);
        assert!(transpiler.const_vars.read().expect("rwlock").is_empty());
    }

    #[test]
    fn test_collect_function_signatures_empty() {
        let mut transpiler = Transpiler::new();
        transpiler.collect_function_signatures(&[]);
        assert!(transpiler.function_signatures.is_empty());
    }

    #[test]
    fn test_collect_module_names_empty() {
        let mut transpiler = Transpiler::new();
        transpiler.collect_module_names(&[]);
        assert!(transpiler.module_names.is_empty());
    }

    #[test]
    fn test_type_to_string_named() {
        let ty = Type {
            kind: TypeKind::Named("i32".to_string()),
            span: Span::default(),
        };
        assert_eq!(Transpiler::type_to_string(&ty), "i32");
    }

    #[test]
    fn test_type_to_string_generic() {
        let inner = Type {
            kind: TypeKind::Named("i32".to_string()),
            span: Span::default(),
        };
        let ty = Type {
            kind: TypeKind::Generic {
                base: "Option".to_string(),
                params: vec![inner],
            },
            span: Span::default(),
        };
        assert_eq!(Transpiler::type_to_string(&ty), "Option<i32>");
    }

    #[test]
    fn test_type_to_string_reference() {
        let inner = Type {
            kind: TypeKind::Named("str".to_string()),
            span: Span::default(),
        };
        let ty = Type {
            kind: TypeKind::Reference {
                inner: Box::new(inner),
                is_mut: false,
                lifetime: None,
            },
            span: Span::default(),
        };
        assert_eq!(Transpiler::type_to_string(&ty), "&str");
    }

    // ========================================================================
    // Import Detection Tests
    // ========================================================================

    #[test]
    fn test_contains_imports_false() {
        let expr = int_expr(42);
        assert!(!Transpiler::contains_imports(&expr));
    }

    #[test]
    fn test_contains_imports_true() {
        let expr = make_expr(ExprKind::Import {
            module: "std::fs".to_string(),
            items: None,
        });
        assert!(Transpiler::contains_imports(&expr));
    }

    #[test]
    fn test_contains_file_imports_relative() {
        let expr = make_expr(ExprKind::Import {
            module: "./helper".to_string(),
            items: None,
        });
        assert!(Transpiler::contains_file_imports(&expr));
    }

    #[test]
    fn test_contains_file_imports_parent() {
        let expr = make_expr(ExprKind::Import {
            module: "../utils".to_string(),
            items: None,
        });
        assert!(Transpiler::contains_file_imports(&expr));
    }

    #[test]
    fn test_contains_file_imports_std_false() {
        let expr = make_expr(ExprKind::Import {
            module: "std".to_string(),
            items: None,
        });
        assert!(!Transpiler::contains_file_imports(&expr));
    }

    #[test]
    fn test_is_standard_library_std() {
        assert!(Transpiler::is_standard_library("std"));
        assert!(Transpiler::is_standard_library("core"));
        assert!(Transpiler::is_standard_library("polars"));
    }

    #[test]
    fn test_is_standard_library_false() {
        assert!(!Transpiler::is_standard_library("my_module"));
        assert!(!Transpiler::is_standard_library("helper"));
    }

    // ========================================================================
    // AST Content Detection Tests
    // ========================================================================

    #[test]
    fn test_contains_hashmap_false() {
        let expr = int_expr(42);
        assert!(!Transpiler::contains_hashmap(&expr));
    }

    #[test]
    fn test_contains_hashmap_object_literal() {
        let expr = make_expr(ExprKind::ObjectLiteral { fields: vec![] });
        assert!(Transpiler::contains_hashmap(&expr));
    }

    #[test]
    fn test_contains_dataframe_false() {
        let expr = int_expr(42);
        assert!(!Transpiler::contains_dataframe(&expr));
    }

    #[test]
    fn test_contains_dataframe_col() {
        let expr = make_expr(ExprKind::Call {
            func: Box::new(ident_expr("col")),
            args: vec![],
        });
        assert!(Transpiler::contains_dataframe(&expr));
    }

    #[test]
    fn test_has_standalone_functions_false() {
        let expr = int_expr(42);
        assert!(!Transpiler::has_standalone_functions(&expr));
    }

    #[test]
    fn test_has_standalone_functions_single() {
        let func = make_expr(ExprKind::Function {
            name: "test".to_string(),
            type_params: vec![],
            params: vec![],
            body: Box::new(int_expr(1)),
            return_type: None,
            is_async: false,
            is_pub: false,
        });
        assert!(Transpiler::has_standalone_functions(&func));
    }

    #[test]
    fn test_has_standalone_functions_block() {
        let func = make_expr(ExprKind::Function {
            name: "test".to_string(),
            type_params: vec![],
            params: vec![],
            body: Box::new(int_expr(1)),
            return_type: None,
            is_async: false,
            is_pub: false,
        });
        let block = block_expr(vec![func]);
        assert!(Transpiler::has_standalone_functions(&block));
    }
}