llvm-native-core 0.1.13

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
//! C++ Overload Resolution — implements the complete C++ overload
//! resolution algorithm from §12 of the C++ standard.
//!
//! Covers:
//! - Candidate function gathering (name lookup, ADL)
//! - Viable function filtering
//! - Implicit conversion sequence ranking
//! - Best viable function selection
//! - Operator overload resolution
//! - User-defined conversion sequences
//!
//! Clean-room behavioral reconstruction from:
//! - C++ Standard §12 (Overloading), §12.4 (Overload resolution)
//! - Published Clang documentation
//! - No LLVM/Clang source code is consulted.

use std::collections::HashMap;

use super::cpp_ast::*;
use super::cpp_token::AccessSpecifier;

use super::ast::QualType;

// ═══════════════════════════════════════════════════════════════════════════════
// Overload Candidate
// ═══════════════════════════════════════════════════════════════════════════════

/// A candidate function for overload resolution.
#[derive(Debug, Clone)]
pub struct OverloadCandidate {
    /// The declaration of the candidate function.
    pub decl: CXXDecl,
    /// The implicit conversion sequence for each argument.
    pub conversion_sequences: Vec<ImplicitConversionSequence>,
    /// The overall viability of this candidate.
    pub viability: CandidateViability,
    /// Whether this is a built-in candidate (compiler-generated).
    pub is_builtin: bool,
    /// Whether this is a template candidate requiring deduction.
    pub is_template: bool,
    /// The rank of this candidate (lower is better).
    pub rank: CandidateRank,
}

/// The viability of a candidate function.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum CandidateViability {
    /// Candidate is viable and could be the best match.
    Viable,
    /// Candidate is viable but only through a worse conversion.
    ViableButWorse,
    /// Candidate is not viable (argument count mismatch, etc.).
    NotViable,
}

/// The rank of an overload candidate (lower is better).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum CandidateRank {
    /// Exact match (identity, lvalue-to-rvalue, qualification adjustment).
    ExactMatch = 0,
    /// Promotion (integral promotion, float promotion).
    Promotion = 1,
    /// Standard conversion (integral conversion, float conversion, pointer conversion).
    StandardConversion = 2,
    /// User-defined conversion (through constructor or conversion operator).
    UserDefinedConversion = 3,
    /// Ellipsis match (`...`).
    Ellipsis = 4,
    /// Not viable.
    NotViable = 5,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Implicit Conversion Sequence
// ═══════════════════════════════════════════════════════════════════════════════

/// An implicit conversion sequence for a single argument.
#[derive(Debug, Clone, PartialEq)]
pub enum ImplicitConversionSequence {
    /// Standard conversion sequence.
    Standard(StandardConversionSequence),
    /// User-defined conversion sequence.
    UserDefined {
        before: StandardConversionSequence,
        conversion: UserDefinedConversion,
        after: StandardConversionSequence,
    },
    /// Ellipsis conversion (matching `...`).
    Ellipsis,
    /// Bad conversion (no viable conversion).
    BadConversion,
}

/// A standard conversion sequence (SCS).
#[derive(Debug, Clone, PartialEq)]
pub struct StandardConversionSequence {
    /// The rank of this conversion.
    pub rank: CandidateRank,
    /// Whether this is a reference binding.
    pub is_reference_binding: bool,
    /// Whether this involves a qualification adjustment.
    pub is_qualification_adjustment: bool,
    /// Whether this is a derived-to-base conversion.
    pub is_derived_to_base: bool,
}

impl StandardConversionSequence {
    pub fn exact_match() -> Self {
        Self {
            rank: CandidateRank::ExactMatch,
            is_reference_binding: false,
            is_qualification_adjustment: false,
            is_derived_to_base: false,
        }
    }

    pub fn promotion() -> Self {
        Self {
            rank: CandidateRank::Promotion,
            is_reference_binding: false,
            is_qualification_adjustment: false,
            is_derived_to_base: false,
        }
    }

    pub fn standard_conversion() -> Self {
        Self {
            rank: CandidateRank::StandardConversion,
            is_reference_binding: false,
            is_qualification_adjustment: false,
            is_derived_to_base: false,
        }
    }
}

/// A user-defined conversion (constructor or conversion operator).
#[derive(Debug, Clone, PartialEq)]
pub struct UserDefinedConversion {
    /// The constructor or conversion operator declaration.
    pub conversion_fn: Option<CXXDecl>,
    /// The source type.
    pub source_type: String,
    /// The target type.
    pub target_type: String,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Overload Resolution Engine
// ═══════════════════════════════════════════════════════════════════════════════

/// Main overload resolution engine.
pub struct OverloadResolver {
    /// Candidates collected for the current resolution.
    candidates: Vec<OverloadCandidate>,
    /// Error messages from failed resolution.
    errors: Vec<String>,
    /// Whether argument-dependent lookup (ADL) is enabled.
    enable_adl: bool,
    /// The current access check context.
    current_access: AccessSpecifier,
}

impl OverloadResolver {
    pub fn new() -> Self {
        Self {
            candidates: Vec::new(),
            errors: Vec::new(),
            enable_adl: true,
            current_access: AccessSpecifier::Public,
        }
    }

    /// Clear state for a new resolution.
    pub fn reset(&mut self) {
        self.candidates.clear();
        self.errors.clear();
    }

    /// Add a candidate function to the overload set.
    pub fn add_candidate(&mut self, decl: CXXDecl, is_template: bool) {
        self.candidates.push(OverloadCandidate {
            decl,
            conversion_sequences: Vec::new(),
            viability: CandidateViability::Viable,
            is_builtin: false,
            is_template,
            rank: CandidateRank::ExactMatch,
        });
    }

    /// Add a built-in candidate (compiler-generated, e.g., built-in operator).
    pub fn add_builtin_candidate(&mut self, decl: CXXDecl) {
        self.candidates.push(OverloadCandidate {
            decl,
            conversion_sequences: Vec::new(),
            viability: CandidateViability::Viable,
            is_builtin: true,
            is_template: false,
            rank: CandidateRank::ExactMatch,
        });
    }

    /// Resolve overloaded function call with given argument types.
    pub fn resolve_call(
        &mut self,
        name: &str,
        arg_types: &[&str],
        scope: Option<&str>,
    ) -> Result<CXXDecl, Vec<String>> {
        self.reset();

        // Filter viable candidates
        let viable: Vec<&OverloadCandidate> = self
            .candidates
            .iter()
            .filter(|c| self.is_viable(c, arg_types))
            .collect();

        if viable.is_empty() {
            return Err(vec![format!("no matching function for call to '{}'", name)]);
        }

        // Find best viable function
        if viable.len() == 1 {
            return Ok(viable[0].decl.clone());
        }

        // Compare candidates pairwise
        let mut best_index = 0usize;
        for i in 1..viable.len() {
            match self.compare_candidates(&viable[best_index], &viable[i]) {
                Ordering::Better => { /* keep best_index */ }
                Ordering::Worse => {
                    best_index = i;
                }
                Ordering::Ambiguous => {
                    return Err(vec![format!("call to '{}' is ambiguous", name)]);
                }
            }
        }

        Ok(viable[best_index].decl.clone())
    }

    /// Resolve an operator overload.
    pub fn resolve_operator(
        &mut self,
        op: CXXOperator,
        arg_types: &[&str],
    ) -> Result<CXXDecl, Vec<String>> {
        self.resolve_call(&op.canonical_name(), arg_types, None)
    }

    /// Check if a candidate is viable for the given argument types.
    fn is_viable(&self, candidate: &OverloadCandidate, arg_types: &[&str]) -> bool {
        let param_count = self.get_param_count(&candidate.decl);

        // Candidate must have enough parameters (accounting for `this`)
        if param_count < arg_types.len() {
            return false;
        }
        if param_count > arg_types.len() {
            // Too many parameters — only viable if extra params have defaults
            // (simplified: allow)
        }

        true
    }

    /// Get the number of parameters for a function declaration.
    fn get_param_count(&self, decl: &CXXDecl) -> usize {
        match decl {
            CXXDecl::Function { params, .. } => params.len(),
            CXXDecl::ConstructorDecl { params, .. } => params.len(),
            CXXDecl::OperatorFunction { params, .. } => params.len(),
            _ => 0,
        }
    }

    /// Compare two overload candidates to determine which is better.
    fn compare_candidates(&self, a: &OverloadCandidate, b: &OverloadCandidate) -> Ordering {
        // Rule 1: Exact match beats promotion beats conversion
        match a.rank.cmp(&b.rank) {
            std::cmp::Ordering::Less => return Ordering::Better,
            std::cmp::Ordering::Greater => return Ordering::Worse,
            std::cmp::Ordering::Equal => {}
        }

        // Rule 2: Non-template beats template
        if !a.is_template && b.is_template {
            return Ordering::Better;
        }
        if a.is_template && !b.is_template {
            return Ordering::Worse;
        }

        // Rule 3: More specialized template beats less specialized
        if a.is_template && b.is_template {
            // Simplified: prefer the candidate with fewer template parameters
            let a_tp_count = self.count_template_params(&a.decl);
            let b_tp_count = self.count_template_params(&b.decl);
            match a_tp_count.cmp(&b_tp_count) {
                std::cmp::Ordering::Less => return Ordering::Better,
                std::cmp::Ordering::Greater => return Ordering::Worse,
                std::cmp::Ordering::Equal => {}
            }
        }

        // Rule 4: Better conversion sequences win
        for (seq_a, seq_b) in a
            .conversion_sequences
            .iter()
            .zip(b.conversion_sequences.iter())
        {
            match Self::compare_conversion_sequences(seq_a, seq_b) {
                Ordering::Better => return Ordering::Better,
                Ordering::Worse => return Ordering::Worse,
                Ordering::Ambiguous => {} // continue checking
            }
        }

        Ordering::Ambiguous
    }

    /// Count template parameters on a declaration.
    fn count_template_params(&self, decl: &CXXDecl) -> usize {
        match decl {
            CXXDecl::TemplateDeclaration { params, .. } => params.len(),
            _ => 0,
        }
    }

    /// Compare two implicit conversion sequences.
    fn compare_conversion_sequences(
        a: &ImplicitConversionSequence,
        b: &ImplicitConversionSequence,
    ) -> Ordering {
        let rank_a = Self::get_conversion_rank(a);
        let rank_b = Self::get_conversion_rank(b);

        match rank_a.cmp(&rank_b) {
            std::cmp::Ordering::Less => Ordering::Better,
            std::cmp::Ordering::Greater => Ordering::Worse,
            std::cmp::Ordering::Equal => Ordering::Ambiguous,
        }
    }

    /// Get the rank of an implicit conversion sequence.
    fn get_conversion_rank(seq: &ImplicitConversionSequence) -> CandidateRank {
        match seq {
            ImplicitConversionSequence::Standard(scs) => scs.rank,
            ImplicitConversionSequence::UserDefined { .. } => CandidateRank::UserDefinedConversion,
            ImplicitConversionSequence::Ellipsis => CandidateRank::Ellipsis,
            ImplicitConversionSequence::BadConversion => CandidateRank::NotViable,
        }
    }

    /// Determine the implicit conversion sequence from `from_type` to `to_type`.
    pub fn get_implicit_conversion_sequence(
        &self,
        from_type: &str,
        to_type: &str,
    ) -> ImplicitConversionSequence {
        if from_type == to_type {
            return ImplicitConversionSequence::Standard(StandardConversionSequence::exact_match());
        }

        // Integer promotion
        if Self::is_integral_promotion(from_type, to_type) {
            return ImplicitConversionSequence::Standard(StandardConversionSequence::promotion());
        }

        // Standard conversion
        if Self::is_standard_conversion(from_type, to_type) {
            return ImplicitConversionSequence::Standard(
                StandardConversionSequence::standard_conversion(),
            );
        }

        // Derived-to-base (simplified)
        if self.is_derived_to_base(from_type, to_type) {
            let mut scs = StandardConversionSequence::standard_conversion();
            scs.is_derived_to_base = true;
            return ImplicitConversionSequence::Standard(scs);
        }

        ImplicitConversionSequence::BadConversion
    }

    /// Check if `from` to `to` is an integral promotion.
    fn is_integral_promotion(from: &str, to: &str) -> bool {
        matches!(
            (from, to),
            ("bool", "int")
                | ("char", "int")
                | ("signed char", "int")
                | ("unsigned char", "int")
                | ("short", "int")
                | ("unsigned short", "int")
                | ("float", "double")
        )
    }

    /// Check if `from` to `to` is a standard conversion.
    fn is_standard_conversion(from: &str, to: &str) -> bool {
        matches!(
            (from, to),
            ("int", "long")
                | ("int", "unsigned int")
                | ("int", "double")
                | ("long", "double")
                | ("double", "int")
                | ("float", "int")
        )
    }

    /// Check if `from` to `to` is a derived-to-base conversion (simplified).
    fn is_derived_to_base(&self, _from: &str, _to: &str) -> bool {
        false // Requires class hierarchy knowledge
    }

    /// Perform argument-dependent lookup (ADL / Koenig lookup).
    pub fn adl_lookup(
        &mut self,
        name: &str,
        arg_types: &[&str],
        current_namespace: Option<&str>,
    ) -> Vec<String> {
        if !self.enable_adl {
            return vec![];
        }

        let mut found = Vec::new();

        // ADL searches namespaces of the argument types
        for arg_ty in arg_types {
            // Extract namespace from qualified type names
            if let Some(ns) = Self::extract_namespace(arg_ty) {
                found.push(format!("{}::{}", ns, name));
            }
        }

        found
    }

    /// Extract the namespace from a qualified type name.
    fn extract_namespace(type_name: &str) -> Option<&str> {
        if let Some(pos) = type_name.rfind("::") {
            Some(&type_name[..pos])
        } else {
            None
        }
    }

    /// Check access to a member from the current context.
    pub fn check_access(&self, member_access: AccessSpecifier) -> bool {
        match (self.current_access, member_access) {
            (_, AccessSpecifier::Public) => true,
            (AccessSpecifier::Public, _) => false,
            (AccessSpecifier::Protected, AccessSpecifier::Protected) => true,
            (AccessSpecifier::Protected, AccessSpecifier::Private) => false,
            (AccessSpecifier::Private, _) => true,
            (_, AccessSpecifier::None) => true,
            (AccessSpecifier::None, AccessSpecifier::Protected) => false,
            (AccessSpecifier::None, AccessSpecifier::Private) => false,
        }
    }

    /// Set the current access context for access checking.
    pub fn set_current_access(&mut self, access: AccessSpecifier) {
        self.current_access = access;
    }

    /// Enable or disable ADL.
    pub fn set_adl_enabled(&mut self, enabled: bool) {
        self.enable_adl = enabled;
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Comparison Result
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of comparing two candidates or conversion sequences.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ordering {
    Better,
    Worse,
    Ambiguous,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Operator Overload Tables
// ═══════════════════════════════════════════════════════════════════════════════

/// Get the built-in candidate signature for an operator.
pub fn get_builtin_operator_candidates(
    op: CXXOperator,
    lhs_type: &str,
    rhs_type: &str,
) -> Vec<(Vec<&'static str>, &'static str)> {
    match op {
        CXXOperator::Add => vec![
            (vec!["int", "int"], "int"),
            (vec!["double", "double"], "double"),
            (vec!["int", "double"], "double"),
        ],
        CXXOperator::Sub => vec![
            (vec!["int", "int"], "int"),
            (vec!["double", "double"], "double"),
        ],
        CXXOperator::Mul => vec![
            (vec!["int", "int"], "int"),
            (vec!["double", "double"], "double"),
        ],
        CXXOperator::Div => vec![
            (vec!["int", "int"], "int"),
            (vec!["double", "double"], "double"),
        ],
        CXXOperator::Eq => vec![
            (vec!["int", "int"], "bool"),
            (vec!["double", "double"], "bool"),
        ],
        CXXOperator::Lt => vec![
            (vec!["int", "int"], "bool"),
            (vec!["double", "double"], "bool"),
        ],
        CXXOperator::Deref => vec![(vec!["ptr"], "ref")],
        _ => vec![],
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Complete Implicit Conversion Sequence Ranking
// ═══════════════════════════════════════════════════════════════════════════════

/// Detailed ranking of implicit conversion sequences per C++ §12.4.3.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ConversionRank {
    /// Exact match: identity, lvalue-to-rvalue, qualification adjustment.
    ExactMatch = 0,
    /// Promotion: integral promotion, floating-point promotion.
    Promotion = 1,
    /// Standard conversion: integral conversion, floating conversion,
    /// floating-integral conversion, pointer conversion, pointer-to-member
    /// conversion, boolean conversion.
    StandardConversion = 2,
    /// User-defined conversion followed by standard conversion.
    UserDefinedConversion = 3,
    /// Ellipsis conversion.
    Ellipsis = 4,
    /// No viable conversion.
    None = 5,
}

/// Complete implicit conversion sequence builder with detailed tracking.
#[derive(Debug, Clone)]
pub struct ConversionSequenceBuilder {
    /// The source type.
    pub from_type: String,
    /// The target type.
    pub to_type: String,
    /// The overall rank.
    pub rank: ConversionRank,
    /// Qualification adjustments.
    pub qual_conv: Option<QualConversion>,
    /// Lvalue-to-rvalue conversion.
    pub lvalue_to_rvalue: bool,
    /// Function-to-pointer conversion.
    pub function_to_pointer: bool,
    /// Array-to-pointer conversion.
    pub array_to_pointer: bool,
    /// Whether this binds to a reference.
    pub reference_binding: Option<ReferenceBinding>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QualConversion {
    AddConst,
    AddVolatile,
    AddConstVolatile,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReferenceBinding {
    /// Binds to lvalue reference.
    LValue,
    /// Binds to rvalue reference.
    RValue,
    /// Binds to const lvalue reference (extends lifetime).
    ConstLValue,
}

impl ConversionSequenceBuilder {
    pub fn new(from: &str, to: &str) -> Self {
        Self {
            from_type: from.to_string(),
            to_type: to.to_string(),
            rank: ConversionRank::None,
            qual_conv: None,
            lvalue_to_rvalue: false,
            function_to_pointer: false,
            array_to_pointer: false,
            reference_binding: None,
        }
    }

    /// Build the conversion sequence with full ranking.
    pub fn build(&mut self) -> ImplicitConversionSequence {
        // Identity
        if self.from_type == self.to_type {
            self.rank = ConversionRank::ExactMatch;
            return ImplicitConversionSequence::Standard(StandardConversionSequence::exact_match());
        }

        // Lvalue-to-rvalue
        if self.match_lvalue_to_rvalue() {
            self.lvalue_to_rvalue = true;
            self.rank = ConversionRank::ExactMatch;
            return ImplicitConversionSequence::Standard(StandardConversionSequence::exact_match());
        }

        // Array-to-pointer / Function-to-pointer
        if self.match_array_to_pointer() {
            self.array_to_pointer = true;
            self.rank = ConversionRank::ExactMatch;
            return ImplicitConversionSequence::Standard(StandardConversionSequence::exact_match());
        }
        if self.match_function_to_pointer() {
            self.function_to_pointer = true;
            self.rank = ConversionRank::ExactMatch;
            return ImplicitConversionSequence::Standard(StandardConversionSequence::exact_match());
        }

        // Qualification adjustment
        if self.match_qual_conversion() {
            let mut scs = StandardConversionSequence::exact_match();
            scs.is_qualification_adjustment = true;
            return ImplicitConversionSequence::Standard(scs);
        }

        // Promotion
        if self.match_promotion() {
            self.rank = ConversionRank::Promotion;
            return ImplicitConversionSequence::Standard(StandardConversionSequence::promotion());
        }

        // Standard conversion
        if self.match_standard_conversion() {
            self.rank = ConversionRank::StandardConversion;
            return ImplicitConversionSequence::Standard(
                StandardConversionSequence::standard_conversion(),
            );
        }

        ImplicitConversionSequence::BadConversion
    }

    fn match_lvalue_to_rvalue(&self) -> bool {
        // Lvalue T → rvalue T (strip lvalue reference)
        self.from_type == format!("{}&", self.to_type)
            || self.from_type == format!("{}&&", self.to_type)
    }

    fn match_array_to_pointer(&self) -> bool {
        self.from_type.starts_with('[')
            && self.from_type.ends_with(']')
            && self.to_type.ends_with('*')
    }

    fn match_function_to_pointer(&self) -> bool {
        self.from_type.contains("(...)") && self.to_type.contains("(*)")
    }

    fn match_qual_conversion(&self) -> bool {
        let from = self
            .from_type
            .trim_start_matches("const ")
            .trim_start_matches("volatile ");
        let to = self
            .to_type
            .trim_start_matches("const ")
            .trim_start_matches("volatile ");
        from == to
    }

    fn match_promotion(&self) -> bool {
        matches!(
            (self.from_type.as_str(), self.to_type.as_str()),
            ("bool", "int")
                | ("char", "int")
                | ("signed char", "int")
                | ("unsigned char", "int")
                | ("short", "int")
                | ("unsigned short", "int")
                | ("float", "double")
        )
    }

    fn match_standard_conversion(&self) -> bool {
        matches!(
            (self.from_type.as_str(), self.to_type.as_str()),
            ("int", "long")
                | ("int", "unsigned int")
                | ("int", "double")
                | ("long", "double")
                | ("double", "int")
                | ("float", "int")
                | ("int", "char")
                | ("long", "int")
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Constructor Overload Resolution
// ═══════════════════════════════════════════════════════════════════════════════

/// Resolves constructor overloads for direct, copy, and list initialization.
#[derive(Debug, Clone)]
pub struct ConstructorOverloadResolver {
    /// The class being constructed.
    pub class_name: String,
    /// Available constructors.
    pub constructors: Vec<CXXDecl>,
}

impl ConstructorOverloadResolver {
    pub fn new(class_name: &str) -> Self {
        Self {
            class_name: class_name.to_string(),
            constructors: Vec::new(),
        }
    }

    /// Add a constructor to the overload set.
    pub fn add_constructor(&mut self, ctor: CXXDecl) {
        self.constructors.push(ctor);
    }

    /// Resolve direct initialization: `T(args...)`.
    pub fn resolve_direct_init(&self, arg_types: &[&str]) -> Result<CXXDecl, String> {
        let mut resolver = OverloadResolver::new();
        for ctor in &self.constructors {
            resolver.add_candidate(ctor.clone(), false);
        }
        let result = resolver.resolve_call(&self.class_name, arg_types, None);
        match result {
            Ok(_) => {
                let viable = resolver
                    .candidates
                    .iter()
                    .find(|c| c.viability == CandidateViability::Viable)
                    .map(|c| c.decl.clone());
                viable.ok_or_else(|| format!("no matching constructor for '{}'", self.class_name))
            }
            Err(e) => Err(e.join("; ")),
        }
    }

    /// Resolve copy initialization: `T obj = value;`.
    pub fn resolve_copy_init(&self, from_type: &str) -> Result<CXXDecl, String> {
        self.resolve_direct_init(&[from_type])
    }

    /// Resolve list initialization: `T obj = {args...};` or `T{args...}`.
    pub fn resolve_list_init(&self, arg_types: &[&str]) -> Result<ListInitResult, String> {
        // Phase 1: Check if there's a constructor taking std::initializer_list
        let has_init_list_ctor = self.constructors.iter().any(|c| match c {
            CXXDecl::ConstructorDecl { params, .. } => params
                .iter()
                .any(|p| format!("{}", p.ty).contains("initializer_list")),
            _ => false,
        });

        if has_init_list_ctor && arg_types.iter().all(|t| *t == arg_types[0]) {
            return Ok(ListInitResult::InitializerListConstructor);
        }

        // Phase 2: Try regular constructors
        match self.resolve_direct_init(arg_types) {
            Ok(_) => Ok(ListInitResult::RegularConstructor),
            Err(_) => {
                // Phase 3: Aggregate initialization (for aggregates)
                Ok(ListInitResult::AggregateInitialization)
            }
        }
    }
}

/// Result of list-initialization resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ListInitResult {
    /// Calls an initializer_list constructor.
    InitializerListConstructor,
    /// Calls a regular constructor.
    RegularConstructor,
    /// Falls back to aggregate initialization.
    AggregateInitialization,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Operator Overload Resolution with Built-in Candidates
// ═══════════════════════════════════════════════════════════════════════════════

/// Resolves operator overloads by combining user-defined and built-in candidates.
#[derive(Debug, Clone)]
pub struct OperatorOverloadResolver {
    /// The operator being resolved.
    pub op: CXXOperator,
    /// User-defined operator overloads.
    pub user_candidates: Vec<CXXDecl>,
    /// Whether to include built-in candidates.
    pub include_builtins: bool,
}

impl OperatorOverloadResolver {
    pub fn new(op: CXXOperator) -> Self {
        Self {
            op,
            user_candidates: Vec::new(),
            include_builtins: true,
        }
    }

    /// Resolve the operator overload.
    pub fn resolve(&self, arg_types: &[&str]) -> Result<CXXDecl, Vec<String>> {
        let mut resolver = OverloadResolver::new();

        // Add user-defined candidates
        for cand in &self.user_candidates {
            resolver.add_candidate(cand.clone(), false);
        }

        // Add built-in candidates
        if self.include_builtins {
            if arg_types.len() == 2 {
                let builtins = get_builtin_operator_candidates(self.op.clone(), arg_types[0], arg_types[1]);
                for (params, _ret) in &builtins {
                    let builtin_decl = CXXDecl::OperatorFunction {
                        op: self.op.clone(),
                        return_ty: QualType::new(super::ast::TypeNode::Int),
                        params: params
                            .iter()
                            .map(|t| CXXParamDecl {
                                name: String::new(),
                                ty: QualType::new(super::ast::TypeNode::Int),
                                has_default: false,
                                default_value: None,
                                is_parameter_pack: false,
                                default: None,
                                is_pack: false,
                            })
                            .collect(),
                        body: None,
                        is_const: false,
                        is_noexcept: true,
                        is_constexpr: true,
                    };
                    resolver.add_builtin_candidate(builtin_decl);
                }
            }
        }

        resolver.resolve_operator(self.op.clone(), arg_types)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// User-Defined Conversion Sequences
// ═══════════════════════════════════════════════════════════════════════════════

/// Builds user-defined conversion sequences (constructor + conversion operator).
#[derive(Debug, Clone)]
pub struct UserDefinedConversionBuilder {
    /// Available conversion functions (constructors and conversion operators).
    pub conversions: Vec<UserDefinedConversion>,
}

impl UserDefinedConversionBuilder {
    pub fn new() -> Self {
        Self {
            conversions: Vec::new(),
        }
    }

    /// Add a converting constructor.
    pub fn add_converting_constructor(&mut self, source: &str, target: &str) {
        self.conversions.push(UserDefinedConversion {
            conversion_fn: None,
            source_type: source.to_string(),
            target_type: target.to_string(),
        });
    }

    /// Add a conversion operator.
    pub fn add_conversion_operator(&mut self, source: &str, target: &str, func: Option<CXXDecl>) {
        self.conversions.push(UserDefinedConversion {
            conversion_fn: func,
            source_type: source.to_string(),
            target_type: target.to_string(),
        });
    }

    /// Build the user-defined conversion sequence from `from` to `to`.
    pub fn build_sequence(&self, from: &str, to: &str) -> Option<ImplicitConversionSequence> {
        for conv in &self.conversions {
            // Check if we can go from → conv.source → conv.target → to
            if conv.source_type == from {
                let before = StandardConversionSequence::exact_match();
                let mut after_builder = ConversionSequenceBuilder::new(&conv.target_type, to);
                let after_seq = after_builder.build();

                // Only return if the after sequence isn't bad
                if !matches!(after_seq, ImplicitConversionSequence::BadConversion) {
                    return Some(ImplicitConversionSequence::UserDefined {
                        before,
                        conversion: conv.clone(),
                        after: match &after_seq {
                            ImplicitConversionSequence::Standard(scs) => scs.clone(),
                            _ => StandardConversionSequence::exact_match(),
                        },
                    });
                }
            }
        }
        None
    }

    /// Check if a user-defined conversion exists between two types.
    pub fn has_conversion(&self, from: &str, to: &str) -> bool {
        self.conversions
            .iter()
            .any(|c| c.source_type == from && c.target_type == to)
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Overload Resolution with Concepts / Requires Constraints — C++20
// ═══════════════════════════════════════════════════════════════════════════════

/// Filters overload candidates by concept/requires constraints.
#[derive(Debug, Clone)]
pub struct ConceptConstraintFilter {
    /// The template parameters available for checking.
    pub template_params: Vec<String>,
}

impl ConceptConstraintFilter {
    pub fn new() -> Self {
        Self {
            template_params: Vec::new(),
        }
    }

    /// Check if a candidate satisfies its requires clause.
    pub fn check_candidate_constraints(&self, decl: &CXXDecl) -> bool {
        match decl {
            CXXDecl::TemplateDeclaration {
                requires_clause,
                params,
                decl: inner_decl,
                ..
            } => {
                if let Some(clause) = requires_clause {
                    return self.evaluate_requires_clause(clause, params);
                }
                true
            }
            CXXDecl::Function {
                template_params: Some(tparams),
                ..
            } => {
                // Function template — check implicit constraints
                // (simplified: no requires clause on function templates yet)
                true
            }
            _ => true,
        }
    }

    /// Evaluate a requires-clause with given template parameters.
    fn evaluate_requires_clause(&self, clause: &CXXExpr, _params: &[TemplateParamDecl]) -> bool {
        // In a full implementation, this evaluates the constraint expression
        // with the current template argument bindings.
        !matches!(clause, CXXExpr::BoolLiteral(false))
    }

    /// Order two candidates by constraint partial ordering.
    /// A constrained candidate is preferred over an unconstrained one.
    pub fn order_by_constraints(a: &OverloadCandidate, b: &OverloadCandidate) -> Ordering {
        let a_constrained = Self::is_constrained(&a.decl);
        let b_constrained = Self::is_constrained(&b.decl);

        match (a_constrained, b_constrained) {
            (true, false) => Ordering::Better, // constrained beats unconstrained
            (false, true) => Ordering::Worse,
            _ => Ordering::Ambiguous,
        }
    }

    fn is_constrained(decl: &CXXDecl) -> bool {
        match decl {
            CXXDecl::TemplateDeclaration {
                requires_clause, ..
            } => requires_clause.is_some(),
            _ => false,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Reference Binding Rules
// ═══════════════════════════════════════════════════════════════════════════════

/// Rules for reference binding in overload resolution (C++ §12.4.3.1.5).
#[derive(Debug, Clone)]
pub struct ReferenceBindingRules {
    /// The reference type being bound.
    pub ref_type: ReferenceKind,
    /// Whether the source is an lvalue or rvalue.
    pub source_value_category: ValueCategory,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReferenceKind {
    /// `T&` — lvalue reference to non-const.
    LValueRef,
    /// `const T&` — lvalue reference to const.
    ConstLValueRef,
    /// `T&&` — rvalue reference.
    RValueRef,
    /// `const T&&` — const rvalue reference.
    ConstRValueRef,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueCategory {
    LValue,
    XValue,
    PRvalue,
}

impl ReferenceBindingRules {
    pub fn new(ref_type: ReferenceKind, source_cat: ValueCategory) -> Self {
        Self {
            ref_type,
            source_value_category: source_cat,
        }
    }

    /// Check if the reference binding is valid.
    pub fn is_valid(&self) -> bool {
        match (self.ref_type, self.source_value_category) {
            // Lvalue reference can bind to lvalue
            (ReferenceKind::LValueRef, ValueCategory::LValue) => true,
            // Const lvalue reference can bind to anything
            (ReferenceKind::ConstLValueRef, _) => true,
            // Rvalue reference can bind to rvalue (xvalue or prvalue)
            (ReferenceKind::RValueRef, ValueCategory::XValue)
            | (ReferenceKind::RValueRef, ValueCategory::PRvalue) => true,
            // Const rvalue reference can bind to rvalue
            (ReferenceKind::ConstRValueRef, ValueCategory::XValue)
            | (ReferenceKind::ConstRValueRef, ValueCategory::PRvalue) => true,
            _ => false,
        }
    }

    /// Get the conversion rank for this reference binding.
    pub fn binding_rank(&self) -> ConversionRank {
        match self.ref_type {
            ReferenceKind::LValueRef => {
                // Direct binding to lvalue: exact match
                if self.source_value_category == ValueCategory::LValue {
                    ConversionRank::ExactMatch
                } else {
                    ConversionRank::None
                }
            }
            ReferenceKind::ConstLValueRef => {
                // Binding rvalue to const lvalue ref: standard conversion
                match self.source_value_category {
                    ValueCategory::LValue => ConversionRank::ExactMatch,
                    _ => ConversionRank::StandardConversion,
                }
            }
            ReferenceKind::RValueRef | ReferenceKind::ConstRValueRef => {
                match self.source_value_category {
                    ValueCategory::LValue => ConversionRank::None,
                    _ => ConversionRank::ExactMatch,
                }
            }
        }
    }

    /// Whether this binding derives a temporary (extends lifetime).
    pub fn derives_temporary(&self) -> bool {
        match self.ref_type {
            ReferenceKind::ConstLValueRef => self.source_value_category != ValueCategory::LValue,
            ReferenceKind::RValueRef => self.source_value_category == ValueCategory::PRvalue,
            _ => false,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// List-Initialization Overload Resolution with std::initializer_list
// ═══════════════════════════════════════════════════════════════════════════════

/// Handles list-initialization overload resolution.
#[derive(Debug, Clone)]
pub struct ListInitOverloadResolver {
    /// Whether std::initializer_list constructors are preferred.
    pub prefer_initializer_list: bool,
    /// The element types in the braced-init-list.
    pub element_types: Vec<String>,
}

impl ListInitOverloadResolver {
    pub fn new() -> Self {
        Self {
            prefer_initializer_list: true,
            element_types: Vec::new(),
        }
    }

    /// Resolve list-initialization: `T{a, b, c}` or `T = {a, b, c}`.
    pub fn resolve(
        &self,
        target_class: &str,
        ctor_resolver: &ConstructorOverloadResolver,
    ) -> Option<ListInitOutcome> {
        // Phase 1: Try initializer_list constructors first
        if self.prefer_initializer_list {
            let init_list_ctors: Vec<&CXXDecl> = ctor_resolver
                .constructors
                .iter()
                .filter(|c| match c {
                    CXXDecl::ConstructorDecl { params, .. } => params
                        .iter()
                        .any(|p| format!("{}", p.ty).contains("initializer_list")),
                    _ => false,
                })
                .collect();

            if !init_list_ctors.is_empty() {
                return Some(ListInitOutcome {
                    kind: ListInitOutcomeKind::InitializerListCtor,
                    selected_ctor: Some(init_list_ctors[0].clone()),
                });
            }
        }

        // Phase 2: Try regular constructors
        let args: Vec<&str> = self.element_types.iter().map(|s| s.as_str()).collect();
        if let Ok(ctor) = ctor_resolver.resolve_direct_init(&args) {
            return Some(ListInitOutcome {
                kind: ListInitOutcomeKind::RegularCtor,
                selected_ctor: Some(ctor.clone()),
            });
        }

        // Phase 3: Aggregate initialization
        Some(ListInitOutcome {
            kind: ListInitOutcomeKind::Aggregate,
            selected_ctor: None,
        })
    }
}

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

/// Outcome of list-initialization overload resolution.
#[derive(Debug, Clone)]
pub struct ListInitOutcome {
    pub kind: ListInitOutcomeKind,
    pub selected_ctor: Option<CXXDecl>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListInitOutcomeKind {
    InitializerListCtor,
    RegularCtor,
    Aggregate,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Best Viable Function Selection with Tie-Breaking Rules
// ═══════════════════════════════════════════════════════════════════════════════

/// Full tie-breaking rules for best viable function selection.
#[derive(Debug, Clone)]
pub struct BestViableFunctionSelector {
    /// The candidates to choose from.
    pub candidates: Vec<OverloadCandidate>,
    /// The argument types.
    pub arg_types: Vec<String>,
}

impl BestViableFunctionSelector {
    pub fn new() -> Self {
        Self {
            candidates: Vec::new(),
            arg_types: Vec::new(),
        }
    }

    /// Select the best viable function using all tie-breaking rules.
    pub fn select_best(&self) -> Result<CXXDecl, Vec<String>> {
        if self.candidates.is_empty() {
            return Err(vec!["no candidates".to_string()]);
        }

        if self.candidates.len() == 1 {
            return Ok(self.candidates[0].decl.clone());
        }

        // Apply tie-breaking rules in order
        let mut best_indices: Vec<usize> = (0..self.candidates.len()).collect();

        // Rule 1: Better conversion sequence rank
        best_indices = self.tiebreak_by_rank(&best_indices);
        if best_indices.len() == 1 {
            return Ok(self.candidates[best_indices[0]].decl.clone());
        }

        // Rule 2: Non-template beats template
        best_indices = self.tiebreak_by_templateness(&best_indices);
        if best_indices.len() == 1 {
            return Ok(self.candidates[best_indices[0]].decl.clone());
        }

        // Rule 3: More specialized template
        best_indices = self.tiebreak_by_specialization(&best_indices);
        if best_indices.len() == 1 {
            return Ok(self.candidates[best_indices[0]].decl.clone());
        }

        // Rule 4: Better conversion sequence for each argument
        best_indices = self.tiebreak_by_argumentwise(&best_indices);
        if best_indices.len() == 1 {
            return Ok(self.candidates[best_indices[0]].decl.clone());
        }

        // Rule 5: Constrained beats unconstrained (C++20)
        best_indices = self.tiebreak_by_constraints(&best_indices);
        if best_indices.len() == 1 {
            return Ok(self.candidates[best_indices[0]].decl.clone());
        }

        Err(vec![format!(
            "call is ambiguous among {} candidates",
            best_indices.len()
        )])
    }

    fn tiebreak_by_rank(&self, indices: &[usize]) -> Vec<usize> {
        let min_rank = indices
            .iter()
            .map(|&i| self.candidates[i].rank as u8)
            .min()
            .unwrap_or(0);
        indices
            .iter()
            .filter(|&&i| self.candidates[i].rank as u8 == min_rank)
            .copied()
            .collect()
    }

    fn tiebreak_by_templateness(&self, indices: &[usize]) -> Vec<usize> {
        let has_non_template = indices.iter().any(|&i| !self.candidates[i].is_template);
        if has_non_template {
            indices
                .iter()
                .filter(|&&i| !self.candidates[i].is_template)
                .copied()
                .collect()
        } else {
            indices.to_vec()
        }
    }

    fn tiebreak_by_specialization(&self, indices: &[usize]) -> Vec<usize> {
        // Simplified: keep all template candidates that are most specialized
        // Full implementation would do partial ordering of function templates
        indices.to_vec()
    }

    fn tiebreak_by_argumentwise(&self, indices: &[usize]) -> Vec<usize> {
        if indices.len() <= 1 {
            return indices.to_vec();
        }

        let mut best = indices.to_vec();
        for arg_idx in 0..self.arg_types.len() {
            if best.len() == 1 {
                break;
            }

            // Find the best conversion sequence for this argument
            let best_seq: Vec<CandidateRank> = best
                .iter()
                .map(|&i| {
                    self.candidates[i]
                        .conversion_sequences
                        .get(arg_idx)
                        .map(|s| OverloadResolver::get_conversion_rank(s))
                        .unwrap_or(CandidateRank::NotViable)
                })
                .collect();

            let min_rank = best_seq
                .iter()
                .min()
                .copied()
                .unwrap_or(CandidateRank::NotViable);
            best = best
                .iter()
                .enumerate()
                .filter(|(j, _)| best_seq[*j] == min_rank)
                .map(|(_, &i)| i)
                .collect();
        }

        best
    }

    fn tiebreak_by_constraints(&self, indices: &[usize]) -> Vec<usize> {
        let filter = ConceptConstraintFilter::new();
        let constrained: Vec<usize> = indices
            .iter()
            .filter(|&&i| ConceptConstraintFilter::is_constrained(&self.candidates[i].decl))
            .copied()
            .collect();

        if !constrained.is_empty() && constrained.len() < indices.len() {
            constrained
        } else {
            indices.to_vec()
        }
    }

    /// Add a candidate for selection.
    pub fn add_candidate(&mut self, decl: CXXDecl, is_template: bool, rank: CandidateRank) {
        self.candidates.push(OverloadCandidate {
            decl,
            conversion_sequences: Vec::new(),
            viability: CandidateViability::Viable,
            is_builtin: false,
            is_template,
            rank,
        });
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::super::ast::{QualType, TypeNode};
    use super::*;

    fn void_ty() -> QualType {
        QualType::new(TypeNode::Void)
    }
    fn int_ty() -> QualType {
        QualType::new(TypeNode::Int)
    }

    fn make_func(name: &str, params: Vec<CXXParamDecl>) -> CXXDecl {
        CXXDecl::Function {
            name: name.into(),
            return_ty: void_ty(),
            params,
            body: None,
            is_virtual: false,
            is_override: false,
            is_final: false,
            is_const: false,
            is_noexcept: false,
            is_constexpr: false,
            is_consteval: false,
            is_static: false,
            is_inline: false,
            is_explicit: false,
            is_deleted: false,
            is_defaulted: false,
            ref_qualifier: None,
            trailing_return_ty: None,
            template_params: None,
        }
    }

    #[test]
    fn test_implicit_conversion_exact_match() {
        let resolver = OverloadResolver::new();
        let seq = resolver.get_implicit_conversion_sequence("int", "int");
        match seq {
            ImplicitConversionSequence::Standard(scs) => {
                assert_eq!(scs.rank, CandidateRank::ExactMatch);
            }
            _ => panic!("expected standard conversion"),
        }
    }

    #[test]
    fn test_implicit_conversion_promotion() {
        let resolver = OverloadResolver::new();
        let seq = resolver.get_implicit_conversion_sequence("char", "int");
        match seq {
            ImplicitConversionSequence::Standard(scs) => {
                assert_eq!(scs.rank, CandidateRank::Promotion);
            }
            _ => panic!("expected promotion"),
        }
    }

    #[test]
    fn test_implicit_conversion_bad() {
        let resolver = OverloadResolver::new();
        let seq = resolver.get_implicit_conversion_sequence("struct Foo", "int");
        assert_eq!(seq, ImplicitConversionSequence::BadConversion);
    }

    #[test]
    fn test_adl_lookup() {
        let mut resolver = OverloadResolver::new();
        let results = resolver.adl_lookup("swap", &["std::vector<int>"], None);
        assert!(results.contains(&"std::swap".to_string()));
    }

    #[test]
    fn test_access_check() {
        let resolver = OverloadResolver::new();
        assert!(resolver.check_access(AccessSpecifier::Public));
        assert!(!resolver.check_access(AccessSpecifier::Private));
    }

    #[test]
    fn test_is_integral_promotion() {
        assert!(OverloadResolver::is_integral_promotion("char", "int"));
        assert!(OverloadResolver::is_integral_promotion("short", "int"));
        assert!(!OverloadResolver::is_integral_promotion("int", "long"));
    }

    #[test]
    fn test_is_standard_conversion() {
        assert!(OverloadResolver::is_standard_conversion("int", "long"));
        assert!(OverloadResolver::is_standard_conversion("int", "double"));
        assert!(!OverloadResolver::is_standard_conversion("char", "int"));
    }

    #[test]
    fn test_candidate_rank_ordering() {
        assert!(CandidateRank::ExactMatch < CandidateRank::Promotion);
        assert!(CandidateRank::Promotion < CandidateRank::StandardConversion);
        assert!(CandidateRank::StandardConversion < CandidateRank::UserDefinedConversion);
        assert!(CandidateRank::UserDefinedConversion < CandidateRank::Ellipsis);
    }

    #[test]
    fn test_resolver_candidate_management() {
        let mut resolver = OverloadResolver::new();
        let func = make_func("foo", vec![]);
        resolver.add_candidate(func, false);
        assert_eq!(resolver.candidates.len(), 1);
        resolver.reset();
        assert_eq!(resolver.candidates.len(), 0);
    }

    #[test]
    fn test_adl_disabled() {
        let mut resolver = OverloadResolver::new();
        resolver.set_adl_enabled(false);
        let results = resolver.adl_lookup("swap", &["std::vector"], None);
        assert!(results.is_empty());
    }

    #[test]
    fn test_builtin_operator_candidates() {
        let candidates = get_builtin_operator_candidates(CXXOperator::Add, "int", "int");
        assert!(!candidates.is_empty());
    }
}