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
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
// Trait Bound Inference Engine
//
// This module implements automatic inference of trait bounds for generic type parameters.
// Instead of requiring users to write `fn func<T: Display + Clone>(x: T)`, they can write
// `fn func<T>(x: T)` and the compiler will infer the bounds from usage.
//
// ## Algorithm
//
// 1. **Constraint Collection**: Walk the function body and collect trait requirements
//    - `println!("{}", x)` → requires Display
//    - `x.clone()` → requires Clone
//    - `x + y` → requires Add
//    - etc.
//
// 2. **Constraint Simplification**: Deduplicate and merge constraints per type parameter
//
// 3. **Code Generation**: Generate Rust with inferred bounds added to explicit bounds
//
// ## Example
//
// ```windjammer
// fn print_and_clone<T>(x: T) {
//     println!("{}", x)  // Requires Display
//     let y = x.clone()  // Requires Clone
// }
// ```
//
// Infers: `fn print_and_clone<T: Display + Clone>(x: T)`

use crate::parser::{BinaryOp, Expression, FunctionDecl, Item, Statement, TypeParam};
use std::collections::{HashMap, HashSet};

/// Collect inferred trait bounds for all functions and impl methods in a program.
///
/// This eliminates the duplicated loop pattern found in compilation_pipeline,
/// library_multipass, file_compilation_pipeline, ejector, and compiler_database.
pub fn collect_inferred_bounds(items: &[Item]) -> HashMap<String, InferredBounds> {
    let mut engine = InferenceEngine::new();
    let mut bounds_map = HashMap::new();
    for item in items {
        if let Item::Function { decl: func, .. } = item {
            let bounds = engine.infer_function_bounds(func);
            if !bounds.is_empty() {
                bounds_map.insert(func.name.clone(), bounds);
            }
        }
        if let Item::Impl { block, .. } = item {
            for func in &block.functions {
                let bounds = engine.infer_function_bounds(func);
                if !bounds.is_empty() {
                    bounds_map.insert(func.name.clone(), bounds);
                }
            }
        }
    }
    bounds_map
}

/// A trait constraint on a type parameter
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraitConstraint {
    /// The type parameter name (e.g., "T")
    pub type_param: String,
    /// The trait name (e.g., "Display", "Clone")
    pub trait_name: String,
}

/// Inferred trait bounds for a function
#[derive(Debug, Clone)]
pub struct InferredBounds {
    /// Map from type parameter name to set of trait names
    pub bounds: HashMap<String, HashSet<String>>,
}

impl InferredBounds {
    pub fn new() -> Self {
        InferredBounds {
            bounds: HashMap::new(),
        }
    }

    /// Add a constraint to the inferred bounds
    pub fn add_constraint(&mut self, type_param: String, trait_name: String) {
        self.bounds
            .entry(type_param)
            .or_default()
            .insert(trait_name);
    }

    /// Get sorted trait bounds for a type parameter
    pub fn get_bounds(&self, type_param: &str) -> Vec<String> {
        self.bounds
            .get(type_param)
            .map(|traits| {
                let mut sorted: Vec<_> = traits.iter().cloned().collect();
                sorted.sort();
                sorted
            })
            .unwrap_or_default()
    }

    /// Merge explicit bounds from the AST with inferred bounds
    pub fn merge_with_explicit(&self, type_params: &[TypeParam]) -> Vec<TypeParam> {
        type_params
            .iter()
            .map(|param| {
                let mut merged_bounds = param.bounds.clone();

                // Add inferred bounds that aren't already explicit
                if let Some(inferred) = self.bounds.get(&param.name) {
                    for trait_name in inferred {
                        if !merged_bounds.contains(trait_name) {
                            merged_bounds.push(trait_name.clone());
                        }
                    }
                }

                // Sort for stability
                merged_bounds.sort();

                TypeParam {
                    name: param.name.clone(),
                    bounds: merged_bounds,
                }
            })
            .collect()
    }

    /// Check if any bounds were inferred
    pub fn is_empty(&self) -> bool {
        self.bounds.is_empty()
    }
}

impl Default for InferredBounds {
    fn default() -> Self {
        Self::new()
    }
}

/// Registry entry mapping a method name to the trait it belongs to.
/// This drives trait inference from method calls (e.g., `.clone()` → `Clone`).
struct TraitMethodEntry {
    method: &'static str,
    trait_name: &'static str,
}

/// Known trait methods — extend this table to add new method→trait mappings
/// without modifying any match arms.
static TRAIT_METHOD_REGISTRY: &[TraitMethodEntry] = &[
    TraitMethodEntry {
        method: "clone",
        trait_name: "Clone",
    },
    TraitMethodEntry {
        method: "to_string",
        trait_name: "ToString",
    },
    TraitMethodEntry {
        method: "fmt",
        trait_name: "Display",
    },
    TraitMethodEntry {
        method: "eq",
        trait_name: "PartialEq",
    },
    TraitMethodEntry {
        method: "cmp",
        trait_name: "Ord",
    },
    TraitMethodEntry {
        method: "partial_cmp",
        trait_name: "PartialOrd",
    },
    TraitMethodEntry {
        method: "hash",
        trait_name: "Hash",
    },
    TraitMethodEntry {
        method: "default",
        trait_name: "Default",
    },
    TraitMethodEntry {
        method: "into",
        trait_name: "Into",
    },
];

/// The trait bound inference engine
pub struct InferenceEngine {
    /// Current function's type parameters
    type_params: HashSet<String>,
    /// Map from variable names to their type parameters (e.g., "x" -> "T")
    var_to_type_param: HashMap<String, String>,
}

impl InferenceEngine {
    pub fn new() -> Self {
        InferenceEngine {
            type_params: HashSet::new(),
            var_to_type_param: HashMap::new(),
        }
    }

    /// Infer trait bounds for a function
    pub fn infer_function_bounds(&mut self, func: &FunctionDecl) -> InferredBounds {
        // If function has explicit where clause, skip inference to avoid conflicts
        // This is important for associated type bounds like `where P::Output: Display`
        // where we don't want to accidentally infer `P: Display` for the base type
        if !func.where_clause.is_empty() {
            return InferredBounds::new();
        }

        // Collect type parameter names
        self.type_params = func.type_params.iter().map(|p| p.name.clone()).collect();

        // Map function parameters to their type parameters
        self.var_to_type_param.clear();
        for param in &func.parameters {
            // Check for Type::Generic OR Type::Custom with a type parameter name
            let type_param_name = match &param.type_ {
                crate::parser::Type::Generic(name) => Some(name.clone()),
                crate::parser::Type::Custom(name) => {
                    // If the custom type name is one of our type parameters, treat it as generic
                    if self.type_params.contains(name) {
                        Some(name.clone())
                    } else {
                        None
                    }
                }
                _ => None,
            };
            if let Some(tp_name) = type_param_name {
                self.var_to_type_param.insert(param.name.clone(), tp_name);
            }
        }

        let mut bounds = InferredBounds::new();

        // Analyze function body
        self.collect_constraints_from_statements(&func.body, &mut bounds);

        bounds
    }

    /// Collect constraints from a list of statements
    fn collect_constraints_from_statements<'ast>(
        &self,
        statements: &[&'ast Statement<'ast>],
        bounds: &mut InferredBounds,
    ) {
        for stmt in statements {
            self.collect_constraints_from_statement(stmt, bounds);
        }
    }

    /// Collect constraints from a single statement
    fn collect_constraints_from_statement(&self, stmt: &Statement, bounds: &mut InferredBounds) {
        match stmt {
            Statement::Expression { expr, .. } => {
                self.collect_constraints_from_expression(expr, bounds);
            }
            Statement::Let { value, .. } => {
                self.collect_constraints_from_expression(value, bounds);
            }
            Statement::Return {
                value: Some(expr), ..
            } => {
                self.collect_constraints_from_expression(expr, bounds);
            }
            Statement::Return { value: None, .. } => {
                // No constraints from bare return
            }
            Statement::If {
                condition,
                then_block,
                else_block,
                ..
            } => {
                self.collect_constraints_from_expression(condition, bounds);
                self.collect_constraints_from_statements(then_block, bounds);
                if let Some(else_block) = else_block {
                    self.collect_constraints_from_statements(else_block, bounds);
                }
            }
            Statement::Match { value, arms, .. } => {
                self.collect_constraints_from_expression(value, bounds);
                for arm in arms {
                    self.collect_constraints_from_expression(arm.body, bounds);
                    if let Some(guard) = &arm.guard {
                        self.collect_constraints_from_expression(guard, bounds);
                    }
                }
            }
            Statement::For { iterable, body, .. } => {
                // for x in iterable requires IntoIterator
                self.infer_trait_for_expression(iterable, "IntoIterator", bounds);
                self.collect_constraints_from_statements(body, bounds);
            }
            Statement::While {
                condition, body, ..
            } => {
                self.collect_constraints_from_expression(condition, bounds);
                self.collect_constraints_from_statements(body, bounds);
            }
            Statement::Loop { body, .. } => {
                self.collect_constraints_from_statements(body, bounds);
            }
            Statement::Thread { body, .. } | Statement::Async { body, .. } => {
                self.collect_constraints_from_statements(body, bounds);
            }
            _ => {
                // Other statement types don't contribute constraints yet
            }
        }
    }

    /// Collect constraints from an expression
    fn collect_constraints_from_expression(&self, expr: &Expression, bounds: &mut InferredBounds) {
        match expr {
            // Binary operators
            Expression::Binary {
                op, left, right, ..
            } => {
                match op {
                    BinaryOp::Add => {
                        // For T + T operations, we need Add<Output = T>
                        self.infer_operator_trait(left, right, "Add", bounds);
                    }
                    BinaryOp::Sub => {
                        self.infer_operator_trait(left, right, "Sub", bounds);
                    }
                    BinaryOp::Mul => {
                        self.infer_operator_trait(left, right, "Mul", bounds);
                    }
                    BinaryOp::Div => {
                        self.infer_operator_trait(left, right, "Div", bounds);
                    }
                    BinaryOp::Eq | BinaryOp::Ne => {
                        self.infer_trait_for_expression(left, "PartialEq", bounds);
                        self.infer_trait_for_expression(right, "PartialEq", bounds);
                    }
                    BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge => {
                        self.infer_trait_for_expression(left, "PartialOrd", bounds);
                        self.infer_trait_for_expression(right, "PartialOrd", bounds);
                    }
                    _ => {
                        // Other binary ops don't require traits (logical ops, etc.)
                    }
                }

                // Recurse into operands
                self.collect_constraints_from_expression(left, bounds);
                self.collect_constraints_from_expression(right, bounds);
            }

            // Method calls — look up in the trait method registry
            Expression::MethodCall {
                object,
                method,
                arguments,
                ..
            } => {
                if let Some(entry) = TRAIT_METHOD_REGISTRY.iter().find(|e| e.method == method) {
                    self.infer_trait_for_expression(object, entry.trait_name, bounds);
                }

                // Recurse
                self.collect_constraints_from_expression(object, bounds);
                for (_, arg) in arguments {
                    self.collect_constraints_from_expression(arg, bounds);
                }
            }

            // Macro invocations (println!, format!, etc.)
            Expression::MacroInvocation { args, .. } => {
                // Structural format-string detection: if the first argument is a string
                // literal containing format placeholders, infer Display/Debug for the
                // subsequent arguments. Works for any macro, not just specific names.
                if args.len() >= 2 {
                    let labeled_args: Vec<(Option<String>, &Expression)> =
                        args.iter().map(|e| (None, *e)).collect();
                    self.detect_format_string_call(&labeled_args, bounds);
                }

                // Recurse into macro arguments
                for arg in args {
                    self.collect_constraints_from_expression(arg, bounds);
                }
            }

            // Function calls
            Expression::Call {
                arguments,
                function,
                ..
            } => {
                // Structural format-string detection: if the first argument is a string
                // literal containing format placeholders ({} or {:?}) and there are
                // subsequent arguments, infer Display/Debug for those arguments.
                // This works for ANY function that takes a format string, not just
                // specific hard-coded names.
                self.detect_format_string_call(arguments, bounds);

                // Recurse
                self.collect_constraints_from_expression(function, bounds);
                for (_, arg) in arguments {
                    self.collect_constraints_from_expression(arg, bounds);
                }
            }

            // Ternary operator

            // Block expression
            Expression::Block { statements, .. } => {
                self.collect_constraints_from_statements(statements, bounds);
            }

            // Other expressions: recurse as needed
            _ => {
                // TODO: Handle other expression types as needed
            }
        }
    }

    /// Analyze a format string to determine required traits
    fn analyze_format_string<'ast>(
        &self,
        format_str: &str,
        arguments: &[(Option<String>, &'ast Expression<'ast>)],
        bounds: &mut InferredBounds,
    ) {
        // Simple heuristic: check for {:?} (Debug) vs {} (Display)
        let has_debug = format_str.contains("{:?}") || format_str.contains("{:#?}");
        let has_display = format_str.contains("{}");

        if has_debug {
            for (_, arg) in arguments {
                self.infer_trait_for_expression(arg, "Debug", bounds);
            }
        } else if has_display {
            // Only infer Display if not Debug (Debug takes precedence)
            for (_, arg) in arguments {
                self.infer_trait_for_expression(arg, "Display", bounds);
            }
        }
    }

    /// Infer an operator trait (Add, Sub, Mul, Div) with proper Output type
    /// For T + T, we need T: Add<Output = T> + Copy not just T: Add
    fn infer_operator_trait(
        &self,
        left: &Expression,
        right: &Expression,
        trait_name: &str,
        bounds: &mut InferredBounds,
    ) {
        let left_type_param = self.extract_type_param(left);
        let right_type_param = self.extract_type_param(right);

        // If both operands are the same type parameter (e.g., T + T),
        // we need the trait with Output = T AND Copy (because x is used twice)
        if let (Some(left_tp), Some(right_tp)) = (&left_type_param, &right_type_param) {
            if left_tp == right_tp {
                // T + T requires T: Add<Output = T> + Copy
                let full_bound = format!("{}<Output = {}>", trait_name, left_tp);
                bounds.add_constraint(left_tp.clone(), full_bound);
                // Also need Copy because the same variable is used twice
                bounds.add_constraint(left_tp.clone(), "Copy".to_string());
                return;
            }
        }

        // If left is a type parameter, it needs the operator trait
        if let Some(tp) = left_type_param {
            bounds.add_constraint(tp, trait_name.to_string());
        }
        // If right is a type parameter, it needs the operator trait
        if let Some(tp) = right_type_param {
            bounds.add_constraint(tp, trait_name.to_string());
        }
    }

    /// Infer a trait requirement for an expression
    fn infer_trait_for_expression(
        &self,
        expr: &Expression,
        trait_name: &str,
        bounds: &mut InferredBounds,
    ) {
        // CONSERVATIVE APPROACH for v0.10.0:
        // If we see a trait usage and the function has type parameters,
        // assume ALL type parameters might need this trait.
        // This is conservative but simple and works for most cases.

        // Try to extract type parameter from expression
        if let Some(type_param) = self.extract_type_param(expr) {
            bounds.add_constraint(type_param, trait_name.to_string());
        } else {
            // Fallback: if we can't determine which variable, apply to ALL type parameters
            // This is conservative: better to over-constrain than under-constrain
            for type_param in &self.type_params {
                bounds.add_constraint(type_param.clone(), trait_name.to_string());
            }
        }
    }

    /// Extract type parameter name from an expression
    fn extract_type_param(&self, expr: &Expression) -> Option<String> {
        match expr {
            Expression::Identifier { name, .. } => {
                // Look up the type parameter for this variable
                self.var_to_type_param.get(name).cloned()
            }
            _ => None,
        }
    }

    /// Structural format-string detection for function calls.
    ///
    /// If the first argument is a string literal containing Rust-style format placeholders
    /// (`{}` for Display, `{:?}` / `{:#?}` for Debug) and there are subsequent arguments,
    /// infer the appropriate trait bounds on those arguments.
    ///
    /// This is structural, not name-based: it works for `println`, `format`, `log::info`,
    /// or any user-defined function that takes a format string.
    fn detect_format_string_call<'ast>(
        &self,
        arguments: &[(Option<String>, &'ast Expression<'ast>)],
        bounds: &mut InferredBounds,
    ) {
        if arguments.len() < 2 {
            return;
        }

        let fmt_str = match &arguments[0].1 {
            Expression::Literal {
                value: crate::parser::Literal::String(s),
                ..
            } => s.as_str(),
            _ => return,
        };

        if !Self::contains_format_placeholder(fmt_str) {
            return;
        }

        let rest: Vec<(Option<String>, &Expression)> = arguments[1..]
            .iter()
            .map(|(l, e)| (l.clone(), *e))
            .collect();
        self.analyze_format_string(fmt_str, &rest, bounds);
    }

    /// Check if a string contains Rust-style format placeholders.
    fn contains_format_placeholder(s: &str) -> bool {
        let mut chars = s.chars().peekable();
        while let Some(ch) = chars.next() {
            if ch == '{' {
                match chars.peek() {
                    Some('{') => {
                        // Escaped brace `{{` — skip
                        chars.next();
                    }
                    Some('}') | Some(':') => return true,
                    Some(c) if c.is_alphanumeric() => return true,
                    _ => {}
                }
            }
        }
        false
    }
}

impl Default for InferenceEngine {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::{Literal, OwnershipHint, Parameter, Type};
    use crate::test_utils::{test_alloc_expr, test_alloc_stmt};

    #[test]
    fn test_infer_display_from_println() {
        let mut engine = InferenceEngine::new();

        let func = FunctionDecl {
            name: "print".to_string(),
            is_pub: false,
            is_extern: false,
            decorators: vec![],
            type_params: vec![TypeParam {
                name: "T".to_string(),
                bounds: vec![],
            }],
            parameters: vec![Parameter {
                name: "x".to_string(),
                pattern: None,
                type_: Type::Generic("T".to_string()),
                ownership: OwnershipHint::Inferred,
                is_mutable: false,
                decorators: Vec::new(),
            }],
            return_type: None,
            return_decorators: Vec::new(),
            is_async: false,
            body: vec![test_alloc_stmt(Statement::Expression {
                expr: test_alloc_expr(Expression::MacroInvocation {
                    name: "println".to_string(),
                    args: vec![
                        test_alloc_expr(Expression::Literal {
                            value: Literal::String("{}".to_string()),
                            location: None,
                        }),
                        test_alloc_expr(Expression::Identifier {
                            name: "x".to_string(),
                            location: None,
                        }),
                    ],
                    delimiter: crate::parser::MacroDelimiter::Parens,
                    is_repeat: false,
                    location: None,
                }),
                location: None,
            })],
            where_clause: vec![],
            parent_type: None,
            impl_trait: None,
            doc_comment: None,
        };

        let bounds = engine.infer_function_bounds(&func);

        assert!(!bounds.is_empty());
        let t_bounds = bounds.get_bounds("T");
        assert!(t_bounds.contains(&"Display".to_string()));
    }

    #[test]
    fn test_infer_clone_from_method_call() {
        let mut engine = InferenceEngine::new();

        let func = FunctionDecl {
            name: "duplicate".to_string(),
            is_pub: false,
            is_extern: false,
            decorators: vec![],
            type_params: vec![TypeParam {
                name: "T".to_string(),
                bounds: vec![],
            }],
            parameters: vec![Parameter {
                name: "x".to_string(),
                pattern: None,
                type_: Type::Generic("T".to_string()),
                ownership: OwnershipHint::Inferred,
                is_mutable: false,
                decorators: Vec::new(),
            }],
            return_type: Some(Type::Generic("T".to_string())),
            return_decorators: Vec::new(),
            is_async: false,
            body: vec![test_alloc_stmt(Statement::Expression {
                expr: test_alloc_expr(Expression::MethodCall {
                    object: test_alloc_expr(Expression::Identifier {
                        name: "x".to_string(),
                        location: None,
                    }),
                    method: "clone".to_string(),
                    type_args: None,
                    arguments: vec![],
                    location: None,
                }),
                location: None,
            })],
            where_clause: vec![],
            parent_type: None,
            impl_trait: None,
            doc_comment: None,
        };

        let bounds = engine.infer_function_bounds(&func);

        assert!(!bounds.is_empty());
        let t_bounds = bounds.get_bounds("T");
        assert!(t_bounds.contains(&"Clone".to_string()));
    }

    #[test]
    fn test_infer_add_from_binary_op() {
        let mut engine = InferenceEngine::new();

        let func = FunctionDecl {
            is_pub: false,
            is_extern: false,
            name: "add".to_string(),
            decorators: vec![],
            type_params: vec![TypeParam {
                name: "T".to_string(),
                bounds: vec![],
            }],
            parameters: vec![
                Parameter {
                    name: "x".to_string(),
                    pattern: None,
                    type_: Type::Generic("T".to_string()),
                    ownership: OwnershipHint::Inferred,
                    is_mutable: false,
                    decorators: Vec::new(),
                },
                Parameter {
                    name: "y".to_string(),
                    pattern: None,
                    type_: Type::Generic("T".to_string()),
                    ownership: OwnershipHint::Inferred,
                    is_mutable: false,
                    decorators: Vec::new(),
                },
            ],
            return_type: Some(Type::Generic("T".to_string())),
            return_decorators: Vec::new(),
            is_async: false,
            body: vec![test_alloc_stmt(Statement::Expression {
                expr: test_alloc_expr(Expression::Binary {
                    op: BinaryOp::Add,
                    left: test_alloc_expr(Expression::Identifier {
                        name: "x".to_string(),
                        location: None,
                    }),
                    right: test_alloc_expr(Expression::Identifier {
                        name: "y".to_string(),
                        location: None,
                    }),
                    location: None,
                }),
                location: None,
            })],
            where_clause: vec![],
            parent_type: None,
            impl_trait: None,
            doc_comment: None,
        };

        let bounds = engine.infer_function_bounds(&func);

        assert!(!bounds.is_empty());
        let t_bounds = bounds.get_bounds("T");
        // Now infers Add<Output = T> instead of just Add for same-type operands
        assert!(
            t_bounds.iter().any(|b| b.starts_with("Add")),
            "Expected Add bound, got: {:?}",
            t_bounds
        );
    }

    /// Structural format-string detection: any call with a format string ("{}", x) should
    /// infer Display, regardless of the function name. This is NOT hard-coded to println.
    #[test]
    fn test_infer_display_from_call_with_format_string() {
        let mut engine = InferenceEngine::new();

        // fn log_value<T>(item: T) { custom_logger("{}", item) }
        let func = FunctionDecl {
            name: "log_value".to_string(),
            is_pub: false,
            is_extern: false,
            decorators: vec![],
            type_params: vec![TypeParam {
                name: "T".to_string(),
                bounds: vec![],
            }],
            parameters: vec![Parameter {
                name: "item".to_string(),
                pattern: None,
                type_: Type::Generic("T".to_string()),
                ownership: OwnershipHint::Inferred,
                is_mutable: false,
                decorators: Vec::new(),
            }],
            return_type: None,
            return_decorators: Vec::new(),
            is_async: false,
            body: vec![test_alloc_stmt(Statement::Expression {
                expr: test_alloc_expr(Expression::Call {
                    function: test_alloc_expr(Expression::Identifier {
                        name: "custom_logger".to_string(),
                        location: None,
                    }),
                    arguments: vec![
                        (
                            None,
                            test_alloc_expr(Expression::Literal {
                                value: Literal::String("{} logged".to_string()),
                                location: None,
                            }),
                        ),
                        (
                            None,
                            test_alloc_expr(Expression::Identifier {
                                name: "item".to_string(),
                                location: None,
                            }),
                        ),
                    ],
                    location: None,
                }),
                location: None,
            })],
            where_clause: vec![],
            parent_type: None,
            impl_trait: None,
            doc_comment: None,
        };

        let bounds = engine.infer_function_bounds(&func);
        let t_bounds = bounds.get_bounds("T");
        assert!(
            t_bounds.contains(&"Display".to_string()),
            "Format string '{{}} logged' + arg should infer Display via structure, got: {:?}",
            t_bounds
        );
    }

    /// {:?} in any call should infer Debug, not Display.
    #[test]
    fn test_infer_debug_from_call_with_debug_format_string() {
        let mut engine = InferenceEngine::new();

        let func = FunctionDecl {
            name: "debug_it".to_string(),
            is_pub: false,
            is_extern: false,
            decorators: vec![],
            type_params: vec![TypeParam {
                name: "T".to_string(),
                bounds: vec![],
            }],
            parameters: vec![Parameter {
                name: "val".to_string(),
                pattern: None,
                type_: Type::Generic("T".to_string()),
                ownership: OwnershipHint::Inferred,
                is_mutable: false,
                decorators: Vec::new(),
            }],
            return_type: None,
            return_decorators: Vec::new(),
            is_async: false,
            body: vec![test_alloc_stmt(Statement::Expression {
                expr: test_alloc_expr(Expression::Call {
                    function: test_alloc_expr(Expression::Identifier {
                        name: "write_log".to_string(),
                        location: None,
                    }),
                    arguments: vec![
                        (
                            None,
                            test_alloc_expr(Expression::Literal {
                                value: Literal::String("debug: {:?}".to_string()),
                                location: None,
                            }),
                        ),
                        (
                            None,
                            test_alloc_expr(Expression::Identifier {
                                name: "val".to_string(),
                                location: None,
                            }),
                        ),
                    ],
                    location: None,
                }),
                location: None,
            })],
            where_clause: vec![],
            parent_type: None,
            impl_trait: None,
            doc_comment: None,
        };

        let bounds = engine.infer_function_bounds(&func);
        let t_bounds = bounds.get_bounds("T");
        assert!(
            t_bounds.contains(&"Debug".to_string()),
            "Format string 'debug: {{:?}}' should infer Debug, got: {:?}",
            t_bounds
        );
    }

    /// A call with a plain string (no placeholders) should NOT infer Display.
    #[test]
    fn test_no_spurious_display_from_plain_string_arg() {
        let mut engine = InferenceEngine::new();

        // fn foo<T>(item: T) { some_fn("hello", item) }
        // "hello" has no {} — no Display inference
        let func = FunctionDecl {
            name: "foo".to_string(),
            is_pub: false,
            is_extern: false,
            decorators: vec![],
            type_params: vec![TypeParam {
                name: "T".to_string(),
                bounds: vec![],
            }],
            parameters: vec![Parameter {
                name: "item".to_string(),
                pattern: None,
                type_: Type::Generic("T".to_string()),
                ownership: OwnershipHint::Inferred,
                is_mutable: false,
                decorators: Vec::new(),
            }],
            return_type: None,
            return_decorators: Vec::new(),
            is_async: false,
            body: vec![test_alloc_stmt(Statement::Expression {
                expr: test_alloc_expr(Expression::Call {
                    function: test_alloc_expr(Expression::Identifier {
                        name: "some_fn".to_string(),
                        location: None,
                    }),
                    arguments: vec![
                        (
                            None,
                            test_alloc_expr(Expression::Literal {
                                value: Literal::String("hello world".to_string()),
                                location: None,
                            }),
                        ),
                        (
                            None,
                            test_alloc_expr(Expression::Identifier {
                                name: "item".to_string(),
                                location: None,
                            }),
                        ),
                    ],
                    location: None,
                }),
                location: None,
            })],
            where_clause: vec![],
            parent_type: None,
            impl_trait: None,
            doc_comment: None,
        };

        let bounds = engine.infer_function_bounds(&func);
        let t_bounds = bounds.get_bounds("T");
        assert!(
            !t_bounds.contains(&"Display".to_string()),
            "Plain string 'hello world' (no {{}}) should NOT infer Display, got: {:?}",
            t_bounds
        );
    }

    /// Registry-driven: .to_string() on a generic should infer ToString via the registry table.
    #[test]
    fn test_infer_tostring_from_method_call_via_registry() {
        let mut engine = InferenceEngine::new();

        let func = FunctionDecl {
            name: "stringify".to_string(),
            is_pub: false,
            is_extern: false,
            decorators: vec![],
            type_params: vec![TypeParam {
                name: "T".to_string(),
                bounds: vec![],
            }],
            parameters: vec![Parameter {
                name: "val".to_string(),
                pattern: None,
                type_: Type::Generic("T".to_string()),
                ownership: OwnershipHint::Inferred,
                is_mutable: false,
                decorators: Vec::new(),
            }],
            return_type: Some(Type::String),
            return_decorators: Vec::new(),
            is_async: false,
            body: vec![test_alloc_stmt(Statement::Return {
                value: Some(test_alloc_expr(Expression::MethodCall {
                    object: test_alloc_expr(Expression::Identifier {
                        name: "val".to_string(),
                        location: None,
                    }),
                    method: "to_string".to_string(),
                    arguments: vec![],
                    type_args: None,
                    location: None,
                })),
                location: None,
            })],
            where_clause: vec![],
            parent_type: None,
            impl_trait: None,
            doc_comment: None,
        };

        let bounds = engine.infer_function_bounds(&func);
        let t_bounds = bounds.get_bounds("T");
        assert!(
            t_bounds.contains(&"ToString".to_string()),
            "Expected ToString from .to_string() via registry, got: {:?}",
            t_bounds
        );
    }
}