tsz-solver 0.1.8

TypeScript type solver for the tsz compiler
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
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
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
//! TypeScript compatibility layer for assignability rules.

use crate::db::QueryDatabase;
use crate::diagnostics::SubtypeFailureReason;
use crate::subtype::{NoopResolver, SubtypeChecker, TypeResolver};
use crate::types::{IntrinsicKind, LiteralValue, PropertyInfo, TypeData, TypeId};
use crate::visitor::{TypeVisitor, intrinsic_kind, is_empty_object_type_db, lazy_def_id};
use crate::{AnyPropagationRules, AssignabilityChecker, TypeDatabase};
use rustc_hash::FxHashMap;
use tsz_common::interner::Atom;

// =============================================================================
// Visitor Pattern Implementations
// =============================================================================

/// Visitor to extract object shape ID from types.
struct ShapeExtractor<'a, R: TypeResolver> {
    db: &'a dyn TypeDatabase,
    resolver: &'a R,
    guard: crate::recursion::RecursionGuard<TypeId>,
}

impl<'a, R: TypeResolver> ShapeExtractor<'a, R> {
    fn new(db: &'a dyn TypeDatabase, resolver: &'a R) -> Self {
        Self {
            db,
            resolver,
            guard: crate::recursion::RecursionGuard::with_profile(
                crate::recursion::RecursionProfile::ShapeExtraction,
            ),
        }
    }

    /// Extract shape from a type, returning None if not an object type.
    fn extract(&mut self, type_id: TypeId) -> Option<u32> {
        match self.guard.enter(type_id) {
            crate::recursion::RecursionResult::Entered => {}
            _ => return None, // Cycle or limits exceeded
        }
        let result = self.visit_type(self.db, type_id);
        self.guard.leave(type_id);
        result
    }
}

/// Visitor to check if a type is string-like (string, string literal, or template literal).
struct StringLikeVisitor<'a> {
    db: &'a dyn TypeDatabase,
}

impl<'a> TypeVisitor for StringLikeVisitor<'a> {
    type Output = bool;

    fn visit_intrinsic(&mut self, kind: IntrinsicKind) -> Self::Output {
        kind == IntrinsicKind::String
    }

    fn visit_literal(&mut self, value: &LiteralValue) -> Self::Output {
        matches!(value, LiteralValue::String(_))
    }

    fn visit_template_literal(&mut self, _template_id: u32) -> Self::Output {
        true
    }

    fn visit_type_parameter(&mut self, info: &crate::types::TypeParamInfo) -> Self::Output {
        info.constraint.is_some_and(|c| self.visit_type(self.db, c))
    }

    fn visit_ref(&mut self, symbol_ref: u32) -> Self::Output {
        let _symbol_ref = crate::types::SymbolRef(symbol_ref);
        // Resolve the ref and check the resolved type
        // This is a simplified check - in practice we'd need the resolver
        false
    }

    fn visit_lazy(&mut self, _def_id: u32) -> Self::Output {
        // We can't resolve Lazy without a resolver, so conservatively return false
        false
    }

    fn default_output() -> Self::Output {
        false
    }
}

impl<'a, R: TypeResolver> TypeVisitor for ShapeExtractor<'a, R> {
    type Output = Option<u32>;

    fn visit_intrinsic(&mut self, _kind: crate::types::IntrinsicKind) -> Self::Output {
        None
    }

    fn visit_literal(&mut self, _value: &crate::LiteralValue) -> Self::Output {
        None
    }

    fn visit_object(&mut self, shape_id: u32) -> Self::Output {
        Some(shape_id)
    }

    fn visit_object_with_index(&mut self, shape_id: u32) -> Self::Output {
        Some(shape_id)
    }

    fn visit_lazy(&mut self, def_id: u32) -> Self::Output {
        let def_id = crate::def::DefId(def_id);
        if let Some(resolved) = self.resolver.resolve_lazy(def_id, self.db) {
            return self.extract(resolved);
        }
        None
    }

    fn visit_ref(&mut self, symbol_ref: u32) -> Self::Output {
        let symbol_ref = crate::types::SymbolRef(symbol_ref);
        // Prefer DefId resolution if available
        if let Some(def_id) = self.resolver.symbol_to_def_id(symbol_ref) {
            return self.visit_lazy(def_id.0);
        }
        if let Some(resolved) = self.resolver.resolve_symbol_ref(symbol_ref, self.db) {
            return self.extract(resolved);
        }
        None
    }

    // TSZ-4: Handle Intersection types for nominal checking
    // For private brands, we need to find object shapes within the intersection
    fn visit_intersection(&mut self, list_id: u32) -> Self::Output {
        let member_list = self.db.type_list(crate::types::TypeListId(list_id));
        // For nominal checking, iterate and return the first valid object shape found
        // This ensures we check the private/protected members of constituent types
        for member in member_list.iter() {
            if let Some(shape) = self.visit_type(self.db, *member) {
                return Some(shape);
            }
        }
        None
    }

    fn default_output() -> Self::Output {
        None
    }
}

/// Trait for providing checker-specific assignability overrides.
///
/// This allows the solver's `CompatChecker` to call back into the checker
/// for special cases that require binder/symbol information (enums,
/// abstract constructors, constructor accessibility).
pub trait AssignabilityOverrideProvider {
    /// Override for enum assignability rules.
    /// Returns Some(true/false) if the override applies, None to fall through to structural checking.
    fn enum_assignability_override(&self, source: TypeId, target: TypeId) -> Option<bool>;

    /// Override for abstract constructor assignability rules.
    /// Returns Some(false) if abstract class cannot be assigned to concrete constructor, None otherwise.
    fn abstract_constructor_assignability_override(
        &self,
        source: TypeId,
        target: TypeId,
    ) -> Option<bool>;

    /// Override for constructor accessibility rules (private/protected).
    /// Returns Some(false) if accessibility mismatch prevents assignment, None otherwise.
    fn constructor_accessibility_override(&self, source: TypeId, target: TypeId) -> Option<bool>;
}

/// A no-op implementation of `AssignabilityOverrideProvider` for when no checker context is available.
pub struct NoopOverrideProvider;

impl AssignabilityOverrideProvider for NoopOverrideProvider {
    fn enum_assignability_override(&self, _source: TypeId, _target: TypeId) -> Option<bool> {
        None
    }

    fn abstract_constructor_assignability_override(
        &self,
        _source: TypeId,
        _target: TypeId,
    ) -> Option<bool> {
        None
    }

    fn constructor_accessibility_override(&self, _source: TypeId, _target: TypeId) -> Option<bool> {
        None
    }
}

/// Compatibility checker that applies TypeScript's unsound rules
/// before delegating to the structural subtype engine.
///
/// This layer integrates with the "Lawyer" layer to apply nuanced rules
/// for `any` propagation.
pub struct CompatChecker<'a, R: TypeResolver = NoopResolver> {
    interner: &'a dyn TypeDatabase,
    /// Optional query database for Salsa-backed memoization.
    query_db: Option<&'a dyn QueryDatabase>,
    subtype: SubtypeChecker<'a, R>,
    /// The "Lawyer" layer - handles nuanced rules for `any` propagation.
    lawyer: AnyPropagationRules,
    strict_function_types: bool,
    strict_null_checks: bool,
    no_unchecked_indexed_access: bool,
    exact_optional_property_types: bool,
    /// When true, enables additional strict subtype checking rules for lib.d.ts
    strict_subtype_checking: bool,
    cache: FxHashMap<(TypeId, TypeId), bool>,
}

impl<'a> CompatChecker<'a, NoopResolver> {
    /// Create a new compatibility checker without a resolver.
    /// Note: Callers should configure `strict_function_types` explicitly via `set_strict_function_types()`
    pub fn new(interner: &'a dyn TypeDatabase) -> Self {
        CompatChecker {
            interner,
            query_db: None,
            subtype: SubtypeChecker::new(interner),
            lawyer: AnyPropagationRules::new(),
            // Default to false (legacy TypeScript behavior) for compatibility
            // Callers should set this explicitly based on compiler options
            strict_function_types: false,
            strict_null_checks: true,
            no_unchecked_indexed_access: false,
            exact_optional_property_types: false,
            strict_subtype_checking: false,
            cache: FxHashMap::default(),
        }
    }
}

impl<'a, R: TypeResolver> CompatChecker<'a, R> {
    fn normalize_assignability_operand(&mut self, mut type_id: TypeId) -> TypeId {
        // Keep normalization bounded to avoid infinite resolver/evaluator cycles.
        for _ in 0..8 {
            let next = match self.interner.lookup(type_id) {
                Some(TypeData::Lazy(def_id)) => self
                    .subtype
                    .resolver
                    .resolve_lazy(def_id, self.interner)
                    .unwrap_or(type_id),
                Some(TypeData::Mapped(_) | TypeData::Application(_)) => {
                    self.subtype.evaluate_type(type_id)
                }
                _ => type_id,
            };

            if next == type_id {
                break;
            }
            type_id = next;
        }
        type_id
    }

    fn normalize_assignability_operands(
        &mut self,
        source: TypeId,
        target: TypeId,
    ) -> (TypeId, TypeId) {
        (
            self.normalize_assignability_operand(source),
            self.normalize_assignability_operand(target),
        )
    }

    fn is_function_target_member(&self, member: TypeId) -> bool {
        let is_function_object_shape = match self.interner.lookup(member) {
            Some(TypeData::Object(shape_id) | TypeData::ObjectWithIndex(shape_id)) => {
                let shape = self.interner.object_shape(shape_id);
                let apply = self.interner.intern_string("apply");
                let call = self.interner.intern_string("call");
                let has_apply = shape.properties.iter().any(|prop| prop.name == apply);
                let has_call = shape.properties.iter().any(|prop| prop.name == call);
                has_apply && has_call
            }
            _ => false,
        };

        intrinsic_kind(self.interner, member) == Some(IntrinsicKind::Function)
            || is_function_object_shape
            || self
                .subtype
                .resolver
                .get_boxed_type(IntrinsicKind::Function)
                .is_some_and(|boxed| boxed == member)
            || lazy_def_id(self.interner, member).is_some_and(|def_id| {
                self.subtype
                    .resolver
                    .is_boxed_def_id(def_id, IntrinsicKind::Function)
            })
    }

    /// Create a new compatibility checker with a resolver.
    /// Note: Callers should configure `strict_function_types` explicitly via `set_strict_function_types()`
    pub fn with_resolver(interner: &'a dyn TypeDatabase, resolver: &'a R) -> Self {
        CompatChecker {
            interner,
            query_db: None,
            subtype: SubtypeChecker::with_resolver(interner, resolver),
            lawyer: AnyPropagationRules::new(),
            // Default to false (legacy TypeScript behavior) for compatibility
            // Callers should set this explicitly based on compiler options
            strict_function_types: false,
            strict_null_checks: true,
            no_unchecked_indexed_access: false,
            exact_optional_property_types: false,
            strict_subtype_checking: false,
            cache: FxHashMap::default(),
        }
    }

    /// Set the query database for Salsa-backed memoization.
    /// Propagates to the internal `SubtypeChecker`.
    pub fn set_query_db(&mut self, db: &'a dyn QueryDatabase) {
        self.query_db = Some(db);
        self.subtype.query_db = Some(db);
    }

    /// Set the inheritance graph for nominal class subtype checking.
    /// Propagates to the internal `SubtypeChecker`.
    pub const fn set_inheritance_graph(
        &mut self,
        graph: Option<&'a crate::inheritance::InheritanceGraph>,
    ) {
        self.subtype.inheritance_graph = graph;
    }

    /// Configure strict function parameter checking.
    /// See <https://github.com/microsoft/TypeScript/issues/18654>.
    pub fn set_strict_function_types(&mut self, strict: bool) {
        if self.strict_function_types != strict {
            self.strict_function_types = strict;
            self.cache.clear();
        }
    }

    /// Configure strict null checks (legacy null/undefined assignability).
    pub fn set_strict_null_checks(&mut self, strict: bool) {
        if self.strict_null_checks != strict {
            self.strict_null_checks = strict;
            self.cache.clear();
        }
    }

    /// Configure unchecked indexed access (include `undefined` in `T[K]`).
    pub fn set_no_unchecked_indexed_access(&mut self, enabled: bool) {
        if self.no_unchecked_indexed_access != enabled {
            self.no_unchecked_indexed_access = enabled;
            self.cache.clear();
        }
    }

    /// Configure exact optional property types.
    /// See <https://github.com/microsoft/TypeScript/issues/13195>.
    pub fn set_exact_optional_property_types(&mut self, exact: bool) {
        if self.exact_optional_property_types != exact {
            self.exact_optional_property_types = exact;
            self.cache.clear();
        }
    }

    /// Configure strict mode for `any` propagation.
    /// Configure strict subtype checking mode for lib.d.ts type checking.
    ///
    /// When enabled, applies additional strictness rules that reject borderline
    /// cases allowed by TypeScript's legacy behavior. This includes disabling
    /// method bivariance for soundness.
    pub fn set_strict_subtype_checking(&mut self, strict: bool) {
        if self.strict_subtype_checking != strict {
            self.strict_subtype_checking = strict;
            self.cache.clear();
        }
    }

    /// Apply compiler options from a bitmask flags value.
    ///
    /// The flags correspond to `RelationCacheKey` bits:
    /// - bit 0: `strict_null_checks`
    /// - bit 1: `strict_function_types`
    /// - bit 2: `exact_optional_property_types`
    /// - bit 3: `no_unchecked_indexed_access`
    /// - bit 4: `disable_method_bivariance` (`strict_subtype_checking`)
    /// - bit 5: `allow_void_return`
    /// - bit 6: `allow_bivariant_rest`
    /// - bit 7: `allow_bivariant_param_count`
    ///
    /// This is used by `QueryCache::is_assignable_to_with_flags` to ensure
    /// cached results respect the compiler configuration.
    pub fn apply_flags(&mut self, flags: u16) {
        // Apply flags to CompatChecker's own fields
        let strict_null_checks = (flags & (1 << 0)) != 0;
        let strict_function_types = (flags & (1 << 1)) != 0;
        let exact_optional_property_types = (flags & (1 << 2)) != 0;
        let no_unchecked_indexed_access = (flags & (1 << 3)) != 0;
        let disable_method_bivariance = (flags & (1 << 4)) != 0;

        self.set_strict_null_checks(strict_null_checks);
        self.set_strict_function_types(strict_function_types);
        self.set_exact_optional_property_types(exact_optional_property_types);
        self.set_no_unchecked_indexed_access(no_unchecked_indexed_access);
        self.set_strict_subtype_checking(disable_method_bivariance);

        // Also apply flags to the internal SubtypeChecker
        // We do this directly since apply_flags() uses a builder pattern
        self.subtype.strict_null_checks = strict_null_checks;
        self.subtype.strict_function_types = strict_function_types;
        self.subtype.exact_optional_property_types = exact_optional_property_types;
        self.subtype.no_unchecked_indexed_access = no_unchecked_indexed_access;
        self.subtype.disable_method_bivariance = disable_method_bivariance;
        self.subtype.allow_void_return = (flags & (1 << 5)) != 0;
        self.subtype.allow_bivariant_rest = (flags & (1 << 6)) != 0;
        self.subtype.allow_bivariant_param_count = (flags & (1 << 7)) != 0;
    }

    ///
    /// When strict mode is enabled, `any` does NOT silence structural mismatches.
    /// This means the type checker will still report errors even when `any` is involved,
    /// if there's a real structural mismatch.
    pub fn set_strict_any_propagation(&mut self, strict: bool) {
        self.lawyer.set_allow_any_suppression(!strict);
        self.cache.clear();
    }

    /// Get a reference to the lawyer layer for `any` propagation rules.
    pub const fn lawyer(&self) -> &AnyPropagationRules {
        &self.lawyer
    }

    /// Get a mutable reference to the lawyer layer for `any` propagation rules.
    pub fn lawyer_mut(&mut self) -> &mut AnyPropagationRules {
        self.cache.clear();
        &mut self.lawyer
    }

    /// Apply configuration from `JudgeConfig`.
    ///
    /// This is used to configure the `CompatChecker` with settings from
    /// the `CompilerOptions` (passed through `JudgeConfig`).
    pub fn apply_config(&mut self, config: &crate::judge::JudgeConfig) {
        self.strict_function_types = config.strict_function_types;
        self.strict_null_checks = config.strict_null_checks;
        self.exact_optional_property_types = config.exact_optional_property_types;
        self.no_unchecked_indexed_access = config.no_unchecked_indexed_access;

        // North Star: any should NOT silence structural mismatches in strict mode
        self.lawyer.allow_any_suppression = !config.strict_function_types && !config.sound_mode;

        // Clear cache as configuration changed
        self.cache.clear();
    }

    /// Check if `source` is assignable to `target` using TS compatibility rules.
    pub fn is_assignable(&mut self, source: TypeId, target: TypeId) -> bool {
        // Without strictNullChecks, null and undefined are assignable to and from any type.
        // This check is at the top-level only (not in subtype member iteration) to avoid
        // incorrectly accepting types within union member comparisons.
        if !self.strict_null_checks && target.is_nullish() {
            return true;
        }

        let key = (source, target);
        if let Some(&cached) = self.cache.get(&key) {
            return cached;
        }

        let result = self.is_assignable_impl(source, target, self.strict_function_types);

        self.cache.insert(key, result);
        result
    }

    /// Check for excess properties in object literal assignment (TS2353).
    ///
    /// This implements the "Lawyer" layer rule where fresh object literals
    /// cannot have properties that don't exist in the target type, unless the
    /// target has an index signature.
    ///
    /// # Arguments
    /// * `source` - The source type (should be a fresh object literal)
    /// * `target` - The target type
    ///
    /// # Returns
    /// `true` if no excess properties found, `false` if TS2353 should be reported
    fn check_excess_properties(&mut self, source: TypeId, target: TypeId) -> bool {
        use crate::freshness::is_fresh_object_type;
        use crate::visitor::{ObjectTypeKind, classify_object_type};

        // Only check fresh object literals
        if !is_fresh_object_type(self.interner, source) {
            return true;
        }

        // Get source shape
        let source_shape_id = match classify_object_type(self.interner, source) {
            ObjectTypeKind::Object(shape_id) | ObjectTypeKind::ObjectWithIndex(shape_id) => {
                shape_id
            }
            ObjectTypeKind::NotObject => return true,
        };

        let source_shape = self.interner.object_shape(source_shape_id);

        let (has_string_index, has_number_index) = self.check_index_signatures(target);

        // If target has string index signature, skip excess property check entirely
        if has_string_index {
            return true;
        }

        // Collect all target properties (including base types if intersection)
        let target_properties = self.collect_target_properties(target);

        // TypeScript forgives excess properties when the target type is completely empty
        // (like `{}`, an empty interface, or an empty class) because it accepts any non-primitive.
        if target_properties.is_empty() && !has_number_index {
            return true;
        }

        // Check each source property
        for prop_info in &source_shape.properties {
            if !target_properties.contains(&prop_info.name) {
                // If target has a numeric index signature, numeric-named properties are allowed
                if has_number_index {
                    let name_str = self.interner.resolve_atom(prop_info.name);
                    if name_str.parse::<f64>().is_ok() {
                        continue;
                    }
                }
                // Excess property found!
                return false;
            }
        }

        true
    }

    /// Find the first excess property in object literal assignment.
    ///
    /// Returns `Some(property_name)` if an excess property is found, `None` otherwise.
    /// This is used by `explain_failure` to generate TS2353 diagnostics.
    fn find_excess_property(&mut self, source: TypeId, target: TypeId) -> Option<Atom> {
        use crate::freshness::is_fresh_object_type;
        use crate::visitor::{ObjectTypeKind, classify_object_type};

        // Only check fresh object literals
        if !is_fresh_object_type(self.interner, source) {
            return None;
        }

        // Get source shape
        let source_shape_id = match classify_object_type(self.interner, source) {
            ObjectTypeKind::Object(shape_id) | ObjectTypeKind::ObjectWithIndex(shape_id) => {
                shape_id
            }
            ObjectTypeKind::NotObject => return None,
        };

        let source_shape = self.interner.object_shape(source_shape_id);

        // Get target shape - resolve Lazy, Mapped, and Application types
        let target_key = self.interner.lookup(target);
        let resolved_target = match target_key {
            Some(TypeData::Lazy(def_id)) => {
                // Try to resolve the Lazy type
                self.subtype.resolver.resolve_lazy(def_id, self.interner)?
            }
            Some(TypeData::Mapped(_) | TypeData::Application(_)) => {
                // Evaluate mapped and application types
                self.subtype.evaluate_type(target)
            }
            _ => target,
        };

        let (has_string_index, has_number_index) = self.check_index_signatures(resolved_target);

        // If target has string index signature, skip excess property check entirely
        if has_string_index {
            return None;
        }

        // Collect all target properties (including base types if intersection)
        let target_properties = self.collect_target_properties(resolved_target);

        // TypeScript forgives excess properties when the target type is completely empty
        if target_properties.is_empty() && !has_number_index {
            return None;
        }

        // Check each source property
        for prop_info in &source_shape.properties {
            if !target_properties.contains(&prop_info.name) {
                // If target has a numeric index signature, numeric-named properties are allowed
                if has_number_index {
                    let name_str = self.interner.resolve_atom(prop_info.name);
                    if name_str.parse::<f64>().is_ok() {
                        continue;
                    }
                }
                // Excess property found!
                return Some(prop_info.name);
            }
        }

        None
    }

    /// Collect all property names from a type into a set (handles intersections and unions).
    ///
    /// For intersections: property exists if it's in ANY member
    /// For unions: property exists if it's in ALL members
    /// Check if a type or any of its composite members has a string or numeric index signature.
    /// Returns `(has_string_index, has_number_index)`.
    fn check_index_signatures(&mut self, type_id: TypeId) -> (bool, bool) {
        if type_id == TypeId::ANY || type_id == TypeId::UNKNOWN || type_id == TypeId::ERROR {
            return (true, true);
        }

        let type_id = match self.interner.lookup(type_id) {
            Some(TypeData::Lazy(def_id)) => self
                .subtype
                .resolver
                .resolve_lazy(def_id, self.interner)
                .unwrap_or(type_id),
            Some(TypeData::Mapped(_) | TypeData::Application(_)) => {
                self.subtype.evaluate_type(type_id)
            }
            _ => type_id,
        };

        if type_id == TypeId::ANY || type_id == TypeId::UNKNOWN || type_id == TypeId::ERROR {
            return (true, true);
        }

        match self.interner.lookup(type_id) {
            Some(TypeData::Object(shape_id) | TypeData::ObjectWithIndex(shape_id)) => {
                let shape = self.interner.object_shape(shape_id);
                (shape.string_index.is_some(), shape.number_index.is_some())
            }
            Some(TypeData::Intersection(members_id)) | Some(TypeData::Union(members_id)) => {
                let members = self.interner.type_list(members_id);
                let mut has_str = false;
                let mut has_num = false;
                for &member in members.iter() {
                    let (s, n) = self.check_index_signatures(member);
                    has_str |= s;
                    has_num |= n;
                }
                (has_str, has_num)
            }
            _ => (false, false),
        }
    }

    fn collect_target_properties(&mut self, type_id: TypeId) -> rustc_hash::FxHashSet<Atom> {
        // Handle Mapped and Application types by evaluating them to concrete types
        // We resolve before matching so the existing logic handles the result.
        let type_id = match self.interner.lookup(type_id) {
            Some(TypeData::Mapped(_) | TypeData::Application(_)) => {
                self.subtype.evaluate_type(type_id)
            }
            _ => type_id,
        };

        let mut properties = rustc_hash::FxHashSet::default();

        match self.interner.lookup(type_id) {
            Some(TypeData::Intersection(members_id)) => {
                let members = self.interner.type_list(members_id);
                // Property exists if it's in ANY member of intersection
                for &member in members.iter() {
                    let member_props = self.collect_target_properties(member);
                    properties.extend(member_props);
                }
            }
            Some(TypeData::Union(members_id)) => {
                let members = self.interner.type_list(members_id);
                if members.is_empty() {
                    return properties;
                }
                // For unions, property exists if it's in ALL members
                // Start with first member's properties
                let mut all_props = self.collect_target_properties(members[0]);
                // Intersect with remaining members
                for &member in members.iter().skip(1) {
                    let member_props = self.collect_target_properties(member);
                    all_props = all_props.intersection(&member_props).cloned().collect();
                }
                properties = all_props;
            }
            Some(TypeData::Object(shape_id) | TypeData::ObjectWithIndex(shape_id)) => {
                let shape = self.interner.object_shape(shape_id);
                for prop_info in &shape.properties {
                    properties.insert(prop_info.name);
                }
            }
            _ => {}
        }

        properties
    }

    /// Internal implementation of assignability check.
    /// Extracted to share logic between `is_assignable` and `is_assignable_strict`.
    fn is_assignable_impl(
        &mut self,
        source: TypeId,
        target: TypeId,
        strict_function_types: bool,
    ) -> bool {
        let (source, target) = self.normalize_assignability_operands(source, target);

        // Fast path checks
        if let Some(result) = self.check_assignable_fast_path(source, target) {
            return result;
        }

        // Enum nominal typing check (Lawyer layer implementation)
        // This provides enum member distinction even without checker context
        if let Some(result) = self.enum_assignability_override(source, target) {
            return result;
        }

        // Weak type checks
        if self.violates_weak_union(source, target) {
            return false;
        }
        if self.violates_weak_type(source, target) {
            return false;
        }

        // Excess property checking (TS2353) - Lawyer layer
        if !self.check_excess_properties(source, target) {
            return false;
        }

        // Empty object target
        if self.is_empty_object_target(target) {
            return self.is_assignable_to_empty_object(source);
        }

        // Check mapped-to-mapped structural comparison before full subtype check.
        // When both source and target are deferred mapped types over the same constraint
        // (e.g., Readonly<T> vs Partial<T>), compare template types directly.
        if let (Some(TypeData::Mapped(s_mapped_id)), Some(TypeData::Mapped(t_mapped_id))) =
            (self.interner.lookup(source), self.interner.lookup(target))
        {
            let result = self.check_mapped_to_mapped_assignability(s_mapped_id, t_mapped_id);
            if let Some(assignable) = result {
                return assignable;
            }
        }

        // Default to structural subtype checking
        self.configure_subtype(strict_function_types);
        self.subtype.is_subtype_of(source, target)
    }

    /// Check if two mapped types are assignable via structural template comparison.
    ///
    /// When both source and target are mapped types with the same constraint
    /// (e.g., both iterate over `keyof T`), compare their templates directly.
    /// This handles cases like `Readonly<T>` assignable to `Partial<T>` where
    /// the mapped types can't be concretely expanded because T is generic.
    ///
    /// Returns `Some(true/false)` if determination was made, `None` to fall through.
    fn check_mapped_to_mapped_assignability(
        &mut self,
        s_mapped_id: crate::types::MappedTypeId,
        t_mapped_id: crate::types::MappedTypeId,
    ) -> Option<bool> {
        use crate::types::MappedModifier;
        use crate::visitor::mapped_type_id;

        let s_mapped = self.interner.mapped_type(s_mapped_id);
        let t_mapped = self.interner.mapped_type(t_mapped_id);

        // Both must have the same constraint (e.g., both `keyof T`)
        if s_mapped.constraint != t_mapped.constraint {
            return None;
        }

        let source_template = s_mapped.template;
        let mut target_template = t_mapped.template;

        // If the target adds optional (`?`), the target template effectively
        // becomes `template | undefined` since optional properties accept undefined.
        let target_adds_optional = t_mapped.optional_modifier == Some(MappedModifier::Add);
        let source_adds_optional = s_mapped.optional_modifier == Some(MappedModifier::Add);

        if target_adds_optional && !source_adds_optional {
            target_template = self.interner.union2(target_template, TypeId::UNDEFINED);
        }

        // If the target removes optional (Required) but source doesn't,
        // fall through to full structural check.
        let target_removes_optional = t_mapped.optional_modifier == Some(MappedModifier::Remove);
        if target_removes_optional && !source_adds_optional && s_mapped.optional_modifier.is_none()
        {
            return None;
        }

        // If both templates are themselves mapped types, recurse
        if let (Some(s_inner), Some(t_inner)) = (
            mapped_type_id(self.interner, source_template),
            mapped_type_id(self.interner, target_template),
        ) {
            return self.check_mapped_to_mapped_assignability(s_inner, t_inner);
        }

        // Compare templates using the subtype checker
        self.configure_subtype(self.strict_function_types);
        Some(self.subtype.is_subtype_of(source_template, target_template))
    }

    /// Check fast-path assignability conditions.
    /// Returns Some(result) if fast path applies, None if need to do full check.
    fn check_assignable_fast_path(&self, source: TypeId, target: TypeId) -> Option<bool> {
        if let Some(TypeData::Lazy(def_id)) = self.interner.lookup(target)
            && let Some(resolved_target) = self.subtype.resolver.resolve_lazy(def_id, self.interner)
            && resolved_target != target
        {
            return self.check_assignable_fast_path(source, resolved_target);
        }

        // Same type
        if source == target {
            return Some(true);
        }

        // Any at the top-level is assignable to/from everything
        // UNLESS strict any propagation is enabled (disables suppression)
        if source == TypeId::ANY || target == TypeId::ANY {
            // North Star Fix: any should not silence structural mismatches.
            // We only allow any to match any here, and fall through to structural
            // checking for mixed pairs.
            if source == target {
                return Some(true);
            }
            // If legacy suppression is allowed, we still return true here.
            if self.lawyer.allow_any_suppression {
                return Some(true);
            }
            // Fall through to structural checking for unsound pairs
            return None;
        }

        // Null/undefined in non-strict null check mode
        if !self.strict_null_checks && source.is_nullish() {
            return Some(true);
        }

        // unknown is top
        if target == TypeId::UNKNOWN {
            return Some(true);
        }

        // never is bottom
        if source == TypeId::NEVER {
            return Some(true);
        }

        // Error types are assignable to/from everything (like `any`).
        // In tsc, errorType silences further errors to prevent cascading diagnostics.
        if source == TypeId::ERROR || target == TypeId::ERROR {
            return Some(true);
        }

        // unknown is not assignable to non-top types
        if source == TypeId::UNKNOWN {
            return Some(false);
        }

        // Compatibility: unions containing `Function` should accept callable sources.
        // Example: `setTimeout(() => {}, 0)` where first arg is `string | Function`.
        if let Some(TypeData::Union(members_id)) = self.interner.lookup(target) {
            let members = self.interner.type_list(members_id);
            if members
                .iter()
                .any(|&member| self.is_function_target_member(member))
                && crate::type_queries::is_callable_type(self.interner, source)
            {
                return Some(true);
            }
        }

        None // Need full check
    }

    pub fn is_assignable_strict(&mut self, source: TypeId, target: TypeId) -> bool {
        if let Some(TypeData::Lazy(def_id)) = self.interner.lookup(target)
            && let Some(resolved_target) = self.subtype.resolver.resolve_lazy(def_id, self.interner)
            && resolved_target != target
        {
            return self.is_assignable_strict(source, resolved_target);
        }

        // Always use strict function types
        if source == target {
            return true;
        }
        if !self.strict_null_checks && source.is_nullish() {
            return true;
        }
        // Without strictNullChecks, null and undefined are assignable to and from any type.
        // This check is at the top-level only (not in subtype member iteration).
        if !self.strict_null_checks && target.is_nullish() {
            return true;
        }
        if target == TypeId::UNKNOWN {
            return true;
        }
        if source == TypeId::NEVER {
            return true;
        }
        // Error types are assignable to/from everything (like `any` in tsc)
        if source == TypeId::ERROR || target == TypeId::ERROR {
            return true;
        }
        if source == TypeId::UNKNOWN {
            return false;
        }
        if let Some(TypeData::Union(members_id)) = self.interner.lookup(target) {
            let members = self.interner.type_list(members_id);
            if members
                .iter()
                .any(|&member| self.is_function_target_member(member))
                && crate::type_queries::is_callable_type(self.interner, source)
            {
                return true;
            }
        }
        if self.is_empty_object_target(target) {
            return self.is_assignable_to_empty_object(source);
        }

        let prev = self.subtype.strict_function_types;
        self.configure_subtype(true);
        let result = self.subtype.is_subtype_of(source, target);
        self.subtype.strict_function_types = prev;
        result
    }

    /// Explain why `source` is not assignable to `target` using TS compatibility rules.
    pub fn explain_failure(
        &mut self,
        source: TypeId,
        target: TypeId,
    ) -> Option<SubtypeFailureReason> {
        // Fast path: if assignable, no failure to explain
        if source == target {
            return None;
        }
        if target == TypeId::UNKNOWN {
            return None;
        }
        if !self.strict_null_checks && source.is_nullish() {
            return None;
        }
        // Without strictNullChecks, null and undefined are assignable to and from any type.
        if !self.strict_null_checks && (target == TypeId::NULL || target == TypeId::UNDEFINED) {
            return None;
        }
        if source == TypeId::NEVER {
            return None;
        }
        if source == TypeId::UNKNOWN {
            return Some(SubtypeFailureReason::TypeMismatch {
                source_type: source,
                target_type: target,
            });
        }

        // Error types are assignable to/from everything (like `any` in tsc)
        // No failure to explain — suppress cascading diagnostics
        if source == TypeId::ERROR || target == TypeId::ERROR {
            return None;
        }

        // Weak type violations
        let violates = self.violates_weak_union(source, target);
        if violates {
            return Some(SubtypeFailureReason::TypeMismatch {
                source_type: source,
                target_type: target,
            });
        }
        if self.violates_weak_type(source, target) {
            return Some(SubtypeFailureReason::NoCommonProperties {
                source_type: source,
                target_type: target,
            });
        }

        // Excess property checking (TS2353)
        if let Some(excess_prop) = self.find_excess_property(source, target) {
            return Some(SubtypeFailureReason::ExcessProperty {
                property_name: excess_prop,
                target_type: target,
            });
        }

        // Private brand incompatibility (TS2322)
        // Check this before the structural check so we generate the right error
        if let Some(false) = self.private_brand_assignability_override(source, target) {
            return Some(SubtypeFailureReason::TypeMismatch {
                source_type: source,
                target_type: target,
            });
        }

        // Empty object target
        if self.is_empty_object_target(target) && self.is_assignable_to_empty_object(source) {
            return None;
        }

        self.configure_subtype(self.strict_function_types);
        self.subtype.explain_failure(source, target)
    }

    const fn configure_subtype(&mut self, strict_function_types: bool) {
        self.subtype.strict_function_types = strict_function_types;
        self.subtype.allow_void_return = true;
        self.subtype.allow_bivariant_rest = true;
        self.subtype.exact_optional_property_types = self.exact_optional_property_types;
        self.subtype.strict_null_checks = self.strict_null_checks;
        self.subtype.no_unchecked_indexed_access = self.no_unchecked_indexed_access;
        // Any propagation is controlled by the Lawyer's allow_any_suppression flag
        // Standard TypeScript allows any to propagate through arrays/objects regardless
        // of strictFunctionTypes - it only affects function parameter variance
        self.subtype.any_propagation = self.lawyer.any_propagation_mode();
        // In strict mode, disable method bivariance for soundness
        self.subtype.disable_method_bivariance = self.strict_subtype_checking;
    }

    fn violates_weak_type(&self, source: TypeId, target: TypeId) -> bool {
        let mut extractor = ShapeExtractor::new(self.interner, self.subtype.resolver);

        let target_shape_id = match extractor.extract(target) {
            Some(id) => id,
            None => return false,
        };

        let target_shape = self
            .interner
            .object_shape(crate::types::ObjectShapeId(target_shape_id));

        // ObjectWithIndex with index signatures is not a weak type
        if let Some(TypeData::ObjectWithIndex(_)) = self.interner.lookup(target)
            && (target_shape.string_index.is_some() || target_shape.number_index.is_some())
        {
            return false;
        }

        let target_props = target_shape.properties.as_slice();
        if target_props.is_empty() || target_props.iter().any(|prop| !prop.optional) {
            return false;
        }

        self.violates_weak_type_with_target_props(source, target_props)
    }

    fn violates_weak_union(&self, source: TypeId, target: TypeId) -> bool {
        // Don't resolve the target - check it directly for union type
        // (resolve_weak_type_ref was converting unions to objects, which is wrong)
        let target_key = match self.interner.lookup(target) {
            Some(TypeData::Union(members)) => members,
            _ => {
                return false;
            }
        };

        let members = self.interner.type_list(target_key);
        if members.is_empty() {
            return false;
        }

        let mut extractor = ShapeExtractor::new(self.interner, self.subtype.resolver);
        let mut has_weak_member = false;

        for member in members.iter() {
            let resolved_member = self.resolve_weak_type_ref(*member);
            // Weak-union checks only apply when ALL union members are object-like.
            // If any member is primitive/non-object (e.g. `string | Function`),
            // TypeScript does not apply TS2559-style weak-type rejection.
            let member_shape_id = match extractor.extract(resolved_member) {
                Some(id) => id,
                None => return false,
            };

            let member_shape = self
                .interner
                .object_shape(crate::types::ObjectShapeId(member_shape_id));

            if member_shape.properties.is_empty()
                || member_shape.string_index.is_some()
                || member_shape.number_index.is_some()
            {
                return false;
            }

            if member_shape.properties.iter().all(|prop| prop.optional) {
                has_weak_member = true;
            }
        }

        if !has_weak_member {
            return false;
        }

        self.source_lacks_union_common_property(source, members.as_ref())
    }

    pub fn is_weak_union_violation(&self, source: TypeId, target: TypeId) -> bool {
        self.violates_weak_union(source, target)
    }

    fn violates_weak_type_with_target_props(
        &self,
        source: TypeId,
        target_props: &[PropertyInfo],
    ) -> bool {
        // Handle Union types explicitly before visitor
        if let Some(TypeData::Union(members)) = self.interner.lookup(source) {
            let members = self.interner.type_list(members);
            return members
                .iter()
                .all(|member| self.violates_weak_type_with_target_props(*member, target_props));
        }

        let mut extractor = ShapeExtractor::new(self.interner, self.subtype.resolver);
        let source_shape_id = match extractor.extract(source) {
            Some(id) => id,
            None => return false,
        };

        let source_shape = self
            .interner
            .object_shape(crate::types::ObjectShapeId(source_shape_id));
        let source_props = source_shape.properties.as_slice();

        // Empty objects are assignable to weak types (all optional properties).
        // Only trigger weak type violation if source has properties that don't overlap.
        !source_props.is_empty() && !self.has_common_property(source_props, target_props)
    }

    fn source_lacks_union_common_property(
        &self,
        source: TypeId,
        target_members: &[TypeId],
    ) -> bool {
        let source = self.resolve_weak_type_ref(source);

        // Handle Union explicitly
        if let Some(TypeData::Union(members)) = self.interner.lookup(source) {
            let members = self.interner.type_list(members);
            return members
                .iter()
                .all(|member| self.source_lacks_union_common_property(*member, target_members));
        }

        // Handle TypeParameter explicitly
        if let Some(TypeData::TypeParameter(param)) = self.interner.lookup(source) {
            return match param.constraint {
                Some(constraint) => {
                    self.source_lacks_union_common_property(constraint, target_members)
                }
                None => false,
            };
        }

        // Use visitor for Object types
        let mut extractor = ShapeExtractor::new(self.interner, self.subtype.resolver);
        let source_shape_id = match extractor.extract(source) {
            Some(id) => id,
            None => return false,
        };

        let source_shape = self
            .interner
            .object_shape(crate::types::ObjectShapeId(source_shape_id));
        if source_shape.string_index.is_some() || source_shape.number_index.is_some() {
            return false;
        }
        let source_props = source_shape.properties.as_slice();
        if source_props.is_empty() {
            return false;
        }

        let mut has_common = false;
        for member in target_members {
            let resolved_member = self.resolve_weak_type_ref(*member);
            let member_shape_id = match extractor.extract(resolved_member) {
                Some(id) => id,
                None => continue,
            };

            let member_shape = self
                .interner
                .object_shape(crate::types::ObjectShapeId(member_shape_id));
            if member_shape.string_index.is_some() || member_shape.number_index.is_some() {
                return false;
            }
            if self.has_common_property(source_props, member_shape.properties.as_slice()) {
                has_common = true;
                break;
            }
        }

        !has_common
    }

    fn has_common_property(
        &self,
        source_props: &[PropertyInfo],
        target_props: &[PropertyInfo],
    ) -> bool {
        let mut source_idx = 0;
        let mut target_idx = 0;

        while source_idx < source_props.len() && target_idx < target_props.len() {
            let source_name = source_props[source_idx].name;
            let target_name = target_props[target_idx].name;
            if source_name == target_name {
                return true;
            }
            if source_name < target_name {
                source_idx += 1;
            } else {
                target_idx += 1;
            }
        }

        false
    }

    fn resolve_weak_type_ref(&self, type_id: TypeId) -> TypeId {
        self.subtype.resolve_ref_type(type_id)
    }

    /// Check if a type is an empty object target.
    /// Uses the visitor pattern from `solver::visitor`.
    fn is_empty_object_target(&self, target: TypeId) -> bool {
        is_empty_object_type_db(self.interner, target)
    }

    fn is_assignable_to_empty_object(&self, source: TypeId) -> bool {
        if source == TypeId::ANY || source == TypeId::NEVER {
            return true;
        }
        // Error types are assignable to everything (like `any` in tsc)
        if source == TypeId::ERROR {
            return true;
        }
        if !self.strict_null_checks && source.is_nullish() {
            return true;
        }
        if source == TypeId::UNKNOWN
            || source == TypeId::NULL
            || source == TypeId::UNDEFINED
            || source == TypeId::VOID
        {
            return false;
        }

        let key = match self.interner.lookup(source) {
            Some(key) => key,
            None => return false,
        };

        match key {
            TypeData::Union(members) => {
                let members = self.interner.type_list(members);
                members
                    .iter()
                    .all(|member| self.is_assignable_to_empty_object(*member))
            }
            TypeData::Intersection(members) => {
                let members = self.interner.type_list(members);
                members
                    .iter()
                    .any(|member| self.is_assignable_to_empty_object(*member))
            }
            TypeData::TypeParameter(param) => match param.constraint {
                Some(constraint) => self.is_assignable_to_empty_object(constraint),
                None => false,
            },
            _ => true,
        }
    }
}

impl<'a, R: TypeResolver> AssignabilityChecker for CompatChecker<'a, R> {
    fn is_assignable_to(&mut self, source: TypeId, target: TypeId) -> bool {
        self.is_assignable(source, target)
    }

    fn is_assignable_to_strict(&mut self, source: TypeId, target: TypeId) -> bool {
        self.is_assignable_strict(source, target)
    }

    fn is_assignable_to_bivariant_callback(&mut self, source: TypeId, target: TypeId) -> bool {
        // Bypass the cache and perform a one-off check with non-strict function variance.
        self.is_assignable_impl(source, target, false)
    }

    fn evaluate_type(&mut self, type_id: TypeId) -> TypeId {
        self.subtype.evaluate_type(type_id)
    }
}

// =============================================================================
// Assignability Override Functions (moved from checker/state.rs)
// =============================================================================

impl<'a, R: TypeResolver> CompatChecker<'a, R> {
    /// Check if `source` is assignable to `target` using TS compatibility rules,
    /// with checker-provided overrides for enums, abstract constructors, and accessibility.
    ///
    /// This is the main entry point for assignability checking when checker context is available.
    pub fn is_assignable_with_overrides<P: AssignabilityOverrideProvider + ?Sized>(
        &mut self,
        source: TypeId,
        target: TypeId,
        overrides: &P,
    ) -> bool {
        // Check override provider for enum assignability
        if let Some(result) = overrides.enum_assignability_override(source, target) {
            return result;
        }

        // Check override provider for abstract constructor assignability
        if let Some(result) = overrides.abstract_constructor_assignability_override(source, target)
        {
            return result;
        }

        // Check override provider for constructor accessibility
        if let Some(result) = overrides.constructor_accessibility_override(source, target) {
            return result;
        }

        // Check private brand assignability (can be done with TypeDatabase alone)
        if let Some(result) = self.private_brand_assignability_override(source, target) {
            return result;
        }

        // Fall through to regular assignability check
        self.is_assignable(source, target)
    }

    /// Private brand assignability override.
    /// If both source and target types have private brands, they must match exactly.
    /// This implements nominal typing for classes with private fields.
    ///
    /// Uses recursive structure to preserve Union/Intersection semantics:
    /// - Union (A | B): OR logic - must satisfy at least one branch
    /// - Intersection (A & B): AND logic - must satisfy all branches
    pub fn private_brand_assignability_override(
        &self,
        source: TypeId,
        target: TypeId,
    ) -> Option<bool> {
        use crate::types::Visibility;

        // Fast path: identical types don't need nominal brand override logic.
        // Let the regular assignability path decide.
        if source == target {
            return None;
        }

        // 1. Handle Target Union (OR logic)
        // S -> (A | B) : Valid if S -> A OR S -> B
        if let Some(TypeData::Union(members)) = self.interner.lookup(target) {
            let members = self.interner.type_list(members);
            // If source matches ANY target member, it's valid
            for &member in members.iter() {
                match self.private_brand_assignability_override(source, member) {
                    Some(true) | None => return None, // Pass (or structural fallback)
                    Some(false) => {}                 // Keep checking other members
                }
            }
            return Some(false); // Failed against all members
        }

        // 2. Handle Source Union (AND logic)
        // (A | B) -> T : Valid if A -> T AND B -> T
        if let Some(TypeData::Union(members)) = self.interner.lookup(source) {
            let members = self.interner.type_list(members);
            for &member in members.iter() {
                if let Some(false) = self.private_brand_assignability_override(member, target) {
                    return Some(false); // Fail if any member fails
                }
            }
            return None; // All passed or fell back
        }

        // 3. Handle Target Intersection (AND logic)
        // S -> (A & B) : Valid if S -> A AND S -> B
        if let Some(TypeData::Intersection(members)) = self.interner.lookup(target) {
            let members = self.interner.type_list(members);
            for &member in members.iter() {
                if let Some(false) = self.private_brand_assignability_override(source, member) {
                    return Some(false); // Fail if any member fails
                }
            }
            return None; // All passed or fell back
        }

        // 4. Handle Source Intersection (OR logic)
        // (A & B) -> T : Valid if A -> T OR B -> T
        if let Some(TypeData::Intersection(members)) = self.interner.lookup(source) {
            let members = self.interner.type_list(members);
            for &member in members.iter() {
                match self.private_brand_assignability_override(member, target) {
                    Some(true) | None => return None, // Pass (or structural fallback)
                    Some(false) => {}                 // Keep checking other members
                }
            }
            return Some(false); // Failed against all members
        }

        // 5. Handle Lazy types (recursive resolution)
        if let Some(TypeData::Lazy(def_id)) = self.interner.lookup(source)
            && let Some(resolved) = self.subtype.resolver.resolve_lazy(def_id, self.interner)
        {
            // Guard against non-progressing lazy resolution (e.g. DefId -> same Lazy type),
            // which would otherwise recurse forever.
            if resolved == source {
                return None;
            }
            return self.private_brand_assignability_override(resolved, target);
        }

        if let Some(TypeData::Lazy(def_id)) = self.interner.lookup(target)
            && let Some(resolved) = self.subtype.resolver.resolve_lazy(def_id, self.interner)
        {
            // Same non-progress guard for target-side lazy resolution.
            if resolved == target {
                return None;
            }
            return self.private_brand_assignability_override(source, resolved);
        }

        // 6. Base case: Extract and compare object shapes
        let mut extractor = ShapeExtractor::new(self.interner, self.subtype.resolver);

        // Get source shape
        let source_shape_id = extractor.extract(source)?;
        let source_shape = self
            .interner
            .object_shape(crate::types::ObjectShapeId(source_shape_id));

        // Get target shape
        let mut extractor = ShapeExtractor::new(self.interner, self.subtype.resolver);
        let target_shape_id = extractor.extract(target)?;
        let target_shape = self
            .interner
            .object_shape(crate::types::ObjectShapeId(target_shape_id));

        let mut has_private_brands = false;

        // Check Target requirements (Nominality)
        // If Target has a private/protected property, Source MUST match its origin exactly.
        for target_prop in &target_shape.properties {
            if target_prop.visibility == Visibility::Private
                || target_prop.visibility == Visibility::Protected
            {
                has_private_brands = true;
                let source_prop = source_shape
                    .properties
                    .binary_search_by_key(&target_prop.name, |p| p.name)
                    .ok()
                    .map(|idx| &source_shape.properties[idx]);

                match source_prop {
                    Some(sp) => {
                        // CRITICAL: The parent_id must match exactly.
                        if sp.parent_id != target_prop.parent_id {
                            return Some(false);
                        }
                    }
                    None => {
                        return Some(false);
                    }
                }
            }
        }

        // Check Source restrictions (Visibility leakage)
        // If Source has a private/protected property, it cannot be assigned to a Target
        // that expects it to be Public.
        for source_prop in &source_shape.properties {
            if source_prop.visibility == Visibility::Private
                || source_prop.visibility == Visibility::Protected
            {
                has_private_brands = true;
                if let Some(target_prop) = target_shape
                    .properties
                    .binary_search_by_key(&source_prop.name, |p| p.name)
                    .ok()
                    .map(|idx| &target_shape.properties[idx])
                    && target_prop.visibility == Visibility::Public
                {
                    return Some(false);
                }
            }
        }

        has_private_brands.then_some(true)
    }

    /// Enum member assignability override.
    /// Implements nominal typing for enum members: EnumA.X is NOT assignable to `EnumB` even if values match.
    ///
    /// TypeScript enum rules:
    /// 1. Different enums with different `DefIds` are NOT assignable (nominal typing)
    /// 2. Numeric enums are bidirectionally assignable to number (Rule #7 - Open Numeric Enums)
    /// 3. String enums are strictly nominal (string literals NOT assignable to string enums)
    /// 4. Same enum members with different values are NOT assignable (EnumA.X != EnumA.Y)
    /// 5. Unions containing enums: Source union assigned to target enum checks all members
    pub fn enum_assignability_override(&self, source: TypeId, target: TypeId) -> Option<bool> {
        use crate::type_queries;
        use crate::visitor;

        // Special case: Source union -> Target enum
        // When assigning a union to an enum, ALL enum members in the union must match the target enum.
        // This handles cases like: (EnumA | EnumB) assigned to EnumC
        // And allows: (Choice.Yes | Choice.No) assigned to Choice (subset of same enum)
        if let Some((t_def, _)) = visitor::enum_components(self.interner, target)
            && type_queries::is_union_type(self.interner, source)
        {
            let union_members = type_queries::get_union_members(self.interner, source)?;

            let mut all_same_enum = true;
            let mut has_non_enum = false;
            for &member in &union_members {
                if let Some((member_def, _)) = visitor::enum_components(self.interner, member) {
                    // Check if this member belongs to the target enum.
                    // Members have their own DefIds (different from parent enum's DefId),
                    // so we must also check the parent relationship.
                    let member_parent = self.subtype.resolver.get_enum_parent_def_id(member_def);
                    if member_def != t_def && member_parent != Some(t_def) {
                        // Found an enum member from a different enum than target
                        return Some(false);
                    }
                } else {
                    all_same_enum = false;
                    has_non_enum = true;
                }
            }

            // If ALL union members are enum members from the same enum as the target,
            // the union is a subset of the enum and therefore assignable.
            // This handles: `type YesNo = Choice.Yes | Choice.No` assignable to `Choice`.
            if all_same_enum && !has_non_enum && !union_members.is_empty() {
                return Some(true);
            }
            // Otherwise fall through to structural check for non-enum union members.
        }

        // String enums are assignable to string (like numeric enums are to number).
        // Fall through to structural checking for this case.

        // Fast path: Check if both are enum types with same DefId but different TypeIds
        // This handles the test case where enum members aren't in the resolver
        if let (Some((s_def, _)), Some((t_def, _))) = (
            visitor::enum_components(self.interner, source),
            visitor::enum_components(self.interner, target),
        ) && s_def == t_def
            && source != target
        {
            // Same enum DefId but different TypeIds
            // Check if both are literal enum members (not union-based enums)
            if self.is_literal_enum_member(source) && self.is_literal_enum_member(target) {
                // Both are enum literals with same DefId but different values
                // Nominal rule: E.A is NOT assignable to E.B
                return Some(false);
            }
        }

        let source_def = self.get_enum_def_id(source);
        let target_def = self.get_enum_def_id(target);

        match (source_def, target_def) {
            // Case 1: Both are enums (or enum members or Union-based enums)
            // Note: Same-DefId, different-TypeId case is now handled above before get_enum_def_id
            (Some(s_def), Some(t_def)) => {
                if s_def == t_def {
                    // Same DefId: Same type (E.A -> E.A or E -> E)
                    return Some(true);
                }

                // Gap A: Different DefIds, but might be member -> parent relationship
                // Check if they share a parent enum (e.g., E.A -> E)
                let s_parent = self.subtype.resolver.get_enum_parent_def_id(s_def);
                let t_parent = self.subtype.resolver.get_enum_parent_def_id(t_def);

                match (s_parent, t_parent) {
                    (Some(sp), Some(tp)) if sp == tp => {
                        // Same parent enum
                        // If target is the Enum Type (e.g., 'E'), allow structural check
                        if self.subtype.resolver.is_enum_type(target, self.interner) {
                            return None;
                        }
                        // If target is a different specific member (e.g., 'E.B'), reject nominally
                        // E.A -> E.B should fail even if they have the same value
                        Some(false)
                    }
                    (Some(sp), None) => {
                        // Source is a member, target doesn't have a parent (target is not a member)
                        // Check if target is the parent enum type
                        if t_def == sp {
                            // Target is the parent enum of source member
                            // Allow member to parent enum assignment (E.A -> E)
                            return Some(true);
                        }
                        // Target is an enum type but not the parent
                        Some(false)
                    }
                    _ => {
                        // Different parents (or one/both are types, not members)
                        // Nominal mismatch: EnumA.X is not assignable to EnumB
                        Some(false)
                    }
                }
            }

            // Case 2: Target is an enum, source is a primitive
            (None, Some(t_def)) => {
                // Check if target is a numeric enum
                if self.subtype.resolver.is_numeric_enum(t_def) {
                    // Rule #7: Numeric enums allow number assignability
                    // BUT we need to distinguish between:
                    // - `let x: E = 1` (enum TYPE - allowed)
                    // - `let x: E.A = 1` (enum MEMBER - rejected)

                    // Check if source is number-like (number or number literal)
                    let is_source_number = source == TypeId::NUMBER
                        || matches!(
                            self.interner.lookup(source),
                            Some(TypeData::Literal(LiteralValue::Number(_)))
                        );

                    if is_source_number {
                        // If target is the full Enum Type (e.g., `let x: E = 1`), allow it.
                        if self.subtype.resolver.is_enum_type(target, self.interner) {
                            return Some(true);
                        }

                        // If target is a specific member (e.g., `let x: E.A = 1`),
                        // fall through to structural check.
                        // - `1 -> E.A(0)` will fail structural check (Correct)
                        // - `0 -> E.A(0)` will pass structural check (Correct)
                        return None;
                    }

                    None
                } else {
                    // String enums do NOT allow raw string assignability
                    // If source is string or string literal, reject
                    if self.is_string_like(source) {
                        return Some(false);
                    }
                    None
                }
            }

            // Case 3: Source is an enum, target is a primitive
            // String enums (both types and members) are assignable to string via structural checking
            (Some(s_def), None) => {
                // Check if source is a string enum
                if !self.subtype.resolver.is_numeric_enum(s_def) {
                    // Source is a string enum
                    if target == TypeId::STRING {
                        // Both enum types (Union of members) and enum members (string literals)
                        // are assignable to string. Fall through to structural checking.
                        return None;
                    }
                }
                // Numeric enums and non-string targets: fall through to structural check
                None
            }

            // Case 4: Neither is an enum
            (None, None) => None,
        }
    }

    /// Check if a type is string-like (string, string literal, or template literal).
    /// Used to reject primitive-to-string-enum assignments.
    fn is_string_like(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::STRING {
            return true;
        }
        // Use visitor to check for string literals, template literals, etc.
        let mut visitor = StringLikeVisitor { db: self.interner };
        visitor.visit_type(self.interner, type_id)
    }

    /// Get the `DefId` of an enum type, handling both direct Enum members and Union-based Enums.
    /// Check whether `type_id` is an enum whose underlying member is a string or number literal.
    fn is_literal_enum_member(&self, type_id: TypeId) -> bool {
        matches!(
            self.interner.lookup(type_id),
            Some(TypeData::Enum(_, member_type))
                if matches!(
                    self.interner.lookup(member_type),
                    Some(TypeData::Literal(LiteralValue::Number(_) | LiteralValue::String(_)))
                )
        )
    }

    /// Returns `Some(def_id)` if the type is an Enum or a Union of Enum members from the same enum.
    /// Returns None if the type is not an enum or contains mixed enums.
    fn get_enum_def_id(&self, type_id: TypeId) -> Option<crate::def::DefId> {
        use crate::{type_queries, visitor};

        // Resolve Lazy types first (handles imported/forward-declared enums)
        let resolved =
            if let Some(lazy_def_id) = type_queries::get_lazy_def_id(self.interner, type_id) {
                // Try to resolve the Lazy type
                if let Some(resolved_type) = self
                    .subtype
                    .resolver
                    .resolve_lazy(lazy_def_id, self.interner)
                {
                    // Guard against self-referential lazy types
                    if resolved_type == type_id {
                        return None;
                    }
                    // Recursively check the resolved type
                    return self.get_enum_def_id(resolved_type);
                }
                // Lazy type couldn't be resolved yet, return None
                return None;
            } else {
                type_id
            };

        // 1. Check for Intrinsic Primitives first (using visitor, not TypeId constants)
        // This filters out intrinsic types like string, number, boolean which are stored
        // as TypeData::Enum for definition store purposes but are NOT user enums
        if visitor::intrinsic_kind(self.interner, resolved).is_some() {
            return None;
        }

        // 2. Check direct Enum member
        if let Some((def_id, _inner)) = visitor::enum_components(self.interner, resolved) {
            // Use the new is_user_enum_def method to check if this is a user-defined enum
            // This properly filters out intrinsic types from lib.d.ts
            if self.subtype.resolver.is_user_enum_def(def_id) {
                return Some(def_id);
            }
            // Not a user-defined enum (intrinsic type or type alias)
            return None;
        }

        // 3. Check Union of Enum members (handles Enum types represented as Unions)
        if let Some(members) = visitor::union_list_id(self.interner, resolved) {
            let members = self.interner.type_list(members);
            if members.is_empty() {
                return None;
            }

            let first_def = self.get_enum_def_id(members[0])?;
            for &member in members.iter().skip(1) {
                if self.get_enum_def_id(member) != Some(first_def) {
                    return None; // Mixed union or non-enum members
                }
            }
            return Some(first_def);
        }

        None
    }

    /// Checks if two types are compatible for variable redeclaration (TS2403).
    ///
    /// This applies TypeScript's nominal identity rules for enums and
    /// respects 'any' propagation. Used for checking if multiple variable
    /// declarations have compatible types.
    ///
    /// # Examples
    /// - `var x: number; var x: number` → true
    /// - `var x: E.A; var x: E.A` → true
    /// - `var x: E.A; var x: E.B` → false
    /// - `var x: E; var x: F` → false (different enums)
    /// - `var x: E; var x: number` → false
    pub fn are_types_identical_for_redeclaration(&mut self, a: TypeId, b: TypeId) -> bool {
        // 1. Fast path: physical identity
        if a == b {
            return true;
        }

        // 2. Error propagation — suppress cascading errors from ERROR types.
        if a == TypeId::ERROR || b == TypeId::ERROR {
            return true;
        }

        // For redeclaration, `any` is only identical to `any`.
        // `a == b` already caught the `any == any` case above.
        if a == TypeId::ANY || b == TypeId::ANY {
            return false;
        }

        // 4. Enum Nominality Check
        // If one is an enum and the other isn't, or they are different enums,
        // they are not identical for redeclaration, even if structurally compatible.
        if let Some(res) = self.enum_redeclaration_check(a, b) {
            return res;
        }

        // 5. Normalize Application/Mapped/Lazy types before structural comparison.
        // Required<{a?: string}> must evaluate to {a: string} before bidirectional
        // subtype checking, just as is_assignable_impl() does via normalize_assignability_operands.
        let (a_norm, b_norm) = self.normalize_assignability_operands(a, b);
        tracing::trace!(
            a = a.0,
            b = b.0,
            a_norm = a_norm.0,
            b_norm = b_norm.0,
            a_changed = a != a_norm,
            b_changed = b != b_norm,
            "are_types_identical_for_redeclaration: normalized"
        );
        let a = a_norm;
        let b = b_norm;

        // 5. Structural Identity
        // Delegate to the Judge to check bidirectional subtyping
        let fwd = self.subtype.is_subtype_of(a, b);
        let bwd = self.subtype.is_subtype_of(b, a);
        tracing::trace!(
            a = a.0,
            b = b.0,
            fwd,
            bwd,
            "are_types_identical_for_redeclaration: result"
        );
        fwd && bwd
    }

    /// Check if two types involving enums are compatible for redeclaration.
    ///
    /// Returns Some(bool) if either type is an enum:
    /// - Some(false) if different enums or enum vs primitive
    /// - None if neither is an enum (delegate to structural check)
    fn enum_redeclaration_check(&self, a: TypeId, b: TypeId) -> Option<bool> {
        let a_def = self.get_enum_def_id(a);
        let b_def = self.get_enum_def_id(b);

        match (a_def, b_def) {
            (Some(def_a), Some(def_b)) => {
                // Both are enums: must be the same enum definition
                if def_a != def_b {
                    Some(false)
                } else {
                    // Same enum DefId: compatible for redeclaration
                    // This allows: var x: MyEnum; var x = MyEnum.Member;
                    // where MyEnum.Member (enum member) is compatible with MyEnum (enum type)
                    Some(true)
                }
            }
            (Some(_), None) | (None, Some(_)) => {
                // One is an enum, the other is a primitive (e.g., number)
                // In TS, Enum E and 'number' are NOT identical for redeclaration
                Some(false)
            }
            (None, None) => None,
        }
    }
}

#[cfg(test)]
#[path = "../tests/compat_tests.rs"]
mod tests;