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
//! Contextual typing (reverse inference).
//!
//! Contextual typing allows type information to flow "backwards" from
//! an expected type to an expression. This is used for:
//! - Arrow function parameters: `const f: (x: string) => void = (x) => ...`
//! - Array literals: `const arr: number[] = [1, 2, 3]`
//! - Object literals: `const obj: {x: number} = {x: 1}`
//!
//! The key insight is that when we have an expected type, we can use it
//! to infer types for parts of the expression that would otherwise be unknown.

use crate::TypeDatabase;
#[cfg(test)]
use crate::types::*;
use crate::types::{
    CallableShapeId, FunctionShapeId, IntrinsicKind, LiteralValue, ObjectShapeId, ParamInfo,
    TupleListId, TypeApplicationId, TypeData, TypeId, TypeListId,
};
use crate::visitor::TypeVisitor;

// =============================================================================
// Helper Functions
// =============================================================================

/// Helper to collect types and return None, single type, or union.
///
/// This pattern appears frequently in visitor implementations:
/// - If no types collected: return None
/// - If one type collected: return Some(that type)
/// - If multiple types: return Some(union of types)
fn collect_single_or_union(db: &dyn TypeDatabase, types: Vec<TypeId>) -> Option<TypeId> {
    match types.len() {
        0 => None,
        1 => Some(types[0]),
        _ => Some(db.union(types)),
    }
}

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

/// Visitor to extract the `this` type from callable types.
struct ThisTypeExtractor<'a> {
    db: &'a dyn TypeDatabase,
}

impl<'a> ThisTypeExtractor<'a> {
    fn new(db: &'a dyn TypeDatabase) -> Self {
        Self { db }
    }

    fn extract(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.visit_type(self.db, type_id)
    }
}

impl<'a> TypeVisitor for ThisTypeExtractor<'a> {
    type Output = Option<TypeId>;

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

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

    fn visit_function(&mut self, shape_id: u32) -> Self::Output {
        self.db.function_shape(FunctionShapeId(shape_id)).this_type
    }

    fn visit_callable(&mut self, shape_id: u32) -> Self::Output {
        let shape = self.db.callable_shape(CallableShapeId(shape_id));
        // Collect this types from all signatures
        let this_types: Vec<TypeId> = shape
            .call_signatures
            .iter()
            .filter_map(|sig| sig.this_type)
            .collect();

        collect_single_or_union(self.db, this_types)
    }

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

/// Visitor to extract the return type from callable types.
struct ReturnTypeExtractor<'a> {
    db: &'a dyn TypeDatabase,
}

impl<'a> ReturnTypeExtractor<'a> {
    fn new(db: &'a dyn TypeDatabase) -> Self {
        Self { db }
    }

    fn extract(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.visit_type(self.db, type_id)
    }
}

impl<'a> TypeVisitor for ReturnTypeExtractor<'a> {
    type Output = Option<TypeId>;

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

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

    fn visit_function(&mut self, shape_id: u32) -> Self::Output {
        Some(
            self.db
                .function_shape(FunctionShapeId(shape_id))
                .return_type,
        )
    }

    fn visit_callable(&mut self, shape_id: u32) -> Self::Output {
        let shape = self.db.callable_shape(CallableShapeId(shape_id));
        // Collect return types from all signatures
        let return_types: Vec<TypeId> = shape
            .call_signatures
            .iter()
            .map(|sig| sig.return_type)
            .collect();

        collect_single_or_union(self.db, return_types)
    }

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        // For unions of callable types, extract return type from each member
        // and create a union of the results.
        let members = self.db.type_list(TypeListId(list_id));
        let types: Vec<TypeId> = members
            .iter()
            .filter_map(|&member| {
                let mut extractor = ReturnTypeExtractor::new(self.db);
                extractor.extract(member)
            })
            .collect();
        collect_single_or_union(self.db, types)
    }

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

/// Visitor to extract the type T from `ThisType`<T> utility type markers.
///
/// This handles the Vue 2 / Options API pattern where contextual types contain
/// `ThisType`<T> markers to override the type of 'this' in object literal methods.
///
/// Example:
/// ```typescript
/// type ObjectDescriptor<D, M> = {
///     methods?: M & ThisType<D & M>;
/// };
/// ```
struct ThisTypeMarkerExtractor<'a> {
    db: &'a dyn TypeDatabase,
}

impl<'a> ThisTypeMarkerExtractor<'a> {
    fn new(db: &'a dyn TypeDatabase) -> Self {
        Self { db }
    }

    fn extract(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.visit_type(self.db, type_id)
    }

    /// Check if a type application is for the `ThisType` utility.
    fn is_this_type_application(&self, app_id: u32) -> bool {
        let app = self.db.type_application(TypeApplicationId(app_id));

        // CRITICAL: We must NOT return true for all Lazy types!
        // Doing so would break ALL generic type aliases (Partial<T>, Readonly<T>, etc.)
        // We must check if the base type is specifically "ThisType"

        // Check TypeParameter case first (easier - has name directly)
        if let Some(TypeData::TypeParameter(tp)) = self.db.lookup(app.base) {
            let name = self.db.resolve_atom_ref(tp.name);
            return name.as_ref() == "ThisType";
        }

        // For Lazy types (type aliases), we need to resolve the def_id to a name
        // This is harder without access to the symbol table. For now, we fail safe
        // and return false rather than breaking all type aliases.
        // TODO: When we have access to symbol resolution, check if def_id points to lib.d.ts ThisType
        if let Some(TypeData::Lazy(_def_id)) = self.db.lookup(app.base) {
            // Cannot safely identify ThisType without symbol table access
            // Return false to avoid breaking other type aliases
            return false;
        }

        false
    }
}

impl<'a> TypeVisitor for ThisTypeMarkerExtractor<'a> {
    type Output = Option<TypeId>;

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

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

    fn visit_application(&mut self, app_id: u32) -> Self::Output {
        if self.is_this_type_application(app_id) {
            let app = self.db.type_application(TypeApplicationId(app_id));
            // ThisType<T> has exactly one type argument T
            app.args.first().copied()
        } else {
            // Not a ThisType application, recurse into base and args
            let app = self.db.type_application(TypeApplicationId(app_id));
            let base_result = self.visit_type(self.db, app.base);

            // Collect results from all arguments
            let arg_results: Vec<_> = app
                .args
                .iter()
                .filter_map(|&arg_id| self.visit_type(self.db, arg_id))
                .collect();

            // If we found ThisType in arguments, return the first one
            // (ThisType should only appear once in a given type structure)
            if let Some(result) = base_result {
                Some(result)
            } else if let Some(&first) = arg_results.first() {
                Some(first)
            } else {
                None
            }
        }
    }

    fn visit_intersection(&mut self, list_id: u32) -> Self::Output {
        let members = self.db.type_list(TypeListId(list_id));

        // Collect all ThisType markers from the intersection
        let this_types: Vec<TypeId> = members
            .iter()
            .filter_map(|&member_id| self.visit_type(self.db, member_id))
            .collect();

        if this_types.is_empty() {
            None
        } else if this_types.len() == 1 {
            Some(this_types[0])
        } else {
            // Multiple ThisType markers - intersect them
            // ThisType<A> & ThisType<B> => this is A & B
            Some(self.db.intersection(this_types))
        }
    }

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        // For unions, we distribute over members
        // (A & ThisType<X>) | (B & ThisType<Y>) should try each member
        let members = self.db.type_list(TypeListId(list_id));

        // TODO: This blindly picks the first ThisType.
        // Correct behavior requires narrowing the contextual type based on
        // the object literal shape BEFORE determining which this type to use.
        // Example: If context is (A & ThisType<X>) | (B & ThisType<Y>) and
        // the literal is { type: 'b' }, we should pick ThisType<Y>, not ThisType<X>.
        // This is a conservative heuristic and could be improved.
        members
            .iter()
            .find_map(|&member_id| self.visit_type(self.db, member_id))
    }

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

/// Visitor to extract array element type or union of tuple element types.
struct ArrayElementExtractor<'a> {
    db: &'a dyn TypeDatabase,
}

impl<'a> ArrayElementExtractor<'a> {
    fn new(db: &'a dyn TypeDatabase) -> Self {
        Self { db }
    }

    fn extract(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.visit_type(self.db, type_id)
    }
}

impl<'a> TypeVisitor for ArrayElementExtractor<'a> {
    type Output = Option<TypeId>;

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

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

    fn visit_array(&mut self, elem_type: TypeId) -> Self::Output {
        Some(elem_type)
    }

    fn visit_object(&mut self, shape_id: u32) -> Self::Output {
        let shape = self.db.object_shape(ObjectShapeId(shape_id));
        if let Some(ref idx) = shape.number_index {
            return Some(idx.value_type);
        }
        if let Some(ref idx) = shape.string_index {
            return Some(idx.value_type);
        }
        None
    }

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

    fn visit_tuple(&mut self, elements_id: u32) -> Self::Output {
        let elements = self.db.tuple_list(TupleListId(elements_id));
        if elements.is_empty() {
            None
        } else {
            let types: Vec<TypeId> = elements.iter().map(|e| e.type_id).collect();
            Some(self.db.union(types))
        }
    }

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

/// Visitor to extract tuple element at a specific index.
struct TupleElementExtractor<'a> {
    db: &'a dyn TypeDatabase,
    index: usize,
}

impl<'a> TupleElementExtractor<'a> {
    fn new(db: &'a dyn TypeDatabase, index: usize) -> Self {
        Self { db, index }
    }

    fn extract(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.visit_type(self.db, type_id)
    }
}

impl<'a> TypeVisitor for TupleElementExtractor<'a> {
    type Output = Option<TypeId>;

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

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

    fn visit_tuple(&mut self, elements_id: u32) -> Self::Output {
        let elements = self.db.tuple_list(TupleListId(elements_id));
        if self.index < elements.len() {
            Some(elements[self.index].type_id)
        } else if let Some(last) = elements.last() {
            last.rest.then_some(last.type_id)
        } else {
            None
        }
    }

    fn visit_array(&mut self, elem_type: TypeId) -> Self::Output {
        Some(elem_type)
    }

    fn visit_object(&mut self, shape_id: u32) -> Self::Output {
        let shape = self.db.object_shape(ObjectShapeId(shape_id));
        if let Some(ref idx) = shape.number_index {
            return Some(idx.value_type);
        }
        if let Some(ref idx) = shape.string_index {
            return Some(idx.value_type);
        }
        None
    }

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

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        // For unions of tuple/array types, extract the element type from each member
        // and create a union of the results.
        let members = self.db.type_list(TypeListId(list_id));
        let types: Vec<TypeId> = members
            .iter()
            .filter_map(|&member| {
                let mut extractor = TupleElementExtractor::new(self.db, self.index);
                extractor.extract(member)
            })
            .collect();
        collect_single_or_union(self.db, types)
    }

    fn visit_intersection(&mut self, list_id: u32) -> Self::Output {
        // For intersections, try each member and return the first match.
        let members = self.db.type_list(TypeListId(list_id));
        for &member in members.iter() {
            let mut extractor = TupleElementExtractor::new(self.db, self.index);
            if let Some(ty) = extractor.extract(member) {
                return Some(ty);
            }
        }
        None
    }

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

/// Visitor to extract property type from object types by name.
struct PropertyExtractor<'a> {
    db: &'a dyn TypeDatabase,
    name: String,
}

impl<'a> PropertyExtractor<'a> {
    fn new(db: &'a dyn TypeDatabase, name: String) -> Self {
        Self { db, name }
    }

    fn extract(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.visit_type(self.db, type_id)
    }
}

impl<'a> TypeVisitor for PropertyExtractor<'a> {
    type Output = Option<TypeId>;

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

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

    fn visit_object(&mut self, shape_id: u32) -> Self::Output {
        let shape = self.db.object_shape(ObjectShapeId(shape_id));
        for prop in &shape.properties {
            if self.db.resolve_atom_ref(prop.name).as_ref() == self.name {
                return Some(prop.type_id);
            }
        }
        // Fall back to index signatures for Object types too
        // This handles cases where interfaces/types have index signatures
        // but are stored as Object rather than ObjectWithIndex
        // For numeric property names (e.g., "1"), check number index signature first
        if self.name.parse::<f64>().is_ok()
            && let Some(ref idx) = shape.number_index
        {
            return Some(idx.value_type);
        }
        if let Some(ref idx) = shape.string_index {
            return Some(idx.value_type);
        }
        None
    }

    fn visit_object_with_index(&mut self, shape_id: u32) -> Self::Output {
        // First try named properties
        if let Some(ty) = self.visit_object(shape_id) {
            return Some(ty);
        }
        let shape = self.db.object_shape(ObjectShapeId(shape_id));
        // For numeric property names, check number index signature first
        if self.name.parse::<f64>().is_ok()
            && let Some(ref idx) = shape.number_index
        {
            return Some(idx.value_type);
        }
        // Fall back to string index signature value type
        if let Some(ref idx) = shape.string_index {
            return Some(idx.value_type);
        }
        None
    }

    fn visit_lazy(&mut self, def_id: u32) -> Self::Output {
        let resolved = crate::evaluate::evaluate_type(self.db, TypeId(def_id));
        if resolved != TypeId(def_id) {
            self.visit_type(self.db, resolved)
        } else {
            None
        }
    }

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        // For unions, extract the property from each member and combine as a union.
        // e.g., for { foo: ... } with contextual type A | B,
        // the contextual type of `foo` is A["foo"] | B["foo"].
        let members = self.db.type_list(TypeListId(list_id));
        let types: Vec<TypeId> = members
            .iter()
            .filter_map(|&member| {
                let mut extractor = PropertyExtractor::new(self.db, self.name.clone());
                extractor.extract(member)
            })
            .collect();
        collect_single_or_union(self.db, types)
    }

    fn visit_intersection(&mut self, list_id: u32) -> Self::Output {
        let members = self.db.type_list(TypeListId(list_id));
        for &member in members.iter() {
            let mut extractor = PropertyExtractor::new(self.db, self.name.clone());
            if let Some(ty) = extractor.extract(member) {
                return Some(ty);
            }
        }
        None
    }

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

/// Extract the parameter type at `index` from a parameter list, handling rest params.
fn extract_param_type_at(
    db: &dyn TypeDatabase,
    params: &[ParamInfo],
    index: usize,
) -> Option<TypeId> {
    let rest_param = params.last().filter(|p| p.rest);
    let rest_start = if rest_param.is_some() {
        params.len().saturating_sub(1)
    } else {
        params.len()
    };

    // Regular (non-rest) parameters: return directly by index
    if index < rest_start {
        return Some(params[index].type_id);
    }

    // Rest parameter handling
    if let Some(last_param) = rest_param {
        // Adjust index relative to rest parameter start
        let rest_index = index - rest_start;
        if let Some(TypeData::Array(elem)) = db.lookup(last_param.type_id) {
            return Some(elem);
        }
        if let Some(TypeData::Tuple(elements)) = db.lookup(last_param.type_id) {
            let elements = db.tuple_list(elements);
            if rest_index < elements.len() {
                return Some(elements[rest_index].type_id);
            } else if let Some(last_elem) = elements.last()
                && last_elem.rest
            {
                return Some(last_elem.type_id);
            }
            // If out of bounds of the tuple constraint without rest, return undefined/unknown?
            // Fall through
        } else if let Some(TypeData::TypeParameter(param_info)) = db.lookup(last_param.type_id) {
            if let Some(constraint) = param_info.constraint {
                let mut mock_params = params.to_vec();
                mock_params.last_mut().unwrap().type_id = constraint;
                return extract_param_type_at(db, &mock_params, index);
            }
        } else if let Some(TypeData::Intersection(members)) = db.lookup(last_param.type_id) {
            let members = db.type_list(members);
            for &m in members.iter() {
                let mut mock_params = params.to_vec();
                mock_params.last_mut().unwrap().type_id = m;
                if let Some(param_type) = extract_param_type_at(db, &mock_params, index) {
                    // Try to evaluate it if it's a generic type or placeholder to see if it yields a concrete type
                    if !matches!(
                        db.lookup(param_type),
                        Some(TypeData::TypeParameter(_) | TypeData::Intersection(_))
                    ) {
                        return Some(param_type);
                    }
                }
            }
            // If all returned generic types, just fall through
        } else if let Some(TypeData::Application(_app_id)) = db.lookup(last_param.type_id) {
            let evaluated = crate::evaluate::evaluate_type(db, last_param.type_id);
            if evaluated != last_param.type_id {
                let mut mock_params = params.to_vec();
                mock_params.last_mut().unwrap().type_id = evaluated;
                return extract_param_type_at(db, &mock_params, index);
            }
        }

        // If we still didn't extract a specific type, check constraint
        if let Some(constraint) =
            crate::type_queries::get_type_parameter_constraint(db, last_param.type_id)
        {
            let mut mock_params = params.to_vec();
            mock_params.last_mut().unwrap().type_id = constraint;
            if let Some(param_type) = extract_param_type_at(db, &mock_params, index) {
                // If it yielded something different than the constraint itself, use it
                if param_type != constraint {
                    return Some(param_type);
                }
            }
        }

        return Some(last_param.type_id);
    }

    // Index within non-rest params
    (index < params.len()).then(|| params[index].type_id)
}

/// Visitor to extract parameter type from callable types.
struct ParameterExtractor<'a> {
    db: &'a dyn TypeDatabase,
    index: usize,
    no_implicit_any: bool,
}

impl<'a> ParameterExtractor<'a> {
    fn new(db: &'a dyn TypeDatabase, index: usize, no_implicit_any: bool) -> Self {
        Self {
            db,
            index,
            no_implicit_any,
        }
    }

    fn extract(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.visit_type(self.db, type_id)
    }
}

impl<'a> TypeVisitor for ParameterExtractor<'a> {
    type Output = Option<TypeId>;

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

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

    fn visit_function(&mut self, shape_id: u32) -> Self::Output {
        let shape = self.db.function_shape(FunctionShapeId(shape_id));
        extract_param_type_at(self.db, &shape.params, self.index)
    }

    fn visit_callable(&mut self, shape_id: u32) -> Self::Output {
        let shape = self.db.callable_shape(CallableShapeId(shape_id));
        // Collect parameter types from all signatures at the given index
        let param_types: Vec<TypeId> = shape
            .call_signatures
            .iter()
            .filter_map(|sig| extract_param_type_at(self.db, &sig.params, self.index))
            .collect();

        if param_types.is_empty() {
            None
        } else if param_types.len() == 1 {
            Some(param_types[0])
        } else {
            // Multiple different parameter types
            // If noImplicitAny is false, fall back to `any` (return None)
            // If noImplicitAny is true, create a union type
            self.no_implicit_any.then(|| self.db.union(param_types))
        }
    }

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        // For unions of callable types, extract the parameter type from each member
        // and create a union of the results.
        // e.g., ((a: number) => void) | ((a: string) => void) at index 0 => number | string
        let members = self.db.type_list(TypeListId(list_id));
        let types: Vec<TypeId> = members
            .iter()
            .filter_map(|&member| {
                let mut extractor =
                    ParameterExtractor::new(self.db, self.index, self.no_implicit_any);
                extractor.extract(member)
            })
            .collect();
        collect_single_or_union(self.db, types)
    }

    fn visit_intersection(&mut self, list_id: u32) -> Self::Output {
        // For intersections, try each member and return the first match.
        let members = self.db.type_list(TypeListId(list_id));
        for &member in members.iter() {
            let mut extractor = ParameterExtractor::new(self.db, self.index, self.no_implicit_any);
            if let Some(ty) = extractor.extract(member) {
                return Some(ty);
            }
        }
        None
    }

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

/// Visitor to extract parameter type from callable types for a call site.
/// Filters signatures by arity (`arg_count`) to handle overloaded functions.
struct ParameterForCallExtractor<'a> {
    db: &'a dyn TypeDatabase,
    index: usize,
    arg_count: usize,
}

impl<'a> ParameterForCallExtractor<'a> {
    fn new(db: &'a dyn TypeDatabase, index: usize, arg_count: usize) -> Self {
        Self {
            db,
            index,
            arg_count,
        }
    }

    fn extract(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.visit_type(self.db, type_id)
    }

    fn signature_accepts_arg_count(&self, params: &[ParamInfo], arg_count: usize) -> bool {
        // Count required (non-optional) parameters
        let required_count = params.iter().filter(|p| !p.optional).count();

        // Check if there's a rest parameter
        let has_rest = params.iter().any(|p| p.rest);

        if has_rest {
            // With rest parameter: arity must be >= required_count
            arg_count >= required_count
        } else {
            // Without rest parameter: arity must be within [required_count, total_count]
            arg_count >= required_count && arg_count <= params.len()
        }
    }
}

impl<'a> TypeVisitor for ParameterForCallExtractor<'a> {
    type Output = Option<TypeId>;

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

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

    fn visit_function(&mut self, shape_id: u32) -> Self::Output {
        let shape = self.db.function_shape(FunctionShapeId(shape_id));

        if !self.signature_accepts_arg_count(&shape.params, self.arg_count) {
            return None;
        }

        extract_param_type_at(self.db, &shape.params, self.index)
    }

    fn visit_callable(&mut self, shape_id: u32) -> Self::Output {
        let shape = self.db.callable_shape(CallableShapeId(shape_id));

        let mut matched = false;
        let mut param_types: Vec<TypeId> = Vec::new();

        for sig in &shape.call_signatures {
            if self.signature_accepts_arg_count(&sig.params, self.arg_count) {
                matched = true;
                if let Some(param_type) = extract_param_type_at(self.db, &sig.params, self.index) {
                    param_types.push(param_type);
                }
            }
        }

        if param_types.is_empty() && !matched {
            param_types = shape
                .call_signatures
                .iter()
                .filter_map(|sig| extract_param_type_at(self.db, &sig.params, self.index))
                .collect();
        }

        // If no call signatures matched, check non-generic construct signatures.
        // This handles super() calls and new expressions where the callee
        // is a Callable with construct signatures (not call signatures).
        // Skip generic construct signatures: their type parameters must be
        // inferred by the solver, not used as contextual types for arguments.
        if param_types.is_empty() {
            matched = false;
            for sig in &shape.construct_signatures {
                if !sig.type_params.is_empty() {
                    continue;
                }
                if self.signature_accepts_arg_count(&sig.params, self.arg_count) {
                    matched = true;
                    if let Some(param_type) =
                        extract_param_type_at(self.db, &sig.params, self.index)
                    {
                        param_types.push(param_type);
                    }
                }
            }
            if param_types.is_empty() && !matched {
                param_types = shape
                    .construct_signatures
                    .iter()
                    .filter(|sig| sig.type_params.is_empty())
                    .filter_map(|sig| extract_param_type_at(self.db, &sig.params, self.index))
                    .collect();
            }
        }

        collect_single_or_union(self.db, param_types)
    }

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        // For unions, extract parameter types from each member and combine.
        let members = self.db.type_list(TypeListId(list_id));
        let types: Vec<TypeId> = members
            .iter()
            .filter_map(|&member| {
                let mut extractor =
                    ParameterForCallExtractor::new(self.db, self.index, self.arg_count);
                extractor.extract(member)
            })
            .collect();
        collect_single_or_union(self.db, types)
    }

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

/// Visitor to extract a type argument at a given index from an Application type.
///
/// Used for `Generator<Y, R, N>` and similar generic types where we need to
/// pull out a specific type parameter by position.
struct ApplicationArgExtractor<'a> {
    db: &'a dyn TypeDatabase,
    arg_index: usize,
}

impl<'a> ApplicationArgExtractor<'a> {
    fn new(db: &'a dyn TypeDatabase, arg_index: usize) -> Self {
        Self { db, arg_index }
    }

    fn extract(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.visit_type(self.db, type_id)
    }
}

impl<'a> TypeVisitor for ApplicationArgExtractor<'a> {
    type Output = Option<TypeId>;

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

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

    fn visit_application(&mut self, app_id: u32) -> Self::Output {
        let app = self.db.type_application(TypeApplicationId(app_id));
        app.args.get(self.arg_index).copied()
    }

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

/// Context for contextual typing.
/// Holds the expected type and provides methods to extract type information.
pub struct ContextualTypeContext<'a> {
    interner: &'a dyn TypeDatabase,
    /// The expected type (contextual type)
    expected: Option<TypeId>,
    /// Whether noImplicitAny is enabled (affects contextual typing for multi-signature functions)
    no_implicit_any: bool,
}

impl<'a> ContextualTypeContext<'a> {
    /// Create a new contextual type context.
    /// Defaults to `no_implicit_any: false` for compatibility.
    pub fn new(interner: &'a dyn TypeDatabase) -> Self {
        ContextualTypeContext {
            interner,
            expected: None,
            no_implicit_any: false,
        }
    }

    /// Create a context with an expected type.
    /// Defaults to `no_implicit_any: false` for compatibility.
    pub fn with_expected(interner: &'a dyn TypeDatabase, expected: TypeId) -> Self {
        ContextualTypeContext {
            interner,
            expected: Some(expected),
            no_implicit_any: false,
        }
    }

    /// Create a context with an expected type and explicit noImplicitAny setting.
    pub fn with_expected_and_options(
        interner: &'a dyn TypeDatabase,
        expected: TypeId,
        no_implicit_any: bool,
    ) -> Self {
        ContextualTypeContext {
            interner,
            expected: Some(expected),
            no_implicit_any,
        }
    }

    /// Get the expected type.
    pub const fn expected(&self) -> Option<TypeId> {
        self.expected
    }

    /// Check if we have a contextual type.
    pub const fn has_context(&self) -> bool {
        self.expected.is_some()
    }

    /// Get the contextual type for a function parameter at the given index.
    ///
    /// Example:
    /// ```typescript
    /// type Handler = (e: string, i: number) => void;
    /// const h: Handler = (x, y) => {};  // x: string, y: number from context
    /// ```
    pub fn get_parameter_type(&self, index: usize) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect parameter types from all members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let param_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected_and_options(
                        self.interner,
                        m,
                        self.no_implicit_any,
                    );
                    ctx.get_parameter_type(index)
                })
                .collect();

            return collect_single_or_union(self.interner, param_types);
        }

        // Handle Application explicitly - unwrap to base type
        if let Some(TypeData::Application(app_id)) = self.interner.lookup(expected) {
            let app = self.interner.type_application(app_id);
            let ctx = ContextualTypeContext::with_expected_and_options(
                self.interner,
                app.base,
                self.no_implicit_any,
            );
            return ctx.get_parameter_type(index);
        }

        // Handle Intersection explicitly - pick the first callable member's parameter type
        if let Some(TypeData::Intersection(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            for &m in members.iter() {
                let ctx = ContextualTypeContext::with_expected_and_options(
                    self.interner,
                    m,
                    self.no_implicit_any,
                );
                if let Some(param_type) = ctx.get_parameter_type(index) {
                    return Some(param_type);
                }
            }
            return None;
        }

        // Handle Mapped, Conditional, and Lazy types by evaluating them first
        if let Some(TypeData::Mapped(_) | TypeData::Conditional(_) | TypeData::Lazy(_)) =
            self.interner.lookup(expected)
        {
            let evaluated = crate::evaluate::evaluate_type(self.interner, expected);
            if evaluated != expected {
                let ctx = ContextualTypeContext::with_expected_and_options(
                    self.interner,
                    evaluated,
                    self.no_implicit_any,
                );
                return ctx.get_parameter_type(index);
            }
        }

        // Use visitor for Function/Callable types
        let mut extractor = ParameterExtractor::new(self.interner, index, self.no_implicit_any);
        extractor.extract(expected)
    }

    /// Get the contextual type for a call argument at the given index and arity.
    pub fn get_parameter_type_for_call(&self, index: usize, arg_count: usize) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect parameter types from all members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let param_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected(self.interner, m);
                    ctx.get_parameter_type_for_call(index, arg_count)
                })
                .collect();

            return collect_single_or_union(self.interner, param_types);
        }

        // Handle Application explicitly - unwrap to base type
        if let Some(TypeData::Application(app_id)) = self.interner.lookup(expected) {
            let app = self.interner.type_application(app_id);
            let ctx = ContextualTypeContext::with_expected(self.interner, app.base);
            return ctx.get_parameter_type_for_call(index, arg_count);
        }

        // Handle Intersection explicitly - pick the first callable member's parameter type
        if let Some(TypeData::Intersection(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            for &m in members.iter() {
                let ctx = ContextualTypeContext::with_expected(self.interner, m);
                if let Some(param_type) = ctx.get_parameter_type_for_call(index, arg_count) {
                    return Some(param_type);
                }
            }
            return None;
        }

        // Use visitor for Function/Callable types
        let mut extractor = ParameterForCallExtractor::new(self.interner, index, arg_count);
        extractor.extract(expected)
    }

    /// Get the contextual type for a `this` parameter, if present on the expected type.
    pub fn get_this_type(&self) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect this types from all members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let this_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected(self.interner, m);
                    ctx.get_this_type()
                })
                .collect();

            return collect_single_or_union(self.interner, this_types);
        }

        // Handle Application explicitly - unwrap to base type
        if let Some(TypeData::Application(app_id)) = self.interner.lookup(expected) {
            let app = self.interner.type_application(app_id);
            let ctx = ContextualTypeContext::with_expected(self.interner, app.base);
            return ctx.get_this_type();
        }

        // Use visitor for Function/Callable types
        let mut extractor = ThisTypeExtractor::new(self.interner);
        extractor.extract(expected)
    }

    /// Get the type T from a `ThisType`<T> marker in the contextual type.
    ///
    /// This is used for the Vue 2 / Options API pattern where object literal
    /// methods have their `this` type overridden by contextual markers.
    ///
    /// Example:
    /// ```typescript
    /// type ObjectDescriptor<D, M> = {
    ///     methods?: M & ThisType<D & M>;
    /// };
    /// const obj: ObjectDescriptor<{x: number}, {greet(): void}> = {
    ///     methods: {
    ///         greet() { console.log(this.x); } // this is D & M
    ///     }
    /// };
    /// ```
    pub fn get_this_type_from_marker(&self) -> Option<TypeId> {
        let expected = self.expected?;
        let mut extractor = ThisTypeMarkerExtractor::new(self.interner);
        extractor.extract(expected)
    }

    /// Get the contextual return type for a function.
    pub fn get_return_type(&self) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect return types from all members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let return_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected(self.interner, m);
                    ctx.get_return_type()
                })
                .collect();

            return collect_single_or_union(self.interner, return_types);
        }

        // Handle Application explicitly - unwrap to base type
        if let Some(TypeData::Application(app_id)) = self.interner.lookup(expected) {
            let app = self.interner.type_application(app_id);
            let ctx = ContextualTypeContext::with_expected(self.interner, app.base);
            return ctx.get_return_type();
        }

        // Handle Lazy, Mapped, and Conditional types by evaluating first
        if let Some(TypeData::Lazy(_) | TypeData::Mapped(_) | TypeData::Conditional(_)) =
            self.interner.lookup(expected)
        {
            let evaluated = crate::evaluate::evaluate_type(self.interner, expected);
            if evaluated != expected {
                let ctx = ContextualTypeContext::with_expected(self.interner, evaluated);
                return ctx.get_return_type();
            }
        }

        // Use visitor for Function/Callable types
        let mut extractor = ReturnTypeExtractor::new(self.interner);
        extractor.extract(expected)
    }

    /// Get the contextual element type for an array.
    ///
    /// Example:
    /// ```typescript
    /// const arr: number[] = [1, 2, 3];  // elements are contextually typed as number
    /// ```
    pub fn get_array_element_type(&self) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect element types from all array members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let elem_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected(self.interner, m);
                    ctx.get_array_element_type()
                })
                .collect();
            return collect_single_or_union(self.interner, elem_types);
        }

        // Handle Application explicitly - evaluate to resolve type aliases
        if let Some(TypeData::Application(_)) = self.interner.lookup(expected) {
            let evaluated = crate::evaluate::evaluate_type(self.interner, expected);
            if evaluated != expected {
                let ctx = ContextualTypeContext::with_expected(self.interner, evaluated);
                return ctx.get_array_element_type();
            }
        }

        // Handle Mapped/Conditional/Lazy types
        if let Some(TypeData::Mapped(_) | TypeData::Conditional(_) | TypeData::Lazy(_)) =
            self.interner.lookup(expected)
        {
            let evaluated = crate::evaluate::evaluate_type(self.interner, expected);
            if evaluated != expected {
                let ctx = ContextualTypeContext::with_expected(self.interner, evaluated);
                return ctx.get_array_element_type();
            }
        }

        // Handle TypeParameter - use its constraint for element extraction
        if let Some(constraint) =
            crate::type_queries::get_type_parameter_constraint(self.interner, expected)
        {
            let ctx = ContextualTypeContext::with_expected(self.interner, constraint);
            return ctx.get_array_element_type();
        }

        // Handle Intersection - pick the first array member's element type
        if let Some(TypeData::Intersection(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            for &m in members.iter() {
                let ctx = ContextualTypeContext::with_expected(self.interner, m);
                if let Some(elem_type) = ctx.get_array_element_type() {
                    return Some(elem_type);
                }
            }
            return None;
        }

        let mut extractor = ArrayElementExtractor::new(self.interner);
        extractor.extract(expected)
    }

    /// Get the contextual type for a specific tuple element.
    pub fn get_tuple_element_type(&self, index: usize) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect tuple element types from all members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let elem_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected(self.interner, m);
                    ctx.get_tuple_element_type(index)
                })
                .collect();
            return collect_single_or_union(self.interner, elem_types);
        }

        // Handle Application explicitly - evaluate to resolve type aliases
        if let Some(TypeData::Application(_)) = self.interner.lookup(expected) {
            let evaluated = crate::evaluate::evaluate_type(self.interner, expected);
            if evaluated != expected {
                let ctx = ContextualTypeContext::with_expected(self.interner, evaluated);
                return ctx.get_tuple_element_type(index);
            }
        }

        // Handle TypeParameter - use its constraint
        if let Some(constraint) =
            crate::type_queries::get_type_parameter_constraint(self.interner, expected)
        {
            let ctx = ContextualTypeContext::with_expected(self.interner, constraint);
            return ctx.get_tuple_element_type(index);
        }

        // Handle Mapped, Conditional, and Lazy types by evaluating them first
        if let Some(TypeData::Mapped(_) | TypeData::Conditional(_) | TypeData::Lazy(_)) =
            self.interner.lookup(expected)
        {
            let evaluated = crate::evaluate::evaluate_type(self.interner, expected);
            if evaluated != expected {
                let ctx = ContextualTypeContext::with_expected(self.interner, evaluated);
                return ctx.get_tuple_element_type(index);
            }
        }

        let mut extractor = TupleElementExtractor::new(self.interner, index);
        extractor.extract(expected)
    }

    /// Get the contextual type for an object property.
    ///
    /// Example:
    /// ```typescript
    /// const obj: {x: number, y: string} = {x: 1, y: "hi"};
    /// ```
    pub fn get_property_type(&self, name: &str) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect property types from all members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let prop_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected(self.interner, m);
                    ctx.get_property_type(name)
                })
                .collect();

            return if prop_types.is_empty() {
                None
            } else if prop_types.len() == 1 {
                Some(prop_types[0])
            } else {
                // CRITICAL: Use union_preserve_members to keep literal types intact
                // For discriminated unions like `{ success: false } | { success: true }`,
                // the property type should be `false | true`, NOT widened to `boolean`.
                // This preserves literal types for contextual typing.
                Some(self.interner.union_preserve_members(prop_types))
            };
        }

        // Handle Mapped, Conditional, and Application types.
        // These complex types need to be resolved to concrete object types before
        // property extraction can work.
        match self.interner.lookup(expected) {
            Some(TypeData::Mapped(mapped_id)) => {
                // First try evaluating the mapped type directly
                let evaluated = crate::evaluate::evaluate_type(self.interner, expected);
                if evaluated != expected {
                    let ctx = ContextualTypeContext::with_expected(self.interner, evaluated);
                    return ctx.get_property_type(name);
                }
                // If evaluation deferred (e.g. { [K in keyof T]: TakeString } where T is a type
                // parameter), use the mapped type's template as the contextual property type
                // IF the template doesn't reference the mapped type's bound parameter.
                // For example, { [P in keyof T]: TakeString } has template=TakeString which
                // is independent of P, so it's safe to use directly. But { [P in K]: T[P] }
                // has template=T[P] which depends on P, so we can't use it.
                let mapped = self.interner.mapped_type(mapped_id);
                if mapped.template != TypeId::ANY
                    && mapped.template != TypeId::ERROR
                    && mapped.template != TypeId::NEVER
                    && !crate::visitor::contains_type_matching(
                        self.interner,
                        mapped.template,
                        |key| matches!(key, TypeData::BoundParameter(_)),
                    )
                {
                    return Some(mapped.template);
                }
                // Fall back to the constraint of the mapped type's source.
                // For `keyof P` where `P extends Props`, use `Props` as the contextual type.
                if let Some(TypeData::KeyOf(operand)) = self.interner.lookup(mapped.constraint) {
                    // The operand may be a Lazy type wrapping a type parameter — resolve it
                    let resolved_operand = crate::evaluate::evaluate_type(self.interner, operand);
                    if let Some(constraint) = crate::type_queries::get_type_parameter_constraint(
                        self.interner,
                        resolved_operand,
                    ) {
                        let ctx = ContextualTypeContext::with_expected(self.interner, constraint);
                        return ctx.get_property_type(name);
                    }
                    // Also try the original operand (may already be a TypeParameter)
                    if let Some(constraint) =
                        crate::type_queries::get_type_parameter_constraint(self.interner, operand)
                    {
                        let ctx = ContextualTypeContext::with_expected(self.interner, constraint);
                        return ctx.get_property_type(name);
                    }
                }
            }
            Some(TypeData::Application(app_id)) => {
                let evaluated = crate::evaluate::evaluate_type(self.interner, expected);
                if evaluated != expected {
                    let ctx = ContextualTypeContext::with_expected(self.interner, evaluated);
                    return ctx.get_property_type(name);
                }
                // Fallback for unevaluated Application types (e.g. Readonly<T>, Partial<T>).
                // When evaluation fails (e.g. due to RefCell borrow conflicts during contextual
                // typing), try to extract the property from the type argument directly.
                // This is correct for homomorphic mapped types where property types are preserved.
                let app = self.interner.type_application(app_id);
                if !app.args.is_empty() {
                    let ctx = ContextualTypeContext::with_expected(self.interner, app.args[0]);
                    if let Some(prop) = ctx.get_property_type(name) {
                        return Some(prop);
                    }
                }
            }
            Some(TypeData::Conditional(_) | TypeData::Lazy(_)) => {
                let evaluated = crate::evaluate::evaluate_type(self.interner, expected);
                if evaluated != expected {
                    let ctx = ContextualTypeContext::with_expected(self.interner, evaluated);
                    return ctx.get_property_type(name);
                }
            }
            _ => {}
        }

        // Handle TypeParameter - use its constraint for property extraction
        // Example: Actions extends ActionsObject<State>
        // When getting property from Actions, use ActionsObject<State> instead
        if let Some(constraint) =
            crate::type_queries::get_type_parameter_constraint(self.interner, expected)
        {
            let ctx = ContextualTypeContext::with_expected(self.interner, constraint);
            return ctx.get_property_type(name);
        }

        // Use visitor for Object types
        let mut extractor = PropertyExtractor::new(self.interner, name.to_string());
        extractor.extract(expected)
    }

    /// Create a child context for a nested expression.
    /// This is used when checking nested structures with contextual types.
    pub fn for_property(&self, name: &str) -> Self {
        match self.get_property_type(name) {
            Some(ty) => ContextualTypeContext::with_expected(self.interner, ty),
            None => ContextualTypeContext::new(self.interner),
        }
    }

    /// Create a child context for an array element.
    pub fn for_array_element(&self) -> Self {
        match self.get_array_element_type() {
            Some(ty) => ContextualTypeContext::with_expected(self.interner, ty),
            None => ContextualTypeContext::new(self.interner),
        }
    }

    /// Create a child context for a tuple element at the given index.
    pub fn for_tuple_element(&self, index: usize) -> Self {
        match self.get_tuple_element_type(index) {
            Some(ty) => ContextualTypeContext::with_expected(self.interner, ty),
            None => ContextualTypeContext::new(self.interner),
        }
    }

    /// Create a child context for a function parameter at the given index.
    pub fn for_parameter(&self, index: usize) -> Self {
        match self.get_parameter_type(index) {
            Some(ty) => ContextualTypeContext::with_expected(self.interner, ty),
            None => ContextualTypeContext::new(self.interner),
        }
    }

    /// Create a child context for a function return expression.
    pub fn for_return(&self) -> Self {
        match self.get_return_type() {
            Some(ty) => ContextualTypeContext::with_expected(self.interner, ty),
            None => ContextualTypeContext::new(self.interner),
        }
    }

    /// Get the contextual yield type for a generator function.
    ///
    /// If the expected type is `Generator<Y, R, N>`, this returns Y.
    /// This is used to contextually type yield expressions.
    ///
    /// Example:
    /// ```typescript
    /// function* gen(): Generator<number, void, unknown> {
    ///     yield 1;  // 1 is contextually typed as number
    /// }
    /// ```
    pub fn get_generator_yield_type(&self) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect yield types from all members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let yield_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected(self.interner, m);
                    ctx.get_generator_yield_type()
                })
                .collect();

            return collect_single_or_union(self.interner, yield_types);
        }

        // Generator<Y, R, N> — yield type is arg 0
        let mut extractor = ApplicationArgExtractor::new(self.interner, 0);
        extractor.extract(expected)
    }

    /// Get the contextual return type for a generator function (`TReturn` from Generator<Y, `TReturn`, N>).
    ///
    /// This is used to contextually type return statements in generators.
    pub fn get_generator_return_type(&self) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect return types from all members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let return_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected(self.interner, m);
                    ctx.get_generator_return_type()
                })
                .collect();

            return collect_single_or_union(self.interner, return_types);
        }

        // Generator<Y, R, N> — return type is arg 1
        let mut extractor = ApplicationArgExtractor::new(self.interner, 1);
        extractor.extract(expected)
    }

    /// Get the contextual next type for a generator function (`TNext` from Generator<Y, R, `TNext`>).
    ///
    /// This is used to determine the type of values passed to .`next()` and
    /// the type of the yield expression result.
    pub fn get_generator_next_type(&self) -> Option<TypeId> {
        let expected = self.expected?;

        // Handle Union explicitly - collect next types from all members
        if let Some(TypeData::Union(members)) = self.interner.lookup(expected) {
            let members = self.interner.type_list(members);
            let next_types: Vec<TypeId> = members
                .iter()
                .filter_map(|&m| {
                    let ctx = ContextualTypeContext::with_expected(self.interner, m);
                    ctx.get_generator_next_type()
                })
                .collect();

            return collect_single_or_union(self.interner, next_types);
        }

        // Generator<Y, R, N> — next type is arg 2
        let mut extractor = ApplicationArgExtractor::new(self.interner, 2);
        extractor.extract(expected)
    }

    /// Create a child context for a yield expression in a generator.
    pub fn for_yield(&self) -> Self {
        match self.get_generator_yield_type() {
            Some(ty) => ContextualTypeContext::with_expected(self.interner, ty),
            None => ContextualTypeContext::new(self.interner),
        }
    }
}

/// Apply contextual type to infer a more specific type.
///
/// This implements bidirectional type inference:
/// 1. If `expr_type` is any/unknown/error, use contextual type
/// 2. If `expr_type` is a literal and contextual type is a union containing that literal's base type, preserve literal
/// 3. If `expr_type` is assignable to contextual type and is more specific, use `expr_type`
/// 4. Otherwise, prefer `expr_type` (don't widen to contextual type)
pub fn apply_contextual_type(
    interner: &dyn TypeDatabase,
    expr_type: TypeId,
    contextual_type: Option<TypeId>,
) -> TypeId {
    let ctx_type = match contextual_type {
        Some(t) => t,
        None => return expr_type,
    };

    // If expression type is any, unknown, or error, use contextual type
    if expr_type.is_any_or_unknown() || expr_type.is_error() {
        return ctx_type;
    }

    // If expression type is the same, just return it
    if expr_type == ctx_type {
        return expr_type;
    }

    // Check if expr_type is a literal type that should be preserved
    // When contextual type is a union like string | number, we should preserve literal types
    if let Some(expr_key) = interner.lookup(expr_type) {
        // Literal types should be preserved when context is a union
        if matches!(expr_key, TypeData::Literal(_))
            && let Some(ctx_key) = interner.lookup(ctx_type)
            && matches!(ctx_key, TypeData::Union(_))
        {
            // Preserve the literal type - it's more specific than the union
            return expr_type;
        }
    }

    // PERF: Reuse a single SubtypeChecker across all subtype checks in this function
    let mut checker = crate::subtype::SubtypeChecker::new(interner);

    // Check if contextual type is a union
    if let Some(TypeData::Union(members)) = interner.lookup(ctx_type) {
        let members = interner.type_list(members);
        // If expr_type is in the union, it's valid - use the more specific expr_type
        for &member in members.iter() {
            if member == expr_type {
                return expr_type;
            }
        }
        // If expr_type is assignable to any union member, use expr_type
        for &member in members.iter() {
            checker.reset();
            if checker.is_subtype_of(expr_type, member) {
                return expr_type;
            }
        }
    }

    // If expr_type is assignable to contextual type, use expr_type (it's more specific)
    checker.reset();
    if checker.is_subtype_of(expr_type, ctx_type) {
        return expr_type;
    }

    // If contextual type is assignable to expr_type, use contextual type (it's more specific)
    // BUT: Skip for function/callable types — the solver's bivariant SubtypeChecker can
    // incorrectly say that a wider function type (e.g. (x: number|string) => void) is a
    // subtype of a narrower one (e.g. (x: number) => void), which would widen the property
    // type and suppress valid TS2322 errors under strict function types.
    let is_function_type = matches!(
        interner.lookup(expr_type),
        Some(TypeData::Function(_) | TypeData::Object(_))
    );
    if !is_function_type {
        checker.reset();
        if checker.is_subtype_of(ctx_type, expr_type) {
            return ctx_type;
        }
    }

    // Default: prefer the expression type (don't widen to contextual type)
    // This prevents incorrectly widening concrete types to generic type parameters
    expr_type
}

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