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
//! Type Node Checking
//!
//! This module handles type resolution from AST type nodes (type annotations,
//! type references, union types, intersection types, etc.).
//!
//! It follows the "Check Fast, Explain Slow" pattern where we first
//! resolve types, then use the solver to explain any failures.
use crate::context::CheckerContext;
use tsz_parser::parser::NodeIndex;
use tsz_parser::parser::node::NodeAccess;
use tsz_solver::TypeId;
use tsz_solver::Visibility;
use tsz_solver::recursion::{DepthCounter, RecursionProfile};
/// Type node checker that operates on the shared context.
///
/// This is a stateless checker that borrows the context mutably.
/// All type resolution for type nodes goes through this checker.
pub struct TypeNodeChecker<'a, 'ctx> {
pub ctx: &'a mut CheckerContext<'ctx>,
/// Recursion depth counter for stack overflow protection.
depth: DepthCounter,
}
impl<'a, 'ctx> TypeNodeChecker<'a, 'ctx> {
/// Create a new type node checker with a mutable context reference.
pub const fn new(ctx: &'a mut CheckerContext<'ctx>) -> Self {
Self {
ctx,
depth: DepthCounter::with_profile(RecursionProfile::TypeNodeCheck),
}
}
/// Check a type node and return its type.
///
/// This is the main entry point for type node resolution.
/// It handles caching and dispatches to specific type node handlers.
pub fn check(&mut self, idx: NodeIndex) -> TypeId {
// Stack overflow protection
if !self.depth.enter() {
return TypeId::ERROR;
}
// Check cache first
if let Some(&cached) = self.ctx.node_types.get(&idx.0) {
if cached == TypeId::ERROR {
// Always use cached ERROR to prevent duplicate emissions
self.depth.leave();
return cached;
}
// For non-ERROR cached results, check if we're in a generic context
// If we're not in a generic context (type params are empty), the cache is valid
if self.ctx.type_parameter_scope.is_empty() {
// No type parameters in scope - cache is valid
self.depth.leave();
return cached;
}
// If we have type parameters in scope, we need to be more careful
// For now, recompute to ensure correctness
// TODO: Add cache key based on type param hash for smarter caching
}
// Compute and cache
let result = self.compute_type(idx);
// Don't cache TYPE_REFERENCE results here — CheckerState's
// get_type_from_type_node has its own TYPE_REFERENCE handler that
// calls get_type_from_type_reference() which emits diagnostics
// (TS2314, TS2304, etc.). If we cache here, the checker's handler
// finds the cached result and skips the diagnostic-emitting path.
let is_type_ref = self
.ctx
.arena
.get(idx)
.is_some_and(|n| n.kind == tsz_parser::parser::syntax_kind_ext::TYPE_REFERENCE);
if !is_type_ref {
self.ctx.node_types.insert(idx.0, result);
}
self.depth.leave();
result
}
/// Compute the type of a type node (internal, not cached).
fn compute_type(&mut self, idx: NodeIndex) -> TypeId {
use tsz_parser::parser::syntax_kind_ext;
use tsz_scanner::SyntaxKind;
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
match node.kind {
// Keyword types - use compile-time constant TypeIds
k if k == SyntaxKind::NumberKeyword as u16 => TypeId::NUMBER,
k if k == SyntaxKind::StringKeyword as u16 => TypeId::STRING,
k if k == SyntaxKind::BooleanKeyword as u16 => TypeId::BOOLEAN,
k if k == SyntaxKind::VoidKeyword as u16 => TypeId::VOID,
k if k == SyntaxKind::AnyKeyword as u16 => TypeId::ANY,
k if k == SyntaxKind::NeverKeyword as u16 => TypeId::NEVER,
k if k == SyntaxKind::UnknownKeyword as u16 => TypeId::UNKNOWN,
k if k == SyntaxKind::UndefinedKeyword as u16 => TypeId::UNDEFINED,
k if k == SyntaxKind::NullKeyword as u16 => TypeId::NULL,
k if k == SyntaxKind::ObjectKeyword as u16 => TypeId::OBJECT,
k if k == SyntaxKind::BigIntKeyword as u16 => TypeId::BIGINT,
k if k == SyntaxKind::SymbolKeyword as u16 => TypeId::SYMBOL,
// Type reference (e.g., "MyType", "Array<T>")
k if k == syntax_kind_ext::TYPE_REFERENCE => self.get_type_from_type_reference(idx),
// Union type (A | B)
k if k == syntax_kind_ext::UNION_TYPE => self.get_type_from_union_type(idx),
// Intersection type (A & B)
k if k == syntax_kind_ext::INTERSECTION_TYPE => {
self.get_type_from_intersection_type(idx)
}
// Array type (T[])
k if k == syntax_kind_ext::ARRAY_TYPE => self.get_type_from_array_type(idx),
// Tuple type ([T, U, ...V[]])
k if k == syntax_kind_ext::TUPLE_TYPE => self.get_type_from_tuple_type(idx),
// Type operator (readonly, unique, keyof)
k if k == syntax_kind_ext::TYPE_OPERATOR => self.get_type_from_type_operator(idx),
// Indexed access type (T[K], Person["name"])
k if k == syntax_kind_ext::INDEXED_ACCESS_TYPE => {
self.get_type_from_indexed_access_type(idx)
}
// Function type (e.g., () => number, (x: string) => void)
k if k == syntax_kind_ext::FUNCTION_TYPE => self.get_type_from_function_type(idx),
// Constructor type (e.g., new () => number, new (x: string) => any)
k if k == syntax_kind_ext::CONSTRUCTOR_TYPE => self.get_type_from_function_type(idx),
// Type literal ({ a: number; b(): string; })
k if k == syntax_kind_ext::TYPE_LITERAL => self.get_type_from_type_literal(idx),
// Type query (typeof X) - returns the type of X
k if k == syntax_kind_ext::TYPE_QUERY => self.get_type_from_type_query(idx),
// Mapped type ({ [P in K]: T })
// Check for TS7039 before TypeLowering since TypeLowering doesn't emit diagnostics
k if k == syntax_kind_ext::MAPPED_TYPE => self.get_type_from_mapped_type(idx),
k if k == syntax_kind_ext::THIS_TYPE
|| k == tsz_scanner::SyntaxKind::ThisKeyword as u16 =>
{
if !self.is_this_type_allowed(idx) {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages};
self.ctx.error(
node.pos,
node.end.saturating_sub(node.pos),
diagnostic_messages::A_THIS_TYPE_IS_AVAILABLE_ONLY_IN_A_NON_STATIC_MEMBER_OF_A_CLASS_OR_INTERFACE.to_string(),
diagnostic_codes::A_THIS_TYPE_IS_AVAILABLE_ONLY_IN_A_NON_STATIC_MEMBER_OF_A_CLASS_OR_INTERFACE,
);
TypeId::ERROR
} else {
self.ctx.types.this_type()
}
}
// Fall back to TypeLowering for type nodes not handled above
// (conditional types, indexed access types, etc.)
_ => self.lower_with_resolvers(idx, true, true),
}
}
// =========================================================================
// Type Reference Resolution
// =========================================================================
/// Get type from a type reference node (e.g., "number", "string", "`MyType`").
fn get_type_from_type_reference(&mut self, idx: NodeIndex) -> TypeId {
self.lower_with_resolvers(idx, false, false)
}
// =========================================================================
// Composite Type Resolution
// =========================================================================
/// Get type from a union type node (A | B).
///
/// Parses a union type expression and creates a Union type with all members.
///
/// ## Type Normalization:
/// - Empty union -> NEVER (the empty type)
/// - Single member -> the member itself (no union wrapper)
/// - Multiple members -> Union type with all members
fn get_type_from_union_type(&mut self, idx: NodeIndex) -> TypeId {
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
// UnionType uses CompositeTypeData which has a types list
if let Some(composite) = self.ctx.arena.get_composite_type(node) {
let mut member_types = Vec::new();
for &type_idx in &composite.types.nodes {
// Recursively resolve each member type
member_types.push(self.check(type_idx));
}
if member_types.is_empty() {
return TypeId::NEVER;
}
return tsz_solver::utils::union_or_single(self.ctx.types, member_types);
}
TypeId::ERROR
}
/// Get type from an intersection type node (A & B).
///
/// Parses an intersection type expression and creates an Intersection type with all members.
///
/// ## Type Normalization:
/// - Empty intersection -> UNKNOWN (the top type for intersections)
/// - Single member -> the member itself (no intersection wrapper)
/// - Multiple members -> Intersection type with all members
fn get_type_from_intersection_type(&mut self, idx: NodeIndex) -> TypeId {
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
// IntersectionType uses CompositeTypeData which has a types list
if let Some(composite) = self.ctx.arena.get_composite_type(node) {
let mut member_types = Vec::new();
for &type_idx in &composite.types.nodes {
// Recursively resolve each member type
member_types.push(self.check(type_idx));
}
if member_types.is_empty() {
return TypeId::UNKNOWN; // Empty intersection is unknown
}
return tsz_solver::utils::intersection_or_single(self.ctx.types, member_types);
}
TypeId::ERROR
}
/// Get type from an array type node (string[]).
///
/// Parses an array type expression and creates an Array type.
fn get_type_from_array_type(&mut self, idx: NodeIndex) -> TypeId {
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
let factory = self.ctx.types.factory();
if let Some(array_type) = self.ctx.arena.get_array_type(node) {
let elem_type = self.check(array_type.element_type);
return factory.array(elem_type);
}
TypeId::ERROR
}
/// Get type from a tuple type node ([T, U, ...V[]]).
///
/// Parses a tuple type expression and creates a Tuple type with proper handling of:
/// - Regular elements (e.g., `[number, string]`)
/// - Optional elements (e.g., `[number, string?]`)
/// - Rest elements (e.g., `[number, ...string[]]`)
/// - Named elements (e.g., `[x: number, y: string]`)
fn get_type_from_tuple_type(&mut self, idx: NodeIndex) -> TypeId {
use tsz_solver::TupleElement;
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
let factory = self.ctx.types.factory();
if let Some(tuple_type) = self.ctx.arena.get_tuple_type(node) {
let mut elements = Vec::new();
let mut seen_optional = false;
for &elem_idx in &tuple_type.elements.nodes {
if elem_idx.is_none() {
continue;
}
let Some(elem_node) = self.ctx.arena.get(elem_idx) else {
continue;
};
// Check if this is an optional/rest type or a regular type
use tsz_parser::parser::syntax_kind_ext;
if elem_node.kind == syntax_kind_ext::OPTIONAL_TYPE {
// Optional element (e.g., `string?`)
seen_optional = true;
if let Some(wrapped) = self.ctx.arena.get_wrapped_type(elem_node) {
let elem_type = self.check(wrapped.type_node);
elements.push(TupleElement {
type_id: elem_type,
name: None,
optional: true,
rest: false,
});
}
} else if elem_node.kind == syntax_kind_ext::REST_TYPE {
// Rest element (e.g., `...string[]`)
// Rest elements can come after optional elements, so we don't error
if let Some(wrapped) = self.ctx.arena.get_wrapped_type(elem_node) {
let elem_type = self.check(wrapped.type_node);
elements.push(TupleElement {
type_id: elem_type,
name: None,
optional: false,
rest: true,
});
}
} else {
// Regular element
// TS1257: A required element cannot follow an optional element
if seen_optional {
self.ctx.error(
elem_node.pos,
elem_node.end - elem_node.pos,
crate::diagnostics::diagnostic_messages::A_REQUIRED_ELEMENT_CANNOT_FOLLOW_AN_OPTIONAL_ELEMENT.to_string(),
crate::diagnostics::diagnostic_codes::A_REQUIRED_ELEMENT_CANNOT_FOLLOW_AN_OPTIONAL_ELEMENT,
);
}
let elem_type = self.check(elem_idx);
elements.push(TupleElement {
type_id: elem_type,
name: None,
optional: false,
rest: false,
});
}
}
return factory.tuple(elements);
}
TypeId::ERROR
}
// =========================================================================
// Type Operators
// =========================================================================
/// Get type from a type operator node (readonly T[], readonly [T, U], unique symbol).
///
/// Handles type modifiers like:
/// - `readonly T[]` - Creates `ReadonlyType` wrapper
/// - `unique symbol` - Special marker for unique symbols
fn get_type_from_type_operator(&mut self, idx: NodeIndex) -> TypeId {
use tsz_scanner::SyntaxKind;
let factory = self.ctx.types.factory();
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
if let Some(type_op) = self.ctx.arena.get_type_operator(node) {
let operator = type_op.operator;
let inner_type = self.check(type_op.type_node);
// Handle readonly operator
if operator == SyntaxKind::ReadonlyKeyword as u16 {
return factory.readonly_type(inner_type);
}
// Handle keyof operator
if operator == SyntaxKind::KeyOfKeyword as u16 {
return factory.keyof(inner_type);
}
// Handle unique operator
if operator == SyntaxKind::UniqueKeyword as u16 {
// unique is handled differently - it's a type modifier for symbols
// For now, just return the inner type
return inner_type;
}
// Unknown operator - return inner type
inner_type
} else {
TypeId::ERROR
}
}
// =========================================================================
// Indexed Access Types
// =========================================================================
/// Handle indexed access type nodes (e.g., `Person["name"]`, `T[K]`).
fn get_type_from_indexed_access_type(&mut self, idx: NodeIndex) -> TypeId {
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
let factory = self.ctx.types.factory();
if let Some(indexed_access) = self.ctx.arena.get_indexed_access_type(node) {
let object_type = self.check(indexed_access.object_type);
let index_type = self.check(indexed_access.index_type);
// TS2538: Check if the index type is valid (string, number, symbol, or literal thereof)
if let Some(invalid_member) = self.get_invalid_index_type_member(index_type)
&& let Some(inode) = self.ctx.arena.get(indexed_access.index_type)
{
let mut formatter = self.ctx.create_type_formatter();
let index_type_str = formatter.format(invalid_member);
let message = crate::diagnostics::format_message(
crate::diagnostics::diagnostic_messages::TYPE_CANNOT_BE_USED_AS_AN_INDEX_TYPE,
&[&index_type_str],
);
self.ctx
.error(inode.pos, inode.end - inode.pos, message, 2538);
}
factory.index_access(object_type, index_type)
} else {
TypeId::ERROR
}
}
/// Get the specific type that makes this type invalid as an index type (TS2538).
fn get_invalid_index_type_member(&self, type_id: TypeId) -> Option<TypeId> {
tsz_solver::type_queries::get_invalid_index_type_member(self.ctx.types, type_id)
}
// =========================================================================
// Function and Callable Types
// =========================================================================
/// Get type from a function type node (e.g., () => number, (x: string) => void).
fn get_type_from_function_type(&mut self, idx: NodeIndex) -> TypeId {
let Some(_node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
let Some(func_data) = self.ctx.arena.get_function_type(_node) else {
return TypeId::ERROR;
};
// EXPLICIT VALIDATION: Check type references in parameters and return type for TS2304.
// We must do this before TypeLowering because TypeLowering doesn't emit diagnostics.
// This ensures errors like "Cannot find name 'C'" are emitted for: (x: T) => C
check_duplicate_parameters_in_type(self.ctx, &func_data.parameters);
check_parameter_initializers_in_type(self.ctx, &func_data.parameters);
use tsz_parser::parser::syntax_kind_ext;
// Collect type parameter names from this function type (e.g., <T> in <T>(x: T) => T)
let mut local_type_params: std::collections::HashSet<String> =
std::collections::HashSet::new();
if let Some(ref type_params) = func_data.type_parameters {
for &tp_idx in &type_params.nodes {
if let Some(tp_node) = self.ctx.arena.get(tp_idx)
&& let Some(tp_data) = self.ctx.arena.get_type_parameter(tp_node)
&& let Some(name_node) = self.ctx.arena.get(tp_data.name)
&& let Some(ident) = self.ctx.arena.get_identifier(name_node)
{
local_type_params.insert(ident.escaped_text.clone());
}
}
}
// Helper to check if a type name is a built-in TypeScript type
let is_builtin_type = |name: &str| -> bool {
matches!(
name,
// Primitive types
"void" | "null" | "undefined" | "any" | "unknown" | "never" |
"number" | "bigint" | "boolean" | "string" | "symbol" | "object" |
// Special types
"Function" | "Object" | "String" | "Number" | "Boolean" | "Symbol" |
// Compiler-managed
"Array" | "ReadonlyArray" | "Uppercase" | "Lowercase" | "Capitalize" | "Uncapitalize"
)
};
// Collect undefined type names first (to avoid borrow checker issues)
let mut undefined_types: Vec<(NodeIndex, String)> = Vec::new();
let mut renamed_binding_aliases: std::collections::HashSet<String> =
std::collections::HashSet::new();
for ¶m_idx in &func_data.parameters.nodes {
let mut stack = vec![param_idx];
while let Some(node_idx) = stack.pop() {
let Some(binding_node) = self.ctx.arena.get(node_idx) else {
continue;
};
if binding_node.kind == syntax_kind_ext::BINDING_ELEMENT
&& let Some(binding) = self.ctx.arena.get_binding_element(binding_node)
&& binding.property_name.is_some()
&& binding.name.is_some()
&& let Some(alias_name) = self.ctx.arena.get_identifier_text(binding.name)
{
renamed_binding_aliases.insert(alias_name.to_string());
}
stack.extend(self.ctx.arena.get_children(node_idx));
}
}
// Helper: check if a type name is resolvable in any scope (file locals,
// lib contexts, enclosing namespace scopes via binder identifier resolution).
let is_name_resolvable =
|ctx: &CheckerContext, name: &str, name_node_idx: NodeIndex| -> bool {
// Check file-level declarations
if ctx.binder.file_locals.get(name).is_some() {
return true;
}
// Check lib declarations
if ctx
.lib_contexts
.iter()
.any(|lib_ctx| lib_ctx.binder.file_locals.get(name).is_some())
{
return true;
}
// Check scope-based resolution (handles namespace-scoped names)
if ctx
.binder
.resolve_identifier(ctx.arena, name_node_idx)
.is_some()
{
return true;
}
false
};
// Check return type annotation
if func_data.type_annotation.is_some()
&& let Some(tn) = self.ctx.arena.get(func_data.type_annotation)
&& tn.kind == syntax_kind_ext::TYPE_REFERENCE
&& let Some(tr) = self.ctx.arena.get_type_ref(tn)
&& let Some(name_node) = self.ctx.arena.get(tr.type_name)
&& let Some(ident) = self.ctx.arena.get_identifier(name_node)
{
let name = &ident.escaped_text;
let is_builtin = is_builtin_type(name);
let is_local_type_param = local_type_params.contains(name);
let is_type_param = self.ctx.type_parameter_scope.contains_key(name);
let in_scope = is_name_resolvable(self.ctx, name, tr.type_name);
if !is_builtin && !is_local_type_param && !is_type_param && !in_scope {
undefined_types.push((tr.type_name, name.clone()));
}
}
// Check parameter type annotations
for param_idx in &func_data.parameters.nodes {
if let Some(param_node) = self.ctx.arena.get(*param_idx)
&& let Some(param_data) = self.ctx.arena.get_parameter(param_node)
&& param_data.type_annotation.is_some()
&& let Some(tn) = self.ctx.arena.get(param_data.type_annotation)
&& tn.kind == syntax_kind_ext::TYPE_REFERENCE
&& let Some(tr) = self.ctx.arena.get_type_ref(tn)
&& let Some(name_node) = self.ctx.arena.get(tr.type_name)
&& let Some(ident) = self.ctx.arena.get_identifier(name_node)
{
let name = &ident.escaped_text;
let is_builtin = is_builtin_type(name);
let is_local_type_param = local_type_params.contains(name);
let is_type_param = self.ctx.type_parameter_scope.contains_key(name);
let in_scope = is_name_resolvable(self.ctx, name, tr.type_name);
if !is_builtin && !is_local_type_param && !is_type_param && !in_scope {
undefined_types.push((tr.type_name, name.clone()));
}
}
}
// Now emit all the TS2304 errors
for (error_idx, name) in undefined_types {
if renamed_binding_aliases.contains(&name) {
continue;
}
if let Some(node) = self.ctx.arena.get(error_idx) {
let message = format!("Cannot find name '{name}'.");
self.ctx.error(node.pos, node.end - node.pos, message, 2304);
}
}
// Delegate to TypeLowering with standard resolvers
self.lower_with_resolvers(idx, false, false)
}
/// Get type from a type literal node ({ a: number; `b()`: string; }).
fn get_type_from_type_literal(&mut self, idx: NodeIndex) -> TypeId {
use tsz_parser::parser::syntax_kind_ext::{
CALL_SIGNATURE, CONSTRUCT_SIGNATURE, METHOD_SIGNATURE, PROPERTY_SIGNATURE,
};
use tsz_solver::{
CallSignature, CallableShape, FunctionShape, IndexSignature, ObjectFlags, ObjectShape,
PropertyInfo,
};
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
let Some(data) = self.ctx.arena.get_type_literal(node) else {
return TypeId::ERROR;
};
let mut properties = Vec::new();
let mut call_signatures = Vec::new();
let mut construct_signatures = Vec::new();
let mut string_index = None;
let mut number_index = None;
for &member_idx in &data.members.nodes {
let Some(member) = self.ctx.arena.get(member_idx) else {
continue;
};
if let Some(sig) = self.ctx.arena.get_signature(member) {
match member.kind {
CALL_SIGNATURE => {
let (params, this_type) = self.extract_params_from_signature(sig);
let return_type = self
.resolve_return_type_with_params_in_scope(sig.type_annotation, ¶ms);
call_signatures.push(CallSignature {
type_params: Vec::new(),
params,
this_type,
return_type,
type_predicate: None,
is_method: false,
});
}
CONSTRUCT_SIGNATURE => {
let (params, this_type) = self.extract_params_from_signature(sig);
let return_type = self
.resolve_return_type_with_params_in_scope(sig.type_annotation, ¶ms);
construct_signatures.push(CallSignature {
type_params: Vec::new(),
params,
this_type,
return_type,
type_predicate: None,
is_method: false,
});
}
METHOD_SIGNATURE | PROPERTY_SIGNATURE => {
let Some(name) = self.get_property_name(sig.name) else {
continue;
};
let name_atom = self.ctx.types.intern_string(&name);
if member.kind == METHOD_SIGNATURE {
let (params, this_type) = self.extract_params_from_signature(sig);
let return_type = self.resolve_return_type_with_params_in_scope(
sig.type_annotation,
¶ms,
);
let shape = FunctionShape {
type_params: Vec::new(),
params,
this_type,
return_type,
type_predicate: None,
is_constructor: false,
is_method: true,
};
let factory = self.ctx.types.factory();
let method_type = factory.function(shape);
properties.push(PropertyInfo {
name: name_atom,
type_id: method_type,
write_type: method_type,
optional: sig.question_token,
readonly: self.has_readonly_modifier(&sig.modifiers),
is_method: true,
visibility: Visibility::Public,
parent_id: None,
});
} else {
let type_id = if sig.type_annotation.is_some() {
self.check(sig.type_annotation)
} else {
TypeId::ANY
};
properties.push(PropertyInfo {
name: name_atom,
type_id,
write_type: type_id,
optional: sig.question_token,
readonly: self.has_readonly_modifier(&sig.modifiers),
is_method: false,
visibility: Visibility::Public,
parent_id: None,
});
}
}
_ => {}
}
continue;
}
if let Some(index_sig) = self.ctx.arena.get_index_signature(member) {
let param_idx = index_sig
.parameters
.nodes
.first()
.copied()
.unwrap_or(NodeIndex::NONE);
let Some(param_node) = self.ctx.arena.get(param_idx) else {
continue;
};
let Some(param_data) = self.ctx.arena.get_parameter(param_node) else {
continue;
};
let key_type = if param_data.type_annotation.is_some() {
self.check(param_data.type_annotation)
} else {
TypeId::ANY
};
// TS1268: An index signature parameter type must be 'string', 'number',
// 'symbol', or a template literal type.
// Suppress when the parameter already has grammar errors (rest/optional) — matches tsc.
let has_param_grammar_error =
param_data.dot_dot_dot_token || param_data.question_token;
let is_valid_index_type = key_type == TypeId::STRING
|| key_type == TypeId::NUMBER
|| key_type == TypeId::SYMBOL
|| tsz_solver::visitor::is_template_literal_type(self.ctx.types, key_type);
if !is_valid_index_type
&& !has_param_grammar_error
&& let Some(pnode) = self.ctx.arena.get(param_idx)
{
self.ctx.error(
pnode.pos,
pnode.end - pnode.pos,
"An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type.".to_string(),
1268,
);
}
let value_type = if index_sig.type_annotation.is_some() {
self.check(index_sig.type_annotation)
} else {
TypeId::ANY
};
let readonly = self.has_readonly_modifier(&index_sig.modifiers);
let info = IndexSignature {
key_type,
value_type,
readonly,
};
if key_type == TypeId::NUMBER {
number_index = Some(info);
} else {
string_index = Some(info);
}
continue;
}
// Handle accessor declarations (get/set) in type literals
if (member.kind == tsz_parser::parser::syntax_kind_ext::GET_ACCESSOR
|| member.kind == tsz_parser::parser::syntax_kind_ext::SET_ACCESSOR)
&& let Some(accessor) = self.ctx.arena.get_accessor(member)
&& let Some(name) = self.get_property_name(accessor.name)
{
let name_atom = self.ctx.types.intern_string(&name);
let is_getter = member.kind == tsz_parser::parser::syntax_kind_ext::GET_ACCESSOR;
if is_getter {
let getter_type = if accessor.type_annotation.is_some() {
self.check(accessor.type_annotation)
} else {
TypeId::ANY
};
if let Some(existing) = properties.iter_mut().find(|p| p.name == name_atom) {
existing.type_id = getter_type;
} else {
properties.push(PropertyInfo {
name: name_atom,
type_id: getter_type,
write_type: getter_type,
optional: false,
readonly: false,
is_method: false,
visibility: Visibility::Public,
parent_id: None,
});
}
} else {
let setter_type = accessor
.parameters
.nodes
.first()
.and_then(|¶m_idx| self.ctx.arena.get(param_idx))
.and_then(|param_node| self.ctx.arena.get_parameter(param_node))
.and_then(|param| {
(param.type_annotation.is_some())
.then(|| self.check(param.type_annotation))
})
.unwrap_or(TypeId::UNKNOWN);
if let Some(existing) = properties.iter_mut().find(|p| p.name == name_atom) {
existing.write_type = setter_type;
existing.readonly = false;
} else {
properties.push(PropertyInfo {
name: name_atom,
type_id: setter_type,
write_type: setter_type,
optional: false,
readonly: false,
is_method: false,
visibility: Visibility::Public,
parent_id: None,
});
}
}
}
}
if !call_signatures.is_empty() || !construct_signatures.is_empty() {
let factory = self.ctx.types.factory();
return factory.callable(CallableShape {
call_signatures,
construct_signatures,
properties,
string_index,
number_index,
symbol: None,
});
}
if string_index.is_some() || number_index.is_some() {
let factory = self.ctx.types.factory();
return factory.object_with_index(ObjectShape {
flags: ObjectFlags::empty(),
properties,
string_index,
number_index,
symbol: None,
});
}
let factory = self.ctx.types.factory();
factory.object(properties)
}
// =========================================================================
// Type Query (typeof)
// =========================================================================
/// Get type from a type query node (typeof X).
///
/// Creates a `TypeQuery` type that captures the type of a value.
fn get_type_from_type_query(&mut self, idx: NodeIndex) -> TypeId {
use tsz_lowering::TypeLowering;
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
let Some(type_query) = self.ctx.arena.get_type_query(node) else {
return TypeId::ERROR;
};
// Prefer the already-computed value-space type at this query site when available.
// This preserves flow-sensitive narrowing for `typeof expr` in type positions.
if let Some(&expr_type) = self.ctx.node_types.get(&type_query.expr_name.0)
&& expr_type != TypeId::ERROR
{
return expr_type;
}
let name_opt = if let Some(expr_node) = self.ctx.arena.get(type_query.expr_name) {
if expr_node.kind == tsz_scanner::SyntaxKind::Identifier as u16 {
self.ctx
.arena
.get_identifier(expr_node)
.map(|id| id.escaped_text.as_str())
} else {
None
}
} else {
None
};
if name_opt == Some("default") {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages, format_message};
let msg = format_message(diagnostic_messages::CANNOT_FIND_NAME, &["default"]);
self.ctx.error(
self.ctx.arena.get(type_query.expr_name).unwrap().pos,
self.ctx.arena.get(type_query.expr_name).unwrap().end
- self.ctx.arena.get(type_query.expr_name).unwrap().pos,
msg,
diagnostic_codes::CANNOT_FIND_NAME,
);
return TypeId::ERROR;
}
// Check typeof_param_scope — resolves `typeof paramName` in return type
// annotations where the parameter isn't a file-level binding.
if let Some(expr_node) = self.ctx.arena.get(type_query.expr_name)
&& expr_node.kind == tsz_scanner::SyntaxKind::Identifier as u16
&& let Some(ident) = self.ctx.arena.get_identifier(expr_node)
&& let Some(¶m_type) = self.ctx.typeof_param_scope.get(ident.escaped_text.as_str())
{
return param_type;
}
// For qualified names (e.g., typeof M.F2), resolve the symbol through
// the binder's export tables. Simple identifiers are already handled by
// the node_types cache above, but qualified names need member resolution.
if let Some(sym_id) = self.resolve_type_query_symbol(type_query.expr_name) {
let factory = self.ctx.types.factory();
return factory.type_query(tsz_solver::SymbolRef(sym_id.0));
}
// Fall back to TypeLowering with proper value resolvers
let value_resolver = |node_idx: NodeIndex| -> Option<u32> {
let ident = self.ctx.arena.get_identifier_at(node_idx)?;
let name = ident.escaped_text.as_str();
if name == "default" {
return None;
}
let sym_id = self.ctx.binder.file_locals.get(name)?;
Some(sym_id.0)
};
let type_resolver = |_node_idx: NodeIndex| -> Option<u32> { None };
let lowering = TypeLowering::with_resolvers(
self.ctx.arena,
self.ctx.types,
&type_resolver,
&value_resolver,
);
lowering.lower_type(idx)
}
/// Resolve the symbol for a type query expression name.
///
/// Handles both simple identifiers and qualified names (e.g., `M.F2`).
/// For qualified names, walks through namespace exports to find the member.
fn resolve_type_query_symbol(&self, expr_name: NodeIndex) -> Option<tsz_binder::SymbolId> {
use tsz_parser::parser::syntax_kind_ext;
let node = self.ctx.arena.get(expr_name)?;
if node.kind == tsz_scanner::SyntaxKind::Identifier as u16 {
let ident = self.ctx.arena.get_identifier(node)?;
let name = ident.escaped_text.as_str();
if name == "default" {
return None;
}
let sym_id = self.ctx.binder.file_locals.get(name)?;
return Some(sym_id);
}
if node.kind == syntax_kind_ext::QUALIFIED_NAME {
let qn = self.ctx.arena.get_qualified_name(node)?;
// Recursively resolve the left side
let left_sym = self.resolve_type_query_symbol(qn.left)?;
// Get the right name
let right_node = self.ctx.arena.get(qn.right)?;
let right_ident = self.ctx.arena.get_identifier(right_node)?;
let right_name = right_ident.escaped_text.as_str();
// Look through binder + libs for the left symbol's exports
let lib_binders: Vec<std::sync::Arc<tsz_binder::BinderState>> = self
.ctx
.lib_contexts
.iter()
.map(|lc| std::sync::Arc::clone(&lc.binder))
.collect();
let left_symbol = self
.ctx
.binder
.get_symbol_with_libs(left_sym, &lib_binders)?;
if let Some(exports) = left_symbol.exports.as_ref()
&& let Some(member_sym) = exports.get(right_name)
{
return Some(member_sym);
}
}
None
}
/// Check a mapped type ({ [P in K]: T }).
///
/// This function validates the mapped type and emits TS7039 if the type expression
/// after the colon is missing (e.g., `{[P in "bar"]}` instead of `{[P in "bar"]: string}`).
fn get_type_from_mapped_type(&mut self, idx: NodeIndex) -> TypeId {
use tsz_parser::parser::NodeIndex as ParserNodeIndex;
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
let Some(data) = self.ctx.arena.get_mapped_type(node) else {
return TypeId::ERROR;
};
// TS7039: Mapped object type implicitly has an 'any' template type.
// This error occurs when the type expression after the colon is missing.
// Example: type Foo = {[P in "bar"]}; // Missing ": T" after "bar"]
if data.type_node == ParserNodeIndex::NONE {
let message = "Mapped object type implicitly has an 'any' template type.";
self.ctx
.error(node.pos, node.end - node.pos, message.to_string(), 7039);
return TypeId::ANY;
}
// Delegate to TypeLowering with extended resolvers (enum flags + lib search)
self.lower_with_resolvers(idx, true, false)
}
// =========================================================================
// Symbol Resolution Helpers
// =========================================================================
/// Resolve a type symbol from a node index.
///
/// Looks up the identifier in `file_locals` and `lib_contexts` for symbols with
/// TYPE, `REGULAR_ENUM`, or `CONST_ENUM` flags. Returns the raw symbol ID (u32).
/// Skips compiler-managed types (Array, ReadonlyArray, etc.) that `TypeLowering`
/// handles specially.
fn resolve_type_symbol(&self, node_idx: NodeIndex) -> Option<u32> {
use tsz_binder::symbol_flags;
use tsz_solver::is_compiler_managed_type;
let ident = self.ctx.arena.get_identifier_at(node_idx)?;
let name = ident.escaped_text.as_str();
if is_compiler_managed_type(name) {
return None;
}
if let Some(sym_id) = self.ctx.binder.file_locals.get(name) {
let symbol = self.ctx.binder.get_symbol(sym_id)?;
if (symbol.flags
& (symbol_flags::TYPE | symbol_flags::REGULAR_ENUM | symbol_flags::CONST_ENUM))
!= 0
{
return Some(sym_id.0);
}
}
for lib_ctx in &self.ctx.lib_contexts {
if let Some(lib_sym_id) = lib_ctx.binder.file_locals.get(name) {
let symbol = lib_ctx.binder.get_symbol(lib_sym_id)?;
if (symbol.flags
& (symbol_flags::TYPE | symbol_flags::REGULAR_ENUM | symbol_flags::CONST_ENUM))
!= 0
{
let file_sym_id = self.ctx.binder.file_locals.get(name).unwrap_or(lib_sym_id);
return Some(file_sym_id.0);
}
}
}
None
}
/// Resolve a value symbol from a node index (`file_locals` only).
///
/// Looks for symbols with VALUE or ALIAS flags. Used by `type_reference` and
/// `function_type` resolvers.
fn resolve_value_symbol(&self, node_idx: NodeIndex) -> Option<u32> {
use tsz_binder::symbol_flags;
let ident = self.ctx.arena.get_identifier_at(node_idx)?;
let name = ident.escaped_text.as_str();
if let Some(sym_id) = self.ctx.binder.file_locals.get(name) {
let symbol = self.ctx.binder.get_symbol(sym_id)?;
if (symbol.flags & (symbol_flags::VALUE | symbol_flags::ALIAS)) != 0 {
return Some(sym_id.0);
}
}
None
}
/// Resolve a value symbol from a node index (`file_locals` + libs, with enum flags).
///
/// Extended variant used by `compute_type` fallback and `mapped_type` resolvers
/// that also checks `lib_contexts` and includes `REGULAR_ENUM/CONST_ENUM` flags.
fn resolve_value_symbol_with_libs(&self, node_idx: NodeIndex) -> Option<u32> {
use tsz_binder::symbol_flags;
let ident = self.ctx.arena.get_identifier_at(node_idx)?;
let name = ident.escaped_text.as_str();
if let Some(sym_id) = self.ctx.binder.file_locals.get(name)
&& let Some(symbol) = self.ctx.binder.get_symbol(sym_id)
&& (symbol.flags
& (symbol_flags::VALUE
| symbol_flags::ALIAS
| symbol_flags::REGULAR_ENUM
| symbol_flags::CONST_ENUM))
!= 0
{
return Some(sym_id.0);
}
for lib_ctx in &self.ctx.lib_contexts {
if let Some(lib_sym_id) = lib_ctx.binder.file_locals.get(name)
&& let Some(symbol) = lib_ctx.binder.get_symbol(lib_sym_id)
&& (symbol.flags
& (symbol_flags::VALUE
| symbol_flags::ALIAS
| symbol_flags::REGULAR_ENUM
| symbol_flags::CONST_ENUM))
!= 0
{
let file_sym_id = self.ctx.binder.file_locals.get(name).unwrap_or(lib_sym_id);
return Some(file_sym_id.0);
}
}
None
}
/// Resolve a DefId from a node index via the type resolver.
fn resolve_def_id(&self, node_idx: NodeIndex) -> Option<tsz_solver::def::DefId> {
let sym_id = self.resolve_type_symbol(node_idx)?;
Some(self.ctx.get_or_create_def_id(tsz_binder::SymbolId(sym_id)))
}
/// Resolve a DefId with support for qualified names (e.g., `AnimalType.cat`).
///
/// Used by the `compute_type` fallback path where template literal types may
/// reference enum members via qualified names inside `${...}`.
fn resolve_def_id_with_qualified_names(
&self,
node_idx: NodeIndex,
) -> Option<tsz_solver::def::DefId> {
use tsz_parser::parser::syntax_kind_ext;
if let Some(sym_id) = self.resolve_type_symbol(node_idx) {
return Some(self.ctx.get_or_create_def_id(tsz_binder::SymbolId(sym_id)));
}
let node = self.ctx.arena.get(node_idx)?;
if node.kind == syntax_kind_ext::QUALIFIED_NAME {
let qn = self.ctx.arena.get_qualified_name(node)?;
let left_sym_raw = self.resolve_type_symbol(qn.left)?;
let left_sym_id = tsz_binder::SymbolId(left_sym_raw);
let left_symbol = self.ctx.binder.get_symbol(left_sym_id)?;
let right_node = self.ctx.arena.get(qn.right)?;
let right_ident = self.ctx.arena.get_identifier(right_node)?;
let right_name = right_ident.escaped_text.as_str();
let member_sym_id = left_symbol.exports.as_ref()?.get(right_name)?;
return Some(self.ctx.get_or_create_def_id(member_sym_id));
}
None
}
/// Collect type parameter bindings from the current scope.
fn collect_type_param_bindings(&self) -> Vec<(tsz_common::interner::Atom, TypeId)> {
self.ctx
.type_parameter_scope
.iter()
.map(|(name, &type_id)| (self.ctx.types.intern_string(name), type_id))
.collect()
}
/// Run `TypeLowering` with the standard resolvers (type + value + `def_id`).
///
/// This is the common path used by `compute_type` fallback, `type_reference`,
/// `function_type`, and `mapped_type`. The `use_extended_value_resolver` flag
/// controls whether enum flags and lib search are included in value resolution.
/// The `use_qualified_names` flag enables qualified name support in `def_id` resolution.
fn lower_with_resolvers(
&self,
idx: NodeIndex,
use_extended_value_resolver: bool,
use_qualified_names: bool,
) -> TypeId {
use tsz_lowering::TypeLowering;
let type_param_bindings = self.collect_type_param_bindings();
let type_resolver =
|node_idx: NodeIndex| -> Option<u32> { self.resolve_type_symbol(node_idx) };
let value_resolver = |node_idx: NodeIndex| -> Option<u32> {
if use_extended_value_resolver {
self.resolve_value_symbol_with_libs(node_idx)
} else {
self.resolve_value_symbol(node_idx)
}
};
let def_id_resolver = |node_idx: NodeIndex| -> Option<tsz_solver::def::DefId> {
if use_qualified_names {
self.resolve_def_id_with_qualified_names(node_idx)
} else {
self.resolve_def_id(node_idx)
}
};
let mut lowering = TypeLowering::with_hybrid_resolver(
self.ctx.arena,
self.ctx.types,
&type_resolver,
&def_id_resolver,
&value_resolver,
);
if !type_param_bindings.is_empty() {
lowering = lowering.with_type_param_bindings(type_param_bindings);
}
lowering.lower_type(idx)
}
// =========================================================================
// Helper Methods
// =========================================================================
/// Extract parameter information from a signature.
fn extract_params_from_signature(
&mut self,
sig: &tsz_parser::parser::node::SignatureData,
) -> (Vec<tsz_solver::ParamInfo>, Option<TypeId>) {
use tsz_solver::ParamInfo;
let mut params = Vec::new();
let mut this_type = None;
if let Some(ref param_list) = sig.parameters {
for ¶m_idx in ¶m_list.nodes {
let Some(param_node) = self.ctx.arena.get(param_idx) else {
continue;
};
let Some(param_data) = self.ctx.arena.get_parameter(param_node) else {
continue;
};
// Get parameter name
let name = self.get_param_name(param_data.name);
// Check for 'this' parameter
if name == "this" {
this_type = (param_data.type_annotation.is_some())
.then(|| self.check(param_data.type_annotation));
continue;
}
// Get parameter type
let type_id = if param_data.type_annotation.is_some() {
self.check(param_data.type_annotation)
} else {
TypeId::ANY
};
let optional = param_data.question_token || param_data.initializer.is_some();
let rest = param_data.dot_dot_dot_token;
// Under strictNullChecks, optional parameters (with `?`) get
// `undefined` added to their type.
let effective_type = if param_data.question_token
&& self.ctx.strict_null_checks()
&& type_id != TypeId::ANY
&& type_id != TypeId::ERROR
&& type_id != TypeId::UNDEFINED
{
let factory = self.ctx.types.factory();
factory.union(vec![type_id, TypeId::UNDEFINED])
} else {
type_id
};
params.push(ParamInfo {
name: Some(self.ctx.types.intern_string(&name)),
type_id: effective_type,
optional,
rest,
});
}
}
(params, this_type)
}
/// Resolve return type annotation with parameter names in scope for `typeof`.
///
/// Pushes parameter names into `typeof_param_scope` so that `typeof paramName`
/// in the return type annotation resolves to the parameter's declared type.
fn resolve_return_type_with_params_in_scope(
&mut self,
type_annotation: NodeIndex,
params: &[tsz_solver::ParamInfo],
) -> TypeId {
if type_annotation.is_none() {
return TypeId::ANY;
}
// Push param names into typeof_param_scope
for param in params {
if let Some(name_atom) = param.name {
let name = self.ctx.types.resolve_atom(name_atom);
self.ctx.typeof_param_scope.insert(name, param.type_id);
}
}
let return_type = self.check(type_annotation);
// Clear typeof_param_scope
for param in params {
if let Some(name_atom) = param.name {
let name = self.ctx.types.resolve_atom(name_atom);
self.ctx.typeof_param_scope.remove(&name);
}
}
return_type
}
/// Get parameter name from a binding name node.
fn get_param_name(&self, name_idx: NodeIndex) -> String {
if let Some(ident) = self.ctx.arena.get_identifier_at(name_idx) {
return ident.escaped_text.to_string();
}
"_".to_string()
}
/// Get property name from a property name node.
fn get_property_name(&self, name_idx: NodeIndex) -> Option<String> {
use tsz_scanner::SyntaxKind;
let name_node = self.ctx.arena.get(name_idx)?;
// Identifier
if let Some(ident) = self.ctx.arena.get_identifier(name_node) {
return Some(ident.escaped_text.clone());
}
// String literal, no-substitution template literal, or numeric literal
if matches!(
name_node.kind,
k if k == SyntaxKind::StringLiteral as u16
|| k == SyntaxKind::NoSubstitutionTemplateLiteral as u16
|| k == SyntaxKind::NumericLiteral as u16
) && let Some(lit) = self.ctx.arena.get_literal(name_node)
{
// Canonicalize numeric property names (e.g. "1.", "1.0" -> "1")
if name_node.kind == SyntaxKind::NumericLiteral as u16
&& let Some(canonical) = tsz_solver::utils::canonicalize_numeric_name(&lit.text)
{
return Some(canonical);
}
return Some(lit.text.clone());
}
None
}
/// Check if a modifier list contains the readonly modifier.
fn has_readonly_modifier(&self, modifiers: &Option<tsz_parser::parser::NodeList>) -> bool {
self.ctx
.arena
.has_modifier(modifiers, tsz_scanner::SyntaxKind::ReadonlyKeyword)
}
/// Get the context reference (for read-only access).
pub const fn context(&self) -> &CheckerContext<'ctx> {
self.ctx
}
}
#[cfg(test)]
#[path = "../../tests/type_node.rs"]
mod tests;
// Check duplicate parameters from a TypeNodeChecker context.
pub(crate) fn check_duplicate_parameters_in_type(
ctx: &mut crate::CheckerContext,
parameters: &tsz_parser::parser::NodeList,
) {
let mut seen_names = rustc_hash::FxHashSet::default();
for ¶m_idx in ¶meters.nodes {
if let Some(param_node) = ctx.arena.get(param_idx)
&& let Some(param) = ctx.arena.get_parameter(param_node)
{
collect_names_in_type(ctx, param.name, &mut seen_names);
}
}
}
fn collect_names_in_type(
ctx: &mut crate::CheckerContext,
name_idx: tsz_parser::parser::NodeIndex,
seen: &mut rustc_hash::FxHashSet<String>,
) {
use tsz_scanner::SyntaxKind;
let Some(node) = ctx.arena.get(name_idx) else {
return;
};
if node.kind == SyntaxKind::Identifier as u16 {
if let Some(name) = ctx
.arena
.get_identifier(node)
.map(|i| i.escaped_text.clone())
&& !seen.insert(name.clone())
{
let msg = crate::diagnostics::format_message(
crate::diagnostics::diagnostic_messages::DUPLICATE_IDENTIFIER,
&[&name],
);
ctx.error(
node.pos,
node.end - node.pos,
msg,
crate::diagnostics::diagnostic_codes::DUPLICATE_IDENTIFIER,
);
}
} else if (node.kind == tsz_parser::parser::syntax_kind_ext::OBJECT_BINDING_PATTERN
|| node.kind == tsz_parser::parser::syntax_kind_ext::ARRAY_BINDING_PATTERN)
&& let Some(pattern) = ctx.arena.get_binding_pattern(node)
{
for &elem_idx in &pattern.elements.nodes {
if let Some(elem_node) = ctx.arena.get(elem_idx) {
if elem_node.kind == tsz_parser::parser::syntax_kind_ext::OMITTED_EXPRESSION {
continue;
}
if let Some(elem) = ctx.arena.get_binding_element(elem_node) {
if elem.property_name.is_some()
&& let Some(prop_node) = ctx.arena.get(elem.property_name)
&& prop_node.kind == SyntaxKind::Identifier as u16
&& let Some(name_node) = ctx.arena.get(elem.name)
&& name_node.kind == SyntaxKind::Identifier as u16
{
let prop_name = ctx
.arena
.get_identifier(prop_node)
.map(|i| i.escaped_text.trim_end_matches(":").trim().to_string())
.unwrap_or_default();
let name_str = ctx
.arena
.get_identifier(name_node)
.map(|i| i.escaped_text.clone())
.unwrap_or_default();
let msg = crate::diagnostics::format_message(crate::diagnostics::diagnostic_messages::IS_AN_UNUSED_RENAMING_OF_DID_YOU_INTEND_TO_USE_IT_AS_A_TYPE_ANNOTATION, &[&name_str, &prop_name]);
ctx.error(name_node.pos, name_node.end - name_node.pos, msg, crate::diagnostics::diagnostic_codes::IS_AN_UNUSED_RENAMING_OF_DID_YOU_INTEND_TO_USE_IT_AS_A_TYPE_ANNOTATION);
}
collect_names_in_type(ctx, elem.name, seen);
}
}
}
}
}
impl<'a, 'ctx> TypeNodeChecker<'a, 'ctx> {
fn is_this_type_allowed(&self, this_node_idx: tsz_parser::parser::NodeIndex) -> bool {
use tsz_parser::parser::syntax_kind_ext;
let mut child_idx = this_node_idx;
let mut current = self
.ctx
.arena
.get_extended(this_node_idx)
.map(|ext| ext.parent);
while let Some(parent_idx) = current {
if parent_idx.is_none() {
break;
}
let Some(node) = self.ctx.arena.get(parent_idx) else {
break;
};
match node.kind {
// Nodes that PROVIDE a 'this' type context
syntax_kind_ext::CLASS_DECLARATION
| syntax_kind_ext::CLASS_EXPRESSION
| syntax_kind_ext::INTERFACE_DECLARATION => {
return true;
}
// Class/Interface members
syntax_kind_ext::METHOD_DECLARATION
| syntax_kind_ext::PROPERTY_DECLARATION
| syntax_kind_ext::GET_ACCESSOR
| syntax_kind_ext::SET_ACCESSOR
| syntax_kind_ext::INDEX_SIGNATURE
| syntax_kind_ext::PROPERTY_SIGNATURE
| syntax_kind_ext::METHOD_SIGNATURE => {
// If it's static, 'this' type is not allowed
let is_static = (node.flags & tsz_parser::modifier_flags::STATIC as u16) != 0;
if is_static {
return false;
}
// Otherwise, it's an instance member, so 'this' type is allowed.
// We continue walking up, we will eventually hit the class/interface declaration.
}
// Nodes that BLOCK 'this' type context
syntax_kind_ext::CONSTRUCTOR => {
// 'this' type not allowed in constructor parameters or return type,
// but it IS allowed in the constructor body.
if let Some(c) = self.ctx.arena.get_constructor(node)
&& child_idx == c.body
{
return true; // The body provides a 'this' context
}
return false;
}
syntax_kind_ext::FUNCTION_DECLARATION
| syntax_kind_ext::FUNCTION_EXPRESSION
| syntax_kind_ext::TYPE_ALIAS_DECLARATION
| syntax_kind_ext::MODULE_DECLARATION
| syntax_kind_ext::TYPE_LITERAL
| syntax_kind_ext::OBJECT_LITERAL_EXPRESSION
| syntax_kind_ext::CLASS_STATIC_BLOCK_DECLARATION => {
return false;
}
// Everything else (ARROW_FUNCTION, MAPPED_TYPE, BLOCK, RETURN_STATEMENT, etc.)
// just passes through to the parent.
_ => {}
}
child_idx = parent_idx;
current = self
.ctx
.arena
.get_extended(parent_idx)
.map(|ext| ext.parent);
}
false
}
}
pub(crate) fn check_parameter_initializers_in_type(
ctx: &mut crate::CheckerContext,
parameters: &tsz_parser::parser::NodeList,
) {
for ¶m_idx in ¶meters.nodes {
if let Some(param_node) = ctx.arena.get(param_idx)
&& let Some(param) = ctx.arena.get_parameter(param_node)
&& param.initializer.is_some()
{
// TSC anchors the error at the parameter name, not the initializer
let name_node = ctx.arena.get(param.name).unwrap_or(param_node);
ctx.error(
name_node.pos,
name_node.end - name_node.pos,
"A parameter initializer is only allowed in a function or constructor implementation."
.to_string(),
2371,
);
}
}
}