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
//! Type checking validation: utility methods, AST traversal helpers,
//! member/declaration/private identifier/parameter property validation,
//! destructuring, import/return/await/variable/using declaration validation.
use crate::state::CheckerState;
use rustc_hash::FxHashSet;
use tsz_parser::parser::NodeIndex;
use tsz_parser::parser::syntax_kind_ext;
use tsz_scanner::SyntaxKind;
use tsz_solver::TypeId;
// =============================================================================
// Type Checking Methods
// =============================================================================
impl<'a> CheckerState<'a> {
// =========================================================================
// Utility Methods
// =========================================================================
// =========================================================================
// AST Traversal Helper Methods (Consolidate Duplication)
// =========================================================================
/// Get modifiers from a declaration node, consolidating duplicated match statements.
///
/// This helper eliminates the repeated pattern of matching declaration kinds
/// and extracting their modifiers. Used in `has_export_modifier` and similar functions.
pub(crate) fn get_declaration_modifiers(
&self,
node: &tsz_parser::parser::node::Node,
) -> Option<&tsz_parser::parser::NodeList> {
use tsz_parser::parser::syntax_kind_ext;
match node.kind {
syntax_kind_ext::FUNCTION_DECLARATION => self
.ctx
.arena
.get_function(node)
.and_then(|f| f.modifiers.as_ref()),
syntax_kind_ext::CLASS_DECLARATION => self
.ctx
.arena
.get_class(node)
.and_then(|c| c.modifiers.as_ref()),
syntax_kind_ext::VARIABLE_STATEMENT => self
.ctx
.arena
.get_variable(node)
.and_then(|v| v.modifiers.as_ref()),
syntax_kind_ext::INTERFACE_DECLARATION => self
.ctx
.arena
.get_interface(node)
.and_then(|i| i.modifiers.as_ref()),
syntax_kind_ext::TYPE_ALIAS_DECLARATION => self
.ctx
.arena
.get_type_alias(node)
.and_then(|t| t.modifiers.as_ref()),
syntax_kind_ext::ENUM_DECLARATION => self
.ctx
.arena
.get_enum(node)
.and_then(|e| e.modifiers.as_ref()),
syntax_kind_ext::MODULE_DECLARATION => self
.ctx
.arena
.get_module(node)
.and_then(|m| m.modifiers.as_ref()),
syntax_kind_ext::IMPORT_EQUALS_DECLARATION => self
.ctx
.arena
.get_import_decl(node)
.and_then(|i| i.modifiers.as_ref()),
_ => None,
}
}
/// Get the name node from a class member node.
///
/// This helper eliminates the repeated pattern of matching member kinds
/// and extracting their name nodes.
pub(crate) fn get_member_name_node(
&self,
node: &tsz_parser::parser::node::Node,
) -> Option<NodeIndex> {
use tsz_parser::parser::syntax_kind_ext;
match node.kind {
syntax_kind_ext::PROPERTY_DECLARATION => {
self.ctx.arena.get_property_decl(node).map(|p| p.name)
}
syntax_kind_ext::METHOD_DECLARATION => {
self.ctx.arena.get_method_decl(node).map(|m| m.name)
}
k if k == syntax_kind_ext::GET_ACCESSOR || k == syntax_kind_ext::SET_ACCESSOR => {
self.ctx.arena.get_accessor(node).map(|a| a.name)
}
syntax_kind_ext::PROPERTY_SIGNATURE | syntax_kind_ext::METHOD_SIGNATURE => {
self.ctx.arena.get_signature(node).map(|s| s.name)
}
_ => None,
}
}
/// Get identifier text from a node, if it's an identifier.
///
/// This helper eliminates the repeated pattern of checking for identifier
/// and extracting `escaped_text`.
pub(crate) fn get_identifier_text(
&self,
node: &tsz_parser::parser::node::Node,
) -> Option<String> {
self.ctx
.arena
.get_identifier(node)
.map(|ident| ident.escaped_text.clone())
}
/// Get identifier text from a node index, if it's an identifier.
pub(crate) fn get_identifier_text_from_idx(&self, idx: NodeIndex) -> Option<String> {
self.ctx
.arena
.get(idx)
.and_then(|node| self.get_identifier_text(node))
}
/// Generic helper to check if modifiers include a specific keyword.
///
/// This eliminates the duplicated pattern of checking for specific modifier keywords.
pub(crate) fn has_modifier_kind(
&self,
modifiers: &Option<tsz_parser::parser::NodeList>,
kind: SyntaxKind,
) -> bool {
self.ctx.arena.has_modifier(modifiers, kind)
}
// =========================================================================
// Member and Declaration Validation
// =========================================================================
/// Check a class member name for computed property validation and
/// constructor-name restrictions (TS1341, TS1368).
///
/// This dispatches to `check_computed_property_name` for properties,
/// methods, and accessors that use computed names, and also checks
/// that "constructor" is not used as an accessor or generator name.
pub(crate) fn check_class_member_name(&mut self, member_idx: NodeIndex) {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages};
use tsz_parser::parser::syntax_kind_ext;
let Some(node) = self.ctx.arena.get(member_idx) else {
return;
};
let kind = node.kind;
// Use helper to get member name node
if let Some(name_idx) = self.get_member_name_node(node) {
self.check_computed_property_name(name_idx);
// Check constructor-name restrictions for class members
if let Some(name_text) = self.get_identifier_text_from_idx(name_idx)
&& name_text == "constructor"
{
// TS1341: Class constructor may not be an accessor
if kind == syntax_kind_ext::GET_ACCESSOR || kind == syntax_kind_ext::SET_ACCESSOR {
self.error_at_node(
name_idx,
diagnostic_messages::CLASS_CONSTRUCTOR_MAY_NOT_BE_AN_ACCESSOR,
diagnostic_codes::CLASS_CONSTRUCTOR_MAY_NOT_BE_AN_ACCESSOR,
);
}
// TS1368: Class constructor may not be a generator
if kind == syntax_kind_ext::METHOD_DECLARATION {
let node = self.ctx.arena.get(member_idx);
if let Some(method) = node.and_then(|n| self.ctx.arena.get_method_decl(n))
&& method.asterisk_token
{
self.error_at_node(
name_idx,
diagnostic_messages::CLASS_CONSTRUCTOR_MAY_NOT_BE_A_GENERATOR,
diagnostic_codes::CLASS_CONSTRUCTOR_MAY_NOT_BE_A_GENERATOR,
);
}
}
}
}
}
/// Check for duplicate enum member names.
///
/// This function validates that all enum members have unique names.
/// If duplicates are found, it emits TS2308 errors for each duplicate.
///
/// ## Duplicate Detection:
/// - Collects all member names into a `HashSet`
/// - Reports error for each name that appears more than once
/// - Error TS2308: "Duplicate identifier '{name}'"
pub(crate) fn check_enum_duplicate_members(&mut self, enum_idx: NodeIndex) {
use crate::diagnostics::diagnostic_codes;
let Some(enum_node) = self.ctx.arena.get(enum_idx) else {
return;
};
let Some(enum_decl) = self.ctx.arena.get_enum(enum_node) else {
return;
};
let mut seen_names = rustc_hash::FxHashSet::default();
for &member_idx in &enum_decl.members.nodes {
let Some(member_node) = self.ctx.arena.get(member_idx) else {
continue;
};
let Some(member) = self.ctx.arena.get_enum_member(member_node) else {
continue;
};
self.check_computed_property_name(member.name);
// Get the member name
let Some(name_node) = self.ctx.arena.get(member.name) else {
continue;
};
// TS1164: Computed property names are not allowed in enums.
// Emitted here (checker grammar check) rather than in the parser to avoid
// position-based dedup conflicts with TS1357 (missing comma between members).
if name_node.kind == tsz_parser::parser::syntax_kind_ext::COMPUTED_PROPERTY_NAME {
self.error_at_node(
member.name,
"Computed property names are not allowed in enums.",
diagnostic_codes::COMPUTED_PROPERTY_NAMES_ARE_NOT_ALLOWED_IN_ENUMS,
);
}
let name_text = if let Some(ident) = self.ctx.arena.get_identifier(name_node) {
ident.escaped_text.clone()
} else {
continue;
};
// Check for duplicate
if seen_names.contains(&name_text) {
self.error_at_node_msg(
member.name,
diagnostic_codes::DUPLICATE_IDENTIFIER,
&[&name_text],
);
} else {
seen_names.insert(name_text);
}
}
}
// =========================================================================
// Private Identifier Validation
// =========================================================================
/// Check that a private identifier expression is valid.
///
/// Validates that private field/property access is used correctly:
/// - The private identifier must be declared in a class
/// - The object type must be assignable to the declaring class type
/// - Emits appropriate errors for invalid private identifier usage
///
// ## Parameters:
/// - `name_idx`: The private identifier node index
/// - `rhs_type`: The type of the object on which the private identifier is accessed
///
/// ## Validation:
/// - Resolves private identifier symbols
/// - Checks if the object type is assignable to the declaring class
/// - Handles shadowed private members (from derived classes)
/// - Emits property does not exist errors for invalid access
pub(crate) fn check_private_identifier_in_expression(
&mut self,
name_idx: NodeIndex,
rhs_type: TypeId,
) {
let Some(name_node) = self.ctx.arena.get(name_idx) else {
return;
};
let Some(ident) = self.ctx.arena.get_identifier(name_node) else {
return;
};
let property_name = ident.escaped_text.clone();
let (symbols, saw_class_scope) = self.resolve_private_identifier_symbols(name_idx);
if symbols.is_empty() {
if saw_class_scope {
// Use original rhs_type for error message to preserve nominal identity (e.g., D<string>)
self.error_property_not_exist_at(&property_name, rhs_type, name_idx);
}
return;
}
// Evaluate for type checking but keep original for error messages
let evaluated_rhs_type = self.evaluate_application_type(rhs_type);
if evaluated_rhs_type == TypeId::ANY
|| evaluated_rhs_type == TypeId::ERROR
|| evaluated_rhs_type == TypeId::UNKNOWN
{
return;
}
let declaring_type = match self.private_member_declaring_type(symbols[0]) {
Some(ty) => ty,
None => {
if saw_class_scope {
// Use original rhs_type for error message to preserve nominal identity
self.error_property_not_exist_at(&property_name, rhs_type, name_idx);
}
return;
}
};
if !self.is_assignable_to(evaluated_rhs_type, declaring_type) {
let shadowed = symbols.iter().skip(1).any(|sym_id| {
self.private_member_declaring_type(*sym_id)
.is_some_and(|ty| self.is_assignable_to(evaluated_rhs_type, ty))
});
if shadowed {
return;
}
// Use original rhs_type for error message to preserve nominal identity
self.error_property_not_exist_at(&property_name, rhs_type, name_idx);
}
}
// =========================================================================
// Type Name Validation
// =========================================================================
/// Check a parameter's type annotation for missing type names.
///
/// Validates that type references within a parameter's type annotation
/// can be resolved. This helps catch typos and undefined types.
///
// ## Parameters:
/// - `param_idx`: The parameter node index to check
pub(crate) fn check_parameter_type_for_missing_names(&mut self, param_idx: NodeIndex) {
let Some(param_node) = self.ctx.arena.get(param_idx) else {
return;
};
let Some(param) = self.ctx.arena.get_parameter(param_node) else {
return;
};
if param.type_annotation.is_some() {
self.check_type_for_missing_names(param.type_annotation);
}
}
/// Check a tuple element for missing type names.
///
/// Validates that type references within a tuple element can be resolved.
/// Handles both named tuple members and regular tuple elements.
///
/// ## Parameters:
/// - `elem_idx`: The tuple element node index to check
pub(crate) fn check_tuple_element_for_missing_names(&mut self, elem_idx: NodeIndex) {
let Some(elem_node) = self.ctx.arena.get(elem_idx) else {
return;
};
if elem_node.kind == syntax_kind_ext::NAMED_TUPLE_MEMBER
&& let Some(member) = self.ctx.arena.get_named_tuple_member(elem_node)
{
self.check_type_for_missing_names(member.type_node);
}
}
/// Check type parameters for missing type names.
///
/// Iterates through a list of type parameters and validates that
/// their constraints and defaults reference valid types.
///
/// ## Parameters:
/// - `type_parameters`: The type parameter list to check
pub(crate) fn check_type_parameters_for_missing_names(
&mut self,
type_parameters: &Option<tsz_parser::parser::NodeList>,
) {
let Some(list) = type_parameters else {
return;
};
for ¶m_idx in &list.nodes {
self.check_type_parameter_node_for_missing_names(param_idx);
}
}
/// Check for duplicate type parameter names in a type parameter list (TS2300).
///
/// This is used for type parameter lists that are NOT processed through
/// `push_type_parameters` during the checking pass, such as interface method
/// signatures and function type expressions.
pub(crate) fn check_duplicate_type_parameters(
&mut self,
type_parameters: &Option<tsz_parser::parser::NodeList>,
) {
let Some(list) = type_parameters else {
return;
};
let mut seen = FxHashSet::default();
for ¶m_idx in &list.nodes {
let Some(param_node) = self.ctx.arena.get(param_idx) else {
continue;
};
let Some(param) = self.ctx.arena.get_type_parameter(param_node) else {
continue;
};
let Some(name_node) = self.ctx.arena.get(param.name) else {
continue;
};
let Some(ident) = self.ctx.arena.get_identifier(name_node) else {
continue;
};
let name = &ident.escaped_text;
if !seen.insert(name.clone()) {
self.error_at_node_msg(
param.name,
crate::diagnostics::diagnostic_codes::DUPLICATE_IDENTIFIER,
&[name],
);
}
}
}
/// Check a single type parameter node for missing type names.
///
/// Validates that the constraint and default type of a type parameter
/// reference valid types.
///
/// ## Parameters:
/// - `param_idx`: The type parameter node index to check
pub(crate) fn check_type_parameter_node_for_missing_names(&mut self, param_idx: NodeIndex) {
let Some(param_node) = self.ctx.arena.get(param_idx) else {
return;
};
let Some(param) = self.ctx.arena.get_type_parameter(param_node) else {
return;
};
// Check constraint type
if param.constraint.is_some() {
self.check_type_for_missing_names(param.constraint);
}
// Check default type
if param.default.is_some() {
self.check_type_for_missing_names(param.default);
}
}
// =========================================================================
// Parameter Properties Validation
// =========================================================================
/// Check a type node for parameter properties.
///
/// Recursively walks a type node and checks function/constructor types
/// and type literals for parameter properties (public/private/protected/readonly
/// parameters in class constructors).
///
/// ## Parameters:
/// - `type_idx`: The type node index to check
///
/// ## Validation:
/// - Checks function/constructor types for parameter property modifiers
/// - Checks type literals for call/construct signatures with parameter properties
/// - Recursively checks nested types (arrays, unions, intersections, etc.)
pub(crate) fn check_type_for_parameter_properties(&mut self, type_idx: NodeIndex) {
let Some(node) = self.ctx.arena.get(type_idx) else {
return;
};
// Check if this is a function type or constructor type
if node.kind == syntax_kind_ext::FUNCTION_TYPE
|| node.kind == syntax_kind_ext::CONSTRUCTOR_TYPE
{
if let Some(func_type) = self.ctx.arena.get_function_type(node) {
// Check each parameter for parameter property modifiers
self.check_strict_mode_reserved_parameter_names(
&func_type.parameters.nodes,
type_idx,
self.ctx.enclosing_class.is_some(),
);
self.check_parameter_properties(&func_type.parameters.nodes);
for (pi, ¶m_idx) in func_type.parameters.nodes.iter().enumerate() {
if let Some(param_node) = self.ctx.arena.get(param_idx)
&& let Some(param) = self.ctx.arena.get_parameter(param_node)
{
if param.type_annotation.is_some() {
self.check_type_for_parameter_properties(param.type_annotation);
}
self.maybe_report_implicit_any_parameter(param, false, pi);
}
}
// Recursively check the return type
self.check_type_for_parameter_properties(func_type.type_annotation);
}
}
// Check type literals (object types) for call/construct signatures and duplicate properties
else if node.kind == syntax_kind_ext::TYPE_LITERAL {
if let Some(type_lit) = self.ctx.arena.get_type_literal(node) {
self.check_type_literal_duplicate_properties(&type_lit.members.nodes);
for &member_idx in &type_lit.members.nodes {
self.check_type_member_for_parameter_properties(member_idx);
// TS1170: Computed property in type literal must have literal/unique symbol type
if let Some(member_node) = self.ctx.arena.get(member_idx)
&& let Some(sig) = self.ctx.arena.get_signature(member_node)
{
self.check_type_literal_computed_property_name(sig.name);
}
}
// TS2411: Check that properties are assignable to index signature types.
// Type literals don't inherit, so we pass ERROR as the "parent type"
// and rely on direct member scanning inside the method.
self.check_index_signature_compatibility(
&type_lit.members.nodes,
TypeId::ERROR,
type_idx,
);
}
}
// Recursively check array types, union types, intersection types, etc.
else if node.kind == syntax_kind_ext::ARRAY_TYPE {
if let Some(arr) = self.ctx.arena.get_array_type(node) {
self.check_type_for_parameter_properties(arr.element_type);
}
} else if node.kind == syntax_kind_ext::UNION_TYPE
|| node.kind == syntax_kind_ext::INTERSECTION_TYPE
{
if let Some(composite) = self.ctx.arena.get_composite_type(node) {
for &type_idx in &composite.types.nodes {
self.check_type_for_parameter_properties(type_idx);
}
}
} else if node.kind == syntax_kind_ext::PARENTHESIZED_TYPE
&& let Some(paren) = self.ctx.arena.get_wrapped_type(node)
{
self.check_type_for_parameter_properties(paren.type_node);
} else if node.kind == syntax_kind_ext::TYPE_PREDICATE
&& let Some(pred) = self.ctx.arena.get_type_predicate(node)
&& pred.type_node.is_some()
{
self.check_type_for_parameter_properties(pred.type_node);
}
}
/// Check for duplicate property names in type literals (TS2300).
/// e.g. `{ a: string; a: number; }` has duplicate property `a`.
///
/// Method signatures (overloads) with the same name are allowed — only
/// property signatures are checked for duplicates.
pub(crate) fn check_type_literal_duplicate_properties(&mut self, members: &[NodeIndex]) {
use crate::diagnostics::diagnostic_codes;
use tsz_parser::parser::syntax_kind_ext::PROPERTY_SIGNATURE;
let mut seen: rustc_hash::FxHashMap<String, NodeIndex> = rustc_hash::FxHashMap::default();
for &member_idx in members {
let Some(member_node) = self.ctx.arena.get(member_idx) else {
continue;
};
// Only check property signatures for duplicates.
// Method signatures with the same name are valid overloads.
if member_node.kind != PROPERTY_SIGNATURE {
continue;
}
let Some(name) = self.get_member_name(member_idx) else {
continue;
};
if let Some(&prev_idx) = seen.get(&name) {
// Report duplicate on the second occurrence
let name_idx = if let Some(sig) = self.ctx.arena.get_signature(member_node) {
sig.name
} else {
member_idx
};
self.error_at_node(
name_idx,
&format!("Duplicate identifier '{name}'."),
diagnostic_codes::DUPLICATE_IDENTIFIER,
);
// Also mark the first occurrence
if let Some(prev_node) = self.ctx.arena.get(prev_idx) {
let prev_name_idx = if let Some(sig) = self.ctx.arena.get_signature(prev_node) {
sig.name
} else {
prev_idx
};
self.error_at_node(
prev_name_idx,
&format!("Duplicate identifier '{name}'."),
diagnostic_codes::DUPLICATE_IDENTIFIER,
);
}
} else {
seen.insert(name, member_idx);
}
}
}
// =========================================================================
// Destructuring Validation
// =========================================================================
/// Check a binding pattern for destructuring validity.
///
/// Validates that destructuring patterns (object/array destructuring) are applied
/// to valid types and that default values are assignable to their expected types.
///
/// ## Parameters:
/// - `pattern_idx`: The binding pattern node index to check
/// - `pattern_type`: The type being destructured
///
/// ## Validation:
/// - Checks array destructuring target types (TS2461)
/// - Validates default value assignability for binding elements
/// - Recursively checks nested binding patterns
pub(crate) fn check_binding_pattern(
&mut self,
pattern_idx: NodeIndex,
pattern_type: TypeId,
check_default_assignability: bool,
) {
let Some(pattern_node) = self.ctx.arena.get(pattern_idx) else {
return;
};
let Some(pattern_data) = self.ctx.arena.get_binding_pattern(pattern_node) else {
return;
};
let elements_len = pattern_data.elements.nodes.len();
// TS2531/TS2532/TS2533: Destructuring from a possibly-nullish value is an error.
// TypeScript only emits this directly on the pattern when the pattern is empty.
// For non-empty patterns, errors are emitted when accessing the individual properties/elements.
if elements_len == 0 && pattern_type != TypeId::ANY && pattern_type != TypeId::ERROR {
let (non_nullish_type, nullish_cause) = self.split_nullish_type(pattern_type);
if let Some(cause) = nullish_cause {
self.report_nullish_object(pattern_idx, cause, non_nullish_type.is_none());
}
}
// Traverse binding elements
// Note: Array destructuring iterability (TS2488) is checked by the caller
// (state_checking.rs) via check_destructuring_iterability before invoking
// check_binding_pattern, so we do NOT call check_array_destructuring_target_type
// here to avoid duplicate TS2488 errors.
for (i, &element_idx) in pattern_data.elements.nodes.iter().enumerate() {
if i < elements_len - 1
&& let Some(element_node) = self.ctx.arena.get(element_idx)
&& let Some(element_data) = self.ctx.arena.get_binding_element(element_node)
&& element_data.dot_dot_dot_token
{
use tsz_common::diagnostics::diagnostic_codes;
self.error_at_node_msg(
element_idx,
diagnostic_codes::A_REST_ELEMENT_MUST_BE_LAST_IN_A_DESTRUCTURING_PATTERN,
&[],
);
}
self.check_binding_element(
element_idx,
pattern_idx,
i,
pattern_type,
check_default_assignability,
);
}
}
/// Check a single binding element for default value assignability.
///
/// Validates that default values in destructuring patterns are assignable
/// to the expected property/element type.
///
/// ## Parameters:
/// - `element_idx`: The binding element node index to check
/// - `pattern_idx`: The binding pattern node index (object or array)
/// - `element_index`: The index of this element in the pattern
/// - `parent_type`: The type being destructured
///
/// ## Validation:
/// - Checks computed property names for unresolved identifiers
/// - Validates default value type assignability
/// - Recursively checks nested binding patterns
pub(crate) fn check_binding_element(
&mut self,
element_idx: NodeIndex,
pattern_idx: NodeIndex,
element_index: usize,
parent_type: TypeId,
check_default_assignability: bool,
) {
let Some(element_node) = self.ctx.arena.get(element_idx) else {
return;
};
// Handle holes in array destructuring: [a, , b]
if element_node.kind == syntax_kind_ext::OMITTED_EXPRESSION {
return;
}
let Some(element_data) = self.ctx.arena.get_binding_element(element_node) else {
return;
};
let pattern_kind = self.ctx.arena.get(pattern_idx).map_or(0, |n| n.kind);
// Check computed property name expression for unresolved identifiers (TS2304)
// e.g., in `{[z]: x}` where `z` is undefined
if element_data.property_name.is_some() {
self.check_computed_property_name(element_data.property_name);
}
// Get the expected type for this binding element from the parent type
let element_type = if parent_type != TypeId::ANY {
// For object binding patterns, look up the property type
// For array binding patterns, look up the tuple element type
self.get_binding_element_type(pattern_idx, element_index, parent_type, element_data)
} else {
TypeId::ANY
};
// Set contextual type for default initializers that are function-like, so
// parameter types can be inferred from the expected element type. This must
// happen unconditionally (not gated on assignability checks) because the
// initializer's type is computed and cached on first access — if contextual
// type isn't set here, the arrow's parameters will be typed as `any`.
if element_data.initializer.is_some() && element_type != TypeId::ANY {
let prev_context = self.ctx.contextual_type;
if let Some(init_node) = self.ctx.arena.get(element_data.initializer) {
let k = init_node.kind;
if k == syntax_kind_ext::ARROW_FUNCTION || k == syntax_kind_ext::FUNCTION_EXPRESSION
{
self.ctx.contextual_type = Some(element_type);
}
}
let default_value_type = self.get_type_of_node(element_data.initializer);
self.ctx.contextual_type = prev_context;
// TypeScript only checks default value assignability in function parameter
// destructuring, not in variable declaration destructuring.
// For object binding patterns, a default initializer is only reachable when
// the property can be missing/undefined. Skip assignability checks for required
// properties to match TypeScript's control-flow behavior.
if check_default_assignability
&& (pattern_kind != syntax_kind_ext::OBJECT_BINDING_PATTERN
|| tsz_solver::type_queries::type_includes_undefined(
self.ctx.types,
element_type,
))
{
let _ = self.check_assignable_or_report(
default_value_type,
element_type,
element_data.initializer,
);
}
}
// If the name is a nested binding pattern, recursively check it
if let Some(name_node) = self.ctx.arena.get(element_data.name)
&& (name_node.kind == syntax_kind_ext::OBJECT_BINDING_PATTERN
|| name_node.kind == syntax_kind_ext::ARRAY_BINDING_PATTERN)
{
self.check_binding_pattern(
element_data.name,
element_type,
check_default_assignability,
);
}
}
// =========================================================================
// Import Validation
// =========================================================================
}
// =============================================================================
// Statement Validation
// =============================================================================
impl<'a> CheckerState<'a> {
// =========================================================================
// Return Statement Validation
// =========================================================================
/// Check a return statement for validity.
///
/// Validates that:
/// - The return expression type is assignable to the function's return type
/// - Await expressions are only used in async functions (TS1359)
/// - Object literals don't have excess properties
///
/// ## Parameters:
/// - `stmt_idx`: The return statement node index to check
///
/// ## Validation:
/// - Checks return type assignability
/// - Validates await expressions are in async context
/// - Checks object literal excess properties
pub(crate) fn check_return_statement(&mut self, stmt_idx: NodeIndex) {
let Some(node) = self.ctx.arena.get(stmt_idx) else {
return;
};
let Some(return_data) = self.ctx.arena.get_return_statement(node) else {
return;
};
// TS1108: A 'return' statement can only be used within a function body.
// In .d.ts files, TS1036 is emitted instead of TS1108.
// Like TSC's grammarErrorOnFirstToken, suppress grammar errors when parse
// errors are present — TSC checks hasParseDiagnostics(sourceFile) before
// emitting TS1108 and other grammar errors.
if self.current_return_type().is_none() {
if !self.ctx.is_in_ambient_declaration_file && !self.has_syntax_parse_errors() {
use crate::diagnostics::diagnostic_codes;
self.error_at_node(
stmt_idx,
"A 'return' statement can only be used within a function body.",
diagnostic_codes::A_RETURN_STATEMENT_CAN_ONLY_BE_USED_WITHIN_A_FUNCTION_BODY,
);
}
return;
}
// TS2408: Setters cannot return a value.
if return_data.expression.is_some() {
use tsz_parser::parser::syntax_kind_ext;
if let Some(enclosing_fn_idx) = self.find_enclosing_function(stmt_idx)
&& let Some(enclosing_fn_node) = self.ctx.arena.get(enclosing_fn_idx)
&& enclosing_fn_node.kind == syntax_kind_ext::SET_ACCESSOR
{
use crate::diagnostics::diagnostic_codes;
self.error_at_node(
stmt_idx,
"Setters cannot return a value.",
diagnostic_codes::SETTERS_CANNOT_RETURN_A_VALUE,
);
return;
}
}
// Get the expected return type from the function context
let expected_type = self.current_return_type().unwrap_or(TypeId::UNKNOWN);
// Get the type of the return expression (if any)
let return_type = if return_data.expression.is_some() {
// TS1359: Check for await expressions outside async function
self.check_await_expression(return_data.expression);
let prev_context = self.ctx.contextual_type;
let should_contextualize =
self.ctx
.arena
.get(return_data.expression)
.is_some_and(|expr_node| {
expr_node.kind != tsz_scanner::SyntaxKind::Identifier as u16
});
if should_contextualize
&& expected_type != TypeId::ANY
&& !self.type_contains_error(expected_type)
{
self.ctx.contextual_type = Some(expected_type);
// Clear cached type to force recomputation with contextual type
// This is necessary because the expression might have been previously typed
// without contextual information (e.g., during function body analysis)
self.clear_type_cache_recursive(return_data.expression);
}
let mut return_type = self.get_type_of_node(return_data.expression);
if self.ctx.in_async_context() {
return_type = self.unwrap_promise_type(return_type).unwrap_or(return_type);
}
self.ctx.contextual_type = prev_context;
return_type
} else {
// `return;` without expression returns undefined
TypeId::UNDEFINED
};
// Ensure relation preconditions for the return expression before assignability.
// The assignability gateway already prepares `expected_type`, so doing it here
// as well duplicates expensive lazy-ref/application traversals on hot return paths.
self.ensure_relation_input_ready(return_type);
// Check if the return type is assignable to the expected type.
let is_in_constructor = self
.ctx
.enclosing_class
.as_ref()
.is_some_and(|c| c.in_constructor);
// TSC anchors TS2322 at the return statement node (the `return` keyword),
// not at the return value expression.
let error_node = stmt_idx;
// In constructors, bare `return;` (without expression) is always allowed — TSC
// doesn't check assignability for void returns in constructors.
let skip_assignability = is_in_constructor && return_data.expression.is_none();
// Track whether assignability check passed — when it fails, the solver's
// failure reason already emits the appropriate diagnostic (including TS2353
// for excess properties on fresh object literals). Running the explicit
// excess-property check again would produce a duplicate.
let assignability_ok = if !skip_assignability
&& expected_type != TypeId::ANY
&& !self.type_contains_error(expected_type)
{
let ok = self.check_assignable_or_report(return_type, expected_type, error_node);
if !ok {
// TS2409: In constructors, also emit the constructor-specific diagnostic
// alongside the TS2322 already emitted by check_assignable_or_report.
if is_in_constructor {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages};
self.error_at_node(
error_node,
diagnostic_messages::RETURN_TYPE_OF_CONSTRUCTOR_SIGNATURE_MUST_BE_ASSIGNABLE_TO_THE_INSTANCE_TYPE_OF,
diagnostic_codes::RETURN_TYPE_OF_CONSTRUCTOR_SIGNATURE_MUST_BE_ASSIGNABLE_TO_THE_INSTANCE_TYPE_OF,
);
}
}
ok
} else {
true
};
// Only run explicit excess-property check when the assignability check
// passed (types are structurally compatible but may have excess props)
// or was skipped. When assignability failed, the solver already
// emitted the correct TS2353/TS2322 via the failure reason.
if assignability_ok
&& expected_type != TypeId::ANY
&& expected_type != TypeId::UNKNOWN
&& !self.type_contains_error(expected_type)
&& return_data.expression.is_some()
&& let Some(expr_node) = self.ctx.arena.get(return_data.expression)
&& expr_node.kind == syntax_kind_ext::OBJECT_LITERAL_EXPRESSION
{
self.check_object_literal_excess_properties(
return_type,
expected_type,
return_data.expression,
);
}
}
// =========================================================================
// Await Expression Validation
// =========================================================================
/// Check if current compiler options support top-level await.
///
/// Top-level await is supported when:
/// - module is ES2022, `ESNext`, System, Node16, `NodeNext`, or Preserve
/// - target is ES2017 or higher
const fn supports_top_level_await(&self) -> bool {
use tsz_common::common::{ModuleKind, ScriptTarget};
// Check module kind supports top-level await
let module_ok = matches!(
self.ctx.compiler_options.module,
ModuleKind::ES2022
| ModuleKind::ESNext
| ModuleKind::System
| ModuleKind::Node16
| ModuleKind::NodeNext
| ModuleKind::Preserve
);
// Check target is ES2017 or higher
let target_ok = self.ctx.compiler_options.target as u32 >= ScriptTarget::ES2017 as u32;
module_ok && target_ok
}
/// Check an await expression for async context.
///
/// Validates that await expressions are only used within async functions,
/// recursively checking child expressions for nested await usage.
///
/// ## Parameters:
/// - `expr_idx`: The expression node index to check
///
/// ## Validation:
/// - Emits TS1308 if await is used outside async function
/// - Iteratively checks child expressions for await expressions (no recursion)
pub(crate) fn check_await_expression(&mut self, expr_idx: NodeIndex) {
// Use iterative approach with explicit stack to handle deeply nested expressions
// This prevents stack overflow for expressions like `0 + 0 + 0 + ... + 0` (50K+ deep)
let mut stack = vec![expr_idx];
while let Some(current_idx) = stack.pop() {
let Some(node) = self.ctx.arena.get(current_idx) else {
continue;
};
// Push child expressions onto stack for iterative processing
match node.kind {
syntax_kind_ext::BINARY_EXPRESSION => {
if let Some(bin_expr) = self.ctx.arena.get_binary_expr(node) {
if bin_expr.right.is_some() {
stack.push(bin_expr.right);
}
if bin_expr.left.is_some() {
stack.push(bin_expr.left);
}
}
}
syntax_kind_ext::PREFIX_UNARY_EXPRESSION
| syntax_kind_ext::POSTFIX_UNARY_EXPRESSION => {
if let Some(unary_expr) = self.ctx.arena.get_unary_expr_ex(node)
&& unary_expr.expression.is_some()
{
stack.push(unary_expr.expression);
}
}
syntax_kind_ext::AWAIT_EXPRESSION => {
// Validate await expression context
if !self.ctx.in_async_context() {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages};
// Check if we're at top level of a module
let at_top_level = self.ctx.function_depth == 0;
if at_top_level {
// TS1378: Top-level await requires ES2022+/ESNext module and ES2017+ target
if !self.supports_top_level_await() {
self.error_at_node(
current_idx,
diagnostic_messages::TOP_LEVEL_AWAIT_EXPRESSIONS_ARE_ONLY_ALLOWED_WHEN_THE_MODULE_OPTION_IS_SET_TO_ES,
diagnostic_codes::TOP_LEVEL_AWAIT_EXPRESSIONS_ARE_ONLY_ALLOWED_WHEN_THE_MODULE_OPTION_IS_SET_TO_ES,
);
}
} else {
// TS1308: 'await' expressions are only allowed within async functions
self.error_at_node(
current_idx,
diagnostic_messages::AWAIT_EXPRESSIONS_ARE_ONLY_ALLOWED_WITHIN_ASYNC_FUNCTIONS_AND_AT_THE_TOP_LEVELS,
diagnostic_codes::AWAIT_EXPRESSIONS_ARE_ONLY_ALLOWED_WITHIN_ASYNC_FUNCTIONS_AND_AT_THE_TOP_LEVELS,
);
}
}
if let Some(unary_expr) = self.ctx.arena.get_unary_expr_ex(node)
&& unary_expr.expression.is_some()
{
stack.push(unary_expr.expression);
}
}
syntax_kind_ext::CALL_EXPRESSION => {
if let Some(call_expr) = self.ctx.arena.get_call_expr(node) {
// Check arguments (push in reverse order for correct traversal)
if let Some(ref args) = call_expr.arguments {
for &arg in args.nodes.iter().rev() {
if arg.is_some() {
stack.push(arg);
}
}
}
if call_expr.expression.is_some() {
stack.push(call_expr.expression);
}
}
}
syntax_kind_ext::PROPERTY_ACCESS_EXPRESSION => {
if let Some(access_expr) = self.ctx.arena.get_access_expr(node)
&& access_expr.expression.is_some()
{
stack.push(access_expr.expression);
}
}
syntax_kind_ext::PARENTHESIZED_EXPRESSION => {
if let Some(paren_expr) = self.ctx.arena.get_parenthesized(node)
&& paren_expr.expression.is_some()
{
stack.push(paren_expr.expression);
}
}
_ => {
// For other expression types, don't recurse into children
// to avoid infinite recursion or performance issues
}
}
}
}
// =========================================================================
// Variable Statement Validation
// =========================================================================
/// Check a for-await statement for async context and module/target support.
///
/// Validates that for-await loops are only used within async functions or at top level
/// with appropriate compiler options.
///
/// ## Parameters:
/// - `stmt_idx`: The for-await statement node index to check
///
/// ## Validation:
/// - Emits TS1103 if for-await is used outside async function and not at top level
/// - Emits TS1432 if for-await is at top level but module/target options don't support it
pub(crate) fn check_for_await_statement(&mut self, stmt_idx: NodeIndex) {
if !self.ctx.in_async_context() {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages};
// Check if we're at top level of a module
let at_top_level = self.ctx.function_depth == 0;
if at_top_level {
// TS1431: Only emit when the file is NOT a module (no imports/exports).
// If the file is a module, top-level for-await is potentially valid
// (just needs the right module/target settings).
if !self.ctx.binder.is_external_module() {
self.error_at_node(
stmt_idx,
diagnostic_messages::FOR_AWAIT_LOOPS_ARE_ONLY_ALLOWED_AT_THE_TOP_LEVEL_OF_A_FILE_WHEN_THAT_FILE_IS_A,
diagnostic_codes::FOR_AWAIT_LOOPS_ARE_ONLY_ALLOWED_AT_THE_TOP_LEVEL_OF_A_FILE_WHEN_THAT_FILE_IS_A,
);
}
// TS1432: Top-level for-await requires ES2022+/ESNext module and ES2017+ target
if !self.supports_top_level_await() {
self.error_at_node(
stmt_idx,
diagnostic_messages::TOP_LEVEL_FOR_AWAIT_LOOPS_ARE_ONLY_ALLOWED_WHEN_THE_MODULE_OPTION_IS_SET_TO_ES20,
diagnostic_codes::TOP_LEVEL_FOR_AWAIT_LOOPS_ARE_ONLY_ALLOWED_WHEN_THE_MODULE_OPTION_IS_SET_TO_ES20,
);
}
} else {
// TS1103: 'for await' loops are only allowed within async functions
self.error_at_node(
stmt_idx,
diagnostic_messages::FOR_AWAIT_LOOPS_ARE_ONLY_ALLOWED_WITHIN_ASYNC_FUNCTIONS_AND_AT_THE_TOP_LEVELS_OF,
diagnostic_codes::FOR_AWAIT_LOOPS_ARE_ONLY_ALLOWED_WITHIN_ASYNC_FUNCTIONS_AND_AT_THE_TOP_LEVELS_OF,
);
}
}
}
/// Check a variable statement.
///
/// Iterates through variable declaration lists in a variable statement
/// and validates each declaration.
///
/// ## Parameters:
/// - `stmt_idx`: The variable statement node index to check
pub(crate) fn check_variable_statement(&mut self, stmt_idx: NodeIndex) {
let Some(node) = self.ctx.arena.get(stmt_idx) else {
return;
};
if let Some(var) = self.ctx.arena.get_variable(node) {
// VariableStatement.declarations contains VariableDeclarationList nodes
for &list_idx in &var.declarations.nodes {
self.check_variable_declaration_list(list_idx);
}
}
}
/// Check a variable declaration list (var/let/const x, y, z).
///
/// Iterates through individual variable declarations in a list and
/// validates each one.
///
/// ## Parameters:
/// - `list_idx`: The variable declaration list node index to check
pub(crate) fn check_variable_declaration_list(&mut self, list_idx: NodeIndex) {
let Some(node) = self.ctx.arena.get(list_idx) else {
return;
};
// Check if this is a using/await using declaration list.
// Only check the USING bit (bit 2) — AWAIT_USING (6) = CONST (2) | USING (4),
// so checking just the USING bit correctly matches both using and await using
// but not const.
use tsz_parser::parser::flags::node_flags;
let flags_u32 = node.flags as u32;
let is_using = (flags_u32 & node_flags::USING) != 0;
let is_await_using = flags_u32 == node_flags::AWAIT_USING;
// VariableDeclarationList uses the same VariableData structure
if let Some(var_list) = self.ctx.arena.get_variable(node) {
// Now these are actual VariableDeclaration nodes
for &decl_idx in &var_list.declarations.nodes {
self.check_variable_declaration(decl_idx);
// Check using/await using declarations have Symbol.dispose
if is_using || is_await_using {
self.check_using_declaration_disposable(decl_idx, is_await_using);
}
}
}
}
// =========================================================================
// Using Declaration Validation (TS2804, TS2803)
// =========================================================================
/// Check if a using/await using declaration's initializer type has the required dispose method.
///
/// ## Parameters
/// - `decl_idx`: The variable declaration node index
/// - `is_await_using`: Whether this is an await using declaration
///
/// Checks:
/// - `using` requires type to have `[Symbol.dispose]()` method
/// - `await using` requires type to have `[Symbol.asyncDispose]()` or `[Symbol.dispose]()` method
fn check_using_declaration_disposable(&mut self, decl_idx: NodeIndex, is_await_using: bool) {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages};
let Some(node) = self.ctx.arena.get(decl_idx) else {
return;
};
let Some(var_decl) = self.ctx.arena.get_variable_declaration(node) else {
return;
};
// Skip if no initializer
if var_decl.initializer.is_none() {
return;
}
// Get the type of the initializer
let init_type = self.get_type_of_node(var_decl.initializer);
// Skip error type and any (suppressed by convention)
if init_type == TypeId::ERROR || init_type == TypeId::ANY {
return;
}
// Check for the required dispose method
if !self.type_has_disposable_method(init_type, is_await_using) {
let (message, code) = if is_await_using {
(
diagnostic_messages::THE_INITIALIZER_OF_AN_AWAIT_USING_DECLARATION_MUST_BE_EITHER_AN_OBJECT_WITH_A_SY,
diagnostic_codes::THE_INITIALIZER_OF_AN_AWAIT_USING_DECLARATION_MUST_BE_EITHER_AN_OBJECT_WITH_A_SY,
)
} else {
(
diagnostic_messages::THE_INITIALIZER_OF_A_USING_DECLARATION_MUST_BE_EITHER_AN_OBJECT_WITH_A_SYMBOL_DI,
diagnostic_codes::THE_INITIALIZER_OF_A_USING_DECLARATION_MUST_BE_EITHER_AN_OBJECT_WITH_A_SYMBOL_DI,
)
};
self.error_at_node(var_decl.initializer, message, code);
}
}
/// Check if a type has the appropriate dispose method.
///
/// For `using`: checks for `[Symbol.dispose]()`
/// For `await using`: checks for `[Symbol.asyncDispose]()` or `[Symbol.dispose]()`
fn type_has_disposable_method(&mut self, type_id: TypeId, is_await_using: bool) -> bool {
// Check intrinsic types
if type_id == TypeId::ANY
|| type_id == TypeId::UNKNOWN
|| type_id == TypeId::ERROR
|| type_id == TypeId::NEVER
{
return true; // Suppress errors on these types
}
// null and undefined can be disposed (no-op)
if type_id == TypeId::NULL || type_id == TypeId::UNDEFINED {
return true;
}
// Only check for dispose methods if Symbol.dispose is available in the current environment
// Check by looking for the dispose property on SymbolConstructor
let symbol_type = if let Some(sym_id) = self.ctx.binder.file_locals.get("Symbol") {
self.get_type_of_symbol(sym_id)
} else {
TypeId::ERROR
};
let symbol_has_dispose = self.object_has_property(symbol_type, "dispose")
|| self.object_has_property(symbol_type, "[Symbol.dispose]")
|| self.object_has_property(symbol_type, "Symbol.dispose");
let symbol_has_async_dispose = self.object_has_property(symbol_type, "asyncDispose")
|| self.object_has_property(symbol_type, "[Symbol.asyncDispose]")
|| self.object_has_property(symbol_type, "Symbol.asyncDispose");
// For await using, we need either Symbol.asyncDispose or Symbol.dispose
if is_await_using && !symbol_has_async_dispose && !symbol_has_dispose {
// Symbol.asyncDispose and Symbol.dispose are not available in this lib
// Don't check for them (TypeScript will emit other errors about missing globals)
return true;
}
// For regular using, we need Symbol.dispose
if !is_await_using && !symbol_has_dispose {
// Symbol.dispose is not available in this lib
// Don't check for it
return true;
}
// Check for the dispose method on the object type
// Try both "[Symbol.dispose]" and "Symbol.dispose" formats
let has_dispose = self.object_has_property(type_id, "[Symbol.dispose]")
|| self.object_has_property(type_id, "Symbol.dispose");
if is_await_using {
// await using accepts either Symbol.asyncDispose or Symbol.dispose
return has_dispose
|| self.object_has_property(type_id, "[Symbol.asyncDispose]")
|| self.object_has_property(type_id, "Symbol.asyncDispose");
}
has_dispose
}
}
impl<'a> CheckerState<'a> {
/// Check a type alias declaration.
pub(crate) fn check_type_alias_declaration(&mut self, node_idx: NodeIndex) {
let Some(node) = self.ctx.arena.get(node_idx) else {
return;
};
let Some(alias) = self.ctx.arena.get_type_alias(node) else {
return;
};
let updates = self.push_missing_name_type_parameters(&alias.type_parameters);
if let Some(type_params) = &alias.type_parameters {
let factory = self.ctx.types.factory();
for ¶m_idx in &type_params.nodes {
let Some(param_node) = self.ctx.arena.get(param_idx) else {
continue;
};
let Some(param) = self.ctx.arena.get_type_parameter(param_node) else {
continue;
};
let Some(name_node) = self.ctx.arena.get(param.name) else {
continue;
};
let Some(ident) = self.ctx.arena.get_identifier(name_node) else {
continue;
};
let constraint = if param.constraint != NodeIndex::NONE {
Some(self.get_type_from_type_node(param.constraint))
} else {
None
};
let default = if param.default != NodeIndex::NONE {
let default_type = self.get_type_from_type_node(param.default);
if default_type == TypeId::ERROR {
None
} else {
Some(default_type)
}
} else {
None
};
let atom = self.ctx.types.intern_string(&ident.escaped_text);
let constrained_param = factory.type_param(tsz_solver::TypeParamInfo {
name: atom,
constraint,
default,
is_const: false,
});
self.ctx
.type_parameter_scope
.insert(ident.escaped_text.clone(), constrained_param);
}
}
self.check_type_node(alias.type_node);
self.pop_type_parameters(updates);
}
/// Check a type node for validity (recursive).
pub(crate) fn check_type_node(&mut self, node_idx: NodeIndex) {
if node_idx == NodeIndex::NONE {
return;
}
let Some(node) = self.ctx.arena.get(node_idx) else {
return;
};
match node.kind {
k if k == syntax_kind_ext::INDEXED_ACCESS_TYPE => {
self.check_indexed_access_type(node_idx);
}
k if k == syntax_kind_ext::UNION_TYPE || k == syntax_kind_ext::INTERSECTION_TYPE => {
if let Some(composite) = self.ctx.arena.get_composite_type(node) {
for &child in &composite.types.nodes {
self.check_type_node(child);
}
}
}
k if k == syntax_kind_ext::ARRAY_TYPE => {
if let Some(arr) = self.ctx.arena.get_array_type(node) {
self.check_type_node(arr.element_type);
}
}
k if k == syntax_kind_ext::TYPE_LITERAL => {
// TODO: implement check_type_element for type literal members
}
_ => {}
}
}
/// Check an indexed access type (T[K]).
pub(crate) fn check_indexed_access_type(&mut self, node_idx: NodeIndex) {
let Some(node) = self.ctx.arena.get(node_idx) else {
return;
};
let Some(data) = self.ctx.arena.get_indexed_access_type(node) else {
return;
};
let object_type = self.get_type_from_type_node(data.object_type);
let index_type = self.get_type_from_type_node(data.index_type);
use crate::diagnostics::{diagnostic_codes, diagnostic_messages, format_message};
if object_type == TypeId::ERROR
|| index_type == TypeId::ERROR
|| object_type == TypeId::ANY
|| index_type == TypeId::ANY
{
return;
}
let mut object_type_for_check = self.evaluate_type_with_env(object_type);
object_type_for_check = tsz_solver::type_queries::get_type_parameter_constraint(
self.ctx.types,
object_type_for_check,
)
.unwrap_or(object_type_for_check);
if let Some((base_object_type, access_index_type)) =
tsz_solver::type_queries::get_index_access_types(self.ctx.types, object_type_for_check)
&& let Some(base_constraint) = tsz_solver::type_queries::get_type_parameter_constraint(
self.ctx.types,
base_object_type,
)
{
let constrained_access = self
.ctx
.types
.factory()
.index_access(base_constraint, access_index_type);
let evaluated_constrained_access =
self.evaluate_type_for_assignability(constrained_access);
if evaluated_constrained_access != TypeId::ERROR {
object_type_for_check = evaluated_constrained_access;
}
}
let keyof_object = self.ctx.types.evaluate_keyof(object_type_for_check);
let index_type_for_check = self.evaluate_type_with_env(index_type);
let index_type_for_check = tsz_solver::type_queries::get_type_parameter_constraint(
self.ctx.types,
index_type_for_check,
)
.unwrap_or(index_type_for_check);
if !self.is_assignable_to(index_type_for_check, keyof_object) {
if let Some((wants_string, wants_number)) =
self.get_index_key_kind(index_type_for_check)
&& self.is_element_indexable(object_type_for_check, wants_string, wants_number)
{
return;
}
if let Some(object_type_node) = self.ctx.arena.get(data.object_type)
&& let Some(nested_indexed_access) =
self.ctx.arena.get_indexed_access_type(object_type_node)
{
let mut constrained_base_type =
self.get_type_from_type_node(nested_indexed_access.object_type);
constrained_base_type = tsz_solver::type_queries::get_type_parameter_constraint(
self.ctx.types,
constrained_base_type,
)
.unwrap_or(constrained_base_type);
let nested_index_type =
self.get_type_from_type_node(nested_indexed_access.index_type);
let constrained_object_type = if let Some(prop_atom) =
tsz_solver::type_queries::get_string_literal_value(
self.ctx.types,
nested_index_type,
) {
let property_name = self.ctx.types.resolve_atom(prop_atom);
match self
.resolve_property_access_with_env(constrained_base_type, &property_name)
{
tsz_solver::operations::property::PropertyAccessResult::Success {
type_id,
..
} => type_id,
_ => self.evaluate_type_with_env(
self.ctx
.types
.factory()
.index_access(constrained_base_type, nested_index_type),
),
}
} else {
self.evaluate_type_with_env(
self.ctx
.types
.factory()
.index_access(constrained_base_type, nested_index_type),
)
};
if constrained_object_type != TypeId::ERROR
&& let Some((wants_string, wants_number)) =
self.get_index_key_kind(index_type_for_check)
&& self.is_element_indexable(
constrained_object_type,
wants_string,
wants_number,
)
{
return;
}
}
let obj_type_str = self.format_type(object_type);
let index_type_str = self.format_type(index_type);
let message_2536 = format_message(
diagnostic_messages::TYPE_CANNOT_BE_USED_TO_INDEX_TYPE,
&[&index_type_str, &obj_type_str],
);
self.error_at_node(
data.index_type,
&message_2536,
diagnostic_codes::TYPE_CANNOT_BE_USED_TO_INDEX_TYPE,
);
}
}
}