1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
//! Checker Context
//!
//! Holds the shared state used throughout the type checking process.
//! This separates state from logic, allowing specialized checkers (expressions, statements)
//! to borrow the context mutably.
//!
//! Sub-modules:
//! - `constructors` - `CheckerContext` constructor methods
//! - `resolver` - `TypeResolver` trait implementation
//! - `def_mapping` - DefId migration helpers
//! - `compiler_options` - Compiler option accessors and solver config derivation
//! - `lib_queries` - Library/global type availability queries
mod compiler_options;
mod constructors;
mod def_mapping;
mod lib_queries;
mod resolver;
mod strict_mode;
use rustc_hash::{FxHashMap, FxHashSet};
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::rc::Rc;
use std::sync::Arc;
use tsz_common::interner::Atom;
use crate::control_flow::FlowGraph;
use crate::diagnostics::Diagnostic;
use crate::module_resolution::module_specifier_candidates;
use tsz_binder::SymbolId;
use tsz_parser::parser::NodeIndex;
use tsz_solver::def::{DefId, DefinitionStore};
use tsz_solver::{QueryDatabase, TypeEnvironment, TypeId};
// Re-export CheckerOptions and ScriptTarget from tsz-common
use tsz_binder::BinderState;
pub use tsz_common::checker_options::CheckerOptions;
pub use tsz_common::common::ScriptTarget;
use tsz_parser::parser::node::NodeArena;
use tsz_parser::parser::syntax_kind_ext;
type ResolvedModulePathMap = FxHashMap<(usize, String), usize>;
type ResolvedModuleErrorMap = FxHashMap<(usize, String), ResolutionError>;
/// Represents a failed module resolution with specific error details.
#[derive(Clone, Debug)]
pub struct ResolutionError {
pub code: u32,
pub message: String,
}
/// Info about the enclosing class for static member suggestions and abstract property checks.
#[derive(Clone, Debug)]
pub struct EnclosingClassInfo {
/// Name of the class.
pub name: String,
/// Node index for the class declaration.
pub class_idx: NodeIndex,
/// Member node indices for symbol lookup.
pub member_nodes: Vec<NodeIndex>,
/// Whether we're in a constructor (for error 2715 checking).
pub in_constructor: bool,
/// Whether this is a `declare class` (ambient context for error 1183).
pub is_declared: bool,
/// Whether we're in a static property initializer (for TS17011 checking).
pub in_static_property_initializer: bool,
/// Whether we're in a static method or property context.
pub in_static_member: bool,
/// Whether any `super()` call appeared while checking the current constructor body.
pub has_super_call_in_current_constructor: bool,
/// Cached instance `this` type for members of this class.
pub cached_instance_this_type: Option<TypeId>,
/// Names of the class's own type parameters (for TS2302 checking in static members).
pub type_param_names: Vec<String>,
/// The type parameter infos of the class's own type parameters.
pub class_type_parameters: Vec<tsz_solver::TypeParamInfo>,
}
/// Info about a label in scope for break/continue validation.
#[derive(Clone, Debug)]
pub struct LabelInfo {
/// The label name (e.g., "outer").
pub name: String,
/// Whether the label is on an iteration statement (for continue validation).
/// Only iteration labels can be targets of continue statements.
pub is_iteration: bool,
/// The function depth when this label was defined.
/// Used to detect if a jump crosses a function boundary.
pub function_depth: u32,
}
/// Persistent cache for type checking results across LSP queries.
/// This cache survives between LSP requests but is invalidated when the file changes.
#[derive(Clone, Debug)]
pub struct TypeCache {
/// Cached types for symbols.
pub symbol_types: FxHashMap<SymbolId, TypeId>,
/// Cached instance types for class symbols (for TYPE position).
/// Distinguishes from `symbol_types` which holds constructor types for VALUE position.
pub symbol_instance_types: FxHashMap<SymbolId, TypeId>,
/// Cached types for nodes.
pub node_types: FxHashMap<u32, TypeId>,
/// Symbol dependency graph (symbol -> referenced symbols).
pub symbol_dependencies: FxHashMap<SymbolId, FxHashSet<SymbolId>>,
/// Maps `DefIds` to `SymbolIds` for declaration emit usage analysis.
/// Populated by `CheckerContext` during type checking, consumed by `UsageAnalyzer`.
pub def_to_symbol: FxHashMap<tsz_solver::DefId, SymbolId>,
/// Cache for control flow analysis results.
/// Key: (`FlowNodeId`, `SymbolId`, `InitialTypeId`) -> `NarrowedTypeId`
pub flow_analysis_cache:
FxHashMap<(tsz_binder::FlowNodeId, tsz_binder::SymbolId, TypeId), TypeId>,
/// Maps class instance `TypeIds` to their class declaration `NodeIndex`.
/// Used by `get_class_decl_from_type` to correctly identify the class
/// for derived classes that have no private/protected members.
pub class_instance_type_to_decl: FxHashMap<TypeId, NodeIndex>,
/// Forward cache: class declaration `NodeIndex` -> computed instance `TypeId`.
/// Avoids recomputing the full class instance type on every member check.
pub class_instance_type_cache: FxHashMap<NodeIndex, TypeId>,
/// Forward cache: class declaration `NodeIndex` -> computed constructor `TypeId`.
/// Avoids recomputing constructor shape/inheritance on repeated class queries.
pub class_constructor_type_cache: FxHashMap<NodeIndex, TypeId>,
/// Set of import specifier nodes that should be elided from JavaScript output.
/// These are imports that reference type-only declarations (interfaces, type aliases).
pub type_only_nodes: FxHashSet<NodeIndex>,
}
impl TypeCache {
/// Invalidate cached symbol types that depend on the provided roots.
/// Returns the number of affected symbols.
pub fn invalidate_symbols(&mut self, roots: &[SymbolId]) -> usize {
if roots.is_empty() {
return 0;
}
let mut reverse: FxHashMap<SymbolId, Vec<SymbolId>> = FxHashMap::default();
for (symbol, deps) in &self.symbol_dependencies {
for dep in deps {
reverse.entry(*dep).or_default().push(*symbol);
}
}
let mut affected: FxHashSet<SymbolId> = FxHashSet::default();
let mut pending = VecDeque::new();
for &root in roots {
if affected.insert(root) {
pending.push_back(root);
}
}
while let Some(sym_id) = pending.pop_front() {
if let Some(dependents) = reverse.get(&sym_id) {
for &dependent in dependents {
if affected.insert(dependent) {
pending.push_back(dependent);
}
}
}
}
for sym_id in &affected {
self.symbol_types.remove(sym_id);
self.symbol_instance_types.remove(sym_id);
self.symbol_dependencies.remove(sym_id);
}
self.node_types.clear();
self.class_instance_type_cache.clear();
self.class_constructor_type_cache.clear();
self.class_instance_type_to_decl.clear();
affected.len()
}
/// Merge another `TypeCache` into this one.
/// Used to accumulate type information from multiple file checks for declaration emit.
pub fn merge(&mut self, other: Self) {
self.symbol_types.extend(other.symbol_types);
self.symbol_instance_types
.extend(other.symbol_instance_types);
self.node_types.extend(other.node_types);
self.class_instance_type_to_decl
.extend(other.class_instance_type_to_decl);
self.class_instance_type_cache
.extend(other.class_instance_type_cache);
self.class_constructor_type_cache
.extend(other.class_constructor_type_cache);
self.type_only_nodes.extend(other.type_only_nodes);
// Merge symbol dependencies sets
for (sym, deps) in other.symbol_dependencies {
self.symbol_dependencies
.entry(sym)
.or_default()
.extend(deps);
}
// Merge def_to_symbol mapping
self.def_to_symbol.extend(other.def_to_symbol);
}
}
#[cfg(test)]
mod tests {
use super::TypeCache;
use rustc_hash::{FxHashMap, FxHashSet};
use tsz_binder::SymbolId;
use tsz_parser::parser::NodeIndex;
use tsz_solver::TypeId;
fn empty_cache() -> TypeCache {
TypeCache {
symbol_types: FxHashMap::default(),
symbol_instance_types: FxHashMap::default(),
node_types: FxHashMap::default(),
symbol_dependencies: FxHashMap::default(),
def_to_symbol: FxHashMap::default(),
flow_analysis_cache: FxHashMap::default(),
class_instance_type_to_decl: FxHashMap::default(),
class_instance_type_cache: FxHashMap::default(),
class_constructor_type_cache: FxHashMap::default(),
type_only_nodes: FxHashSet::default(),
}
}
#[test]
fn type_cache_merge_keeps_constructor_type_cache() {
let mut lhs = empty_cache();
let mut rhs = empty_cache();
rhs.class_constructor_type_cache
.insert(NodeIndex(42), TypeId::STRING);
lhs.merge(rhs);
assert_eq!(
lhs.class_constructor_type_cache.get(&NodeIndex(42)),
Some(&TypeId::STRING)
);
}
#[test]
fn type_cache_merge_keeps_error_class_type_cache_entries() {
let mut lhs = empty_cache();
let mut rhs = empty_cache();
rhs.class_instance_type_cache
.insert(NodeIndex(10), TypeId::ERROR);
rhs.class_constructor_type_cache
.insert(NodeIndex(11), TypeId::ERROR);
lhs.merge(rhs);
assert_eq!(
lhs.class_instance_type_cache.get(&NodeIndex(10)),
Some(&TypeId::ERROR)
);
assert_eq!(
lhs.class_constructor_type_cache.get(&NodeIndex(11)),
Some(&TypeId::ERROR)
);
}
#[test]
fn invalidate_symbols_clears_class_type_caches() {
let mut cache = empty_cache();
let sym = SymbolId(7);
cache
.symbol_dependencies
.insert(sym, FxHashSet::<SymbolId>::default());
cache
.class_instance_type_cache
.insert(NodeIndex(1), TypeId::NUMBER);
cache
.class_constructor_type_cache
.insert(NodeIndex(2), TypeId::STRING);
cache
.class_instance_type_to_decl
.insert(TypeId::BOOLEAN, NodeIndex(3));
let affected = cache.invalidate_symbols(&[sym]);
assert_eq!(affected, 1);
assert!(cache.class_instance_type_cache.is_empty());
assert!(cache.class_constructor_type_cache.is_empty());
assert!(cache.class_instance_type_to_decl.is_empty());
}
}
/// Info about a symbol that came from destructuring a union type.
/// Info about a symbol that came from destructuring a union type.
/// Used for correlated discriminant narrowing: when `const { data, isSuccess } = getResult()`,
/// narrowing `isSuccess` should also narrow `data`.
#[derive(Clone, Debug)]
pub struct DestructuredBindingInfo {
/// The source type of the entire destructured expression (the union)
pub source_type: TypeId,
/// The property name that this symbol corresponds to (for object patterns)
pub property_name: String,
/// The element index for array/tuple patterns (`u32::MAX` if object pattern)
pub element_index: u32,
/// The binding group ID — all symbols from the same destructuring share this
pub group_id: u32,
/// Whether this is a const binding (only const bindings support correlated narrowing)
pub is_const: bool,
}
/// Shared state for type checking.
pub struct CheckerContext<'a> {
/// The `NodeArena` containing the AST.
pub arena: &'a NodeArena,
/// The binder state with symbols.
pub binder: &'a BinderState,
/// Query database for type interning and memoized type operations.
/// Supports both `TypeInterner` (via trait upcasting) and `QueryCache`.
pub types: &'a dyn QueryDatabase,
/// Current file name.
pub file_name: String,
/// Compiler options for type checking.
pub compiler_options: CheckerOptions,
/// Whether `noImplicitOverride` diagnostics are enabled for this source file.
pub no_implicit_override: bool,
/// Whether unresolved import diagnostics should be emitted by the checker.
/// The CLI driver handles module resolution in multi-file mode.
///
/// Checker invariant: when driver-provided resolution context is available,
/// checker should consume that context and avoid ad-hoc module-existence inference.
pub report_unresolved_imports: bool,
/// Tracking the current computed property name node for TS2467
pub checking_computed_property_name: Option<NodeIndex>,
/// Count of spelling suggestions (TS2552) emitted to limit output size.
pub spelling_suggestions_emitted: u32,
// --- Caches ---
/// Cached types for symbols.
pub symbol_types: FxHashMap<SymbolId, TypeId>,
/// Cached instance types for class symbols (for TYPE position).
/// Distinguishes from `symbol_types` which holds constructor types for VALUE position.
pub symbol_instance_types: FxHashMap<SymbolId, TypeId>,
/// Cached types for variable declarations (used for TS2403 checks).
pub var_decl_types: FxHashMap<SymbolId, TypeId>,
/// Cache for `resolve_lib_type_by_name` results.
/// Keyed by type name and stores both hits (`Some(TypeId)`) and misses (`None`).
pub lib_type_resolution_cache: FxHashMap<String, Option<TypeId>>,
/// Cached types for nodes.
pub node_types: FxHashMap<u32, TypeId>,
/// Cached type environment for resolving Ref types during assignability checks.
pub type_environment: Rc<RefCell<TypeEnvironment>>,
/// Recursion guard for application evaluation.
pub application_eval_set: FxHashSet<TypeId>,
/// Recursion guard for mapped type evaluation with resolution.
pub mapped_eval_set: FxHashSet<TypeId>,
/// Cache for control flow analysis results.
/// Key: (`FlowNodeId`, `SymbolId`, `InitialTypeId`) -> `NarrowedTypeId`
/// Prevents re-traversing the flow graph for the same symbol/flow combination.
/// Fixes performance regression on binaryArithmeticControlFlowGraphNotTooLarge.ts
/// where each operand in a + b + c was triggering fresh graph traversals.
pub flow_analysis_cache:
RefCell<FxHashMap<(tsz_binder::FlowNodeId, tsz_binder::SymbolId, TypeId), TypeId>>,
/// Reusable buffers for flow analysis to avoid frequent heap allocations in `check_flow`.
pub flow_worklist: RefCell<VecDeque<(tsz_binder::FlowNodeId, TypeId)>>,
pub flow_in_worklist: RefCell<FxHashSet<tsz_binder::FlowNodeId>>,
pub flow_visited: RefCell<FxHashSet<tsz_binder::FlowNodeId>>,
pub flow_results: RefCell<FxHashMap<tsz_binder::FlowNodeId, TypeId>>,
/// Shared cache for narrowing operations (type resolution, property lookup).
/// Reused across flow analysis passes to prevent O(N^2) behavior in CFA chains.
pub narrowing_cache: tsz_solver::NarrowingCache,
/// Cache for switch-reference relevance checks.
/// Reused across `FlowAnalyzer` instances within a single file check.
pub flow_switch_reference_cache: RefCell<FxHashMap<(u32, u32), bool>>,
/// Cache numeric atom conversions during flow analysis.
/// Reused across `FlowAnalyzer` instances within a single file check.
pub flow_numeric_atom_cache: RefCell<FxHashMap<u64, Atom>>,
/// Shared reference-equivalence cache used by flow narrowing.
/// Key: (`node_a`, `node_b`) -> whether they reference the same symbol/property chain.
/// Reused across `FlowAnalyzer` instances within a single file check.
pub flow_reference_match_cache: RefCell<FxHashMap<(u32, u32), bool>>,
/// Instantiated type predicates from generic call resolutions.
/// Keyed by call expression node index. Used by flow narrowing to get
/// predicates with inferred type arguments applied (e.g., `T` -> `string`).
pub call_type_predicates: crate::control_flow::CallPredicateMap,
/// `TypeIds` whose application/lazy symbol references are fully resolved in `type_env`.
/// This avoids repeated deep traversals in assignability hot paths.
pub application_symbols_resolved: FxHashSet<TypeId>,
/// Recursion guard for application symbol resolution traversal.
pub application_symbols_resolution_set: FxHashSet<TypeId>,
/// Maps class instance `TypeIds` to their class declaration `NodeIndex`.
/// Used by `get_class_decl_from_type` to correctly identify the class
/// for derived classes that have no private/protected members (and thus no brand).
/// Populated by `get_class_instance_type_inner` when creating class instance types.
pub class_instance_type_to_decl: FxHashMap<TypeId, NodeIndex>,
/// Forward cache: class declaration `NodeIndex` -> computed instance `TypeId`.
/// Avoids recomputing the full class instance type on every member check.
pub class_instance_type_cache: FxHashMap<NodeIndex, TypeId>,
/// Forward cache: class declaration `NodeIndex` -> computed constructor `TypeId`.
/// Avoids recomputing constructor inheritance checks in class-heavy programs.
pub class_constructor_type_cache: FxHashMap<NodeIndex, TypeId>,
/// Cache class symbol -> class declaration node lookups used in inheritance queries.
/// Stores misses as `None` to avoid repeated declaration scans on hot paths.
pub class_symbol_to_decl_cache: RefCell<FxHashMap<SymbolId, Option<NodeIndex>>>,
/// Cache heritage expression node -> resolved symbol lookups.
/// Stores misses as `None` to avoid repeating namespace/alias walks across
/// class and interface inheritance passes.
pub heritage_symbol_cache: RefCell<FxHashMap<NodeIndex, Option<SymbolId>>>,
/// Cache constructor type fallback for heritage expressions with no explicit type args.
/// Avoids repeatedly re-evaluating anonymous/complex `extends` expressions.
pub base_constructor_expr_cache: RefCell<FxHashMap<NodeIndex, Option<TypeId>>>,
/// Cache instance type fallback for heritage expressions with no explicit type args.
/// Reuses constructor->instance fallback work across class instance checks.
pub base_instance_expr_cache: RefCell<FxHashMap<NodeIndex, Option<TypeId>>>,
/// Cache of non-class `TypeId`s for `get_class_decl_from_type`.
/// Avoids repeating private-brand scans on hot miss paths.
pub class_decl_miss_cache: RefCell<FxHashSet<TypeId>>,
/// Cache for JSX intrinsic element evaluated props types.
/// Maps (`intrinsic_elements_type`, `tag_atom`) -> `evaluated_props_type`.
/// Avoids re-evaluating `JSX.IntrinsicElements['div']` for every `<div>` element.
pub jsx_intrinsic_props_cache: FxHashMap<(TypeId, tsz_common::interner::Atom), TypeId>,
/// Symbol dependency graph (symbol -> referenced symbols).
pub symbol_dependencies: FxHashMap<SymbolId, FxHashSet<SymbolId>>,
/// Stack of symbols currently being evaluated for dependency tracking.
pub symbol_dependency_stack: Vec<SymbolId>,
/// Set of symbols that have been referenced (used for TS6133 unused checking).
/// Uses `RefCell` to allow tracking from &self methods (e.g., `resolve_identifier_symbol`).
pub referenced_symbols: std::cell::RefCell<FxHashSet<SymbolId>>,
/// Set of symbols written to (assignment targets).
/// Tracked separately from references for flow/usage checks.
pub written_symbols: std::cell::RefCell<FxHashSet<SymbolId>>,
// --- Destructured Binding Tracking ---
/// Maps destructured const binding symbols to their source union type info.
/// Used for correlated discriminant narrowing (TS 4.6+ feature).
pub destructured_bindings: FxHashMap<SymbolId, DestructuredBindingInfo>,
/// Counter for generating unique binding group IDs.
pub next_binding_group_id: u32,
// --- Diagnostics ---
/// Whether the source file has parse errors.
/// Set by the driver before type checking to suppress noise-sensitive diagnostics
/// (e.g., TS2695 for comma operators in malformed JSON files).
pub has_parse_errors: bool,
/// Whether the source file has real syntax errors (not just conflict markers TS1185).
/// Used to suppress TS2304 only when there are genuine parse errors.
pub has_syntax_parse_errors: bool,
/// Positions (start) of syntax parse errors (excluding conflict markers TS1185).
/// Used for targeted TS2304 suppression near parse error sites.
pub syntax_parse_error_positions: Vec<u32>,
/// Whether the file has "real" syntax errors (TS1005, TS1109, TS1127, TS1128,
/// TS1135, etc.) that indicate actual parse failure, as opposed to grammar
/// checks (TS1100, TS1173, TS1212, etc.) which are semantic errors emitted
/// during parsing. Used for broader TS2304 suppression matching tsc behavior.
pub has_real_syntax_errors: bool,
/// Diagnostics produced during type checking.
pub diagnostics: Vec<Diagnostic>,
/// Set of already-emitted diagnostics (start, code) for deduplication.
pub emitted_diagnostics: FxHashSet<(u32, u32)>,
/// Set of modules that have already had TS2307 emitted (prevents duplicate emissions).
pub modules_with_ts2307_emitted: FxHashSet<String>,
// --- Recursion Guards ---
/// Stack of symbols being resolved.
pub symbol_resolution_stack: Vec<SymbolId>,
/// O(1) lookup set for symbol resolution stack.
pub symbol_resolution_set: FxHashSet<SymbolId>,
/// O(1) lookup set for class instance type resolution to avoid recursion.
pub class_instance_resolution_set: FxHashSet<SymbolId>,
/// O(1) lookup set for class constructor type resolution to avoid recursion.
pub class_constructor_resolution_set: FxHashSet<SymbolId>,
/// Deferred TS7034 candidates: non-ambient variables with no annotation, no init, and type ANY.
/// Maps symbol ID → declaration name node. Consumed when a capture is detected.
pub pending_implicit_any_vars: FxHashMap<SymbolId, NodeIndex>,
/// Variables that have already had TS7034 emitted.
/// Used to emit TS7005 on subsequent usages.
pub reported_implicit_any_vars: FxHashSet<SymbolId>,
/// Inheritance graph tracking class/interface relationships
pub inheritance_graph: tsz_solver::classes::inheritance::InheritanceGraph,
/// Stack of nodes being resolved.
pub node_resolution_stack: Vec<NodeIndex>,
/// O(1) lookup set for node resolution stack.
pub node_resolution_set: FxHashSet<NodeIndex>,
/// Set of class declaration nodes currently being checked.
/// Used to prevent infinite recursion in `check_class_declaration` when
/// class checking triggers type resolution that circles back to the same class.
pub checking_classes: FxHashSet<NodeIndex>,
/// Set of class declaration nodes that have been fully checked.
/// Used to avoid re-checking the same class multiple times (e.g. once via
/// dependency resolution and once via the main source file traversal).
pub checked_classes: FxHashSet<NodeIndex>,
// --- Scopes & Context ---
/// Current type parameter scope.
pub type_parameter_scope: FxHashMap<String, TypeId>,
/// Temporary scope for value parameters visible to `typeof` in return type annotations.
/// Populated during signature processing so `typeof paramName` in return types
/// can resolve to the parameter's type.
pub typeof_param_scope: FxHashMap<String, TypeId>,
/// Contextual type for expression being checked.
pub contextual_type: Option<TypeId>,
/// Whether we're in the statement checking phase (vs type environment building).
/// During `build_type_environment`, closure parameter types may not have contextual types
/// yet, so TS7006 should be deferred until the checking phase.
pub is_checking_statements: bool,
/// Whether the current file is a declaration file (.d.ts/.d.tsx/.d.mts/.d.cts).
/// Used to suppress statement-specific errors (TS1105, TS1108, TS1104) in favor of TS1036.
pub is_in_ambient_declaration_file: bool,
/// Whether we are currently evaluating the LHS of a destructuring assignment.
/// Used to suppress TS1117 (duplicate property) checks in object patterns.
pub in_destructuring_target: bool,
/// Whether to skip flow narrowing when computing types.
/// Used in assignment target type resolution to get declared types instead of narrowed types.
/// When checking `foo[x] = 1` after `if (foo[x] === undefined)`, we need the declared type
/// (e.g., `number | undefined`) not the narrowed type (e.g., `undefined`).
pub skip_flow_narrowing: bool,
/// Current depth of recursive type instantiation.
pub instantiation_depth: RefCell<u32>,
/// Whether type instantiation depth was exceeded (for TS2589 emission).
pub depth_exceeded: RefCell<bool>,
/// General recursion depth counter for type checking.
/// Prevents stack overflow by bailing out when depth exceeds the limit.
pub recursion_depth: RefCell<tsz_solver::recursion::DepthCounter>,
/// Current depth of call expression resolution.
pub call_depth: RefCell<tsz_solver::recursion::DepthCounter>,
/// Stack of expected return types for functions.
pub return_type_stack: Vec<TypeId>,
/// Stack of contextual yield types for generator functions.
/// Used to contextually type yield expressions (prevents false TS7006).
pub yield_type_stack: Vec<Option<TypeId>>,
/// Stack of current `this` types for class member bodies.
pub this_type_stack: Vec<TypeId>,
/// Current enclosing class info.
pub enclosing_class: Option<EnclosingClassInfo>,
/// Type environment for symbol resolution with type parameters.
/// Used by the evaluator to expand Application types.
pub type_env: RefCell<TypeEnvironment>,
// --- DefId Migration Infrastructure ---
/// Storage for type definitions (interfaces, classes, type aliases).
/// Part of the `DefId` migration to decouple Solver from Binder.
pub definition_store: Arc<DefinitionStore>,
/// Mapping from Binder `SymbolId` to Solver `DefId`.
/// Used during migration to avoid creating duplicate `DefIds` for the same symbol.
/// Wrapped in `RefCell` to allow mutation through shared references (for use in Fn closures).
pub symbol_to_def: RefCell<FxHashMap<SymbolId, DefId>>,
/// Reverse mapping from Solver `DefId` to Binder `SymbolId`.
/// Used to look up binder symbols from DefId-based types (e.g., namespace exports).
/// Wrapped in `RefCell` to allow mutation through shared references (for use in Fn closures).
pub def_to_symbol: RefCell<FxHashMap<DefId, SymbolId>>,
/// Type parameters for `DefIds` (used for type aliases, classes, interfaces).
/// Enables the Solver to expand Application(Lazy(DefId), Args) by providing
/// the type parameters needed for generic substitution.
/// Wrapped in `RefCell` to allow mutation through shared references.
pub def_type_params: RefCell<FxHashMap<DefId, Vec<tsz_solver::TypeParamInfo>>>,
/// `DefIds` known to have no type parameters.
/// This avoids repeated cross-arena lookups for non-generic symbols.
pub def_no_type_params: RefCell<FxHashSet<DefId>>,
/// Abstract constructor types (`TypeIds`) produced for abstract classes.
pub abstract_constructor_types: FxHashSet<TypeId>,
/// Protected constructor types (`TypeIds`) produced for protected constructors.
pub protected_constructor_types: FxHashSet<TypeId>,
/// Private constructor types (`TypeIds`) produced for private constructors.
pub private_constructor_types: FxHashSet<TypeId>,
/// Maps cross-file `SymbolIds` to their source file index.
/// Populated by `resolve_cross_file_export/resolve_cross_file_namespace_exports`
/// so `delegate_cross_arena_symbol_resolution` can find the correct arena.
pub cross_file_symbol_targets: RefCell<FxHashMap<SymbolId, usize>>,
/// All arenas for cross-file resolution (indexed by `file_idx` from `Symbol.decl_file_idx`).
/// Set during multi-file type checking to allow resolving declarations across files.
pub all_arenas: Option<Arc<Vec<Arc<NodeArena>>>>,
/// All binders for cross-file resolution (indexed by `file_idx`).
/// Enables looking up exported symbols from other files during import resolution.
pub all_binders: Option<Arc<Vec<Arc<BinderState>>>>,
/// Resolved module paths map: (`source_file_idx`, specifier) -> `target_file_idx`.
/// Used by `get_type_of_symbol` to resolve imports to their target file and symbol.
///
/// Key invariant: all specifier lookups should use
/// `module_resolution::module_specifier_candidates` for canonical variants.
pub resolved_module_paths: Option<Arc<ResolvedModulePathMap>>,
/// Current file index in multi-file mode (index into `all_arenas/all_binders`).
/// Used with `resolved_module_paths` to look up cross-file imports.
pub current_file_idx: usize,
/// Resolved module specifiers for this file (multi-file CLI mode).
pub resolved_modules: Option<FxHashSet<String>>,
/// Track value exports declared in module augmentations for duplicate detection.
/// Keyed by a canonical module key (resolved file index or specifier).
pub module_augmentation_value_decls: FxHashMap<String, FxHashMap<String, NodeIndex>>,
/// Per-file cache of `is_external_module` values to preserve state across files.
/// Maps file path -> whether that file is an external module (has imports/exports).
/// This prevents state corruption when binding multiple files sequentially.
pub is_external_module_by_file: Option<Arc<FxHashMap<String, bool>>>,
/// Map of resolution errors: (`source_file_idx`, specifier) -> Error details.
/// Populated by the driver when `ModuleResolver` returns a specific error.
/// Contains structured error information (code, message) for TS2834, TS2835, TS2792, etc.
///
/// Diagnostic-source invariant: module-not-found-family code/message selection
/// should come from resolver outcomes when present.
pub resolved_module_errors: Option<Arc<ResolvedModuleErrorMap>>,
/// Import resolution stack for circular import detection.
/// Tracks the chain of modules being resolved to detect circular dependencies.
pub import_resolution_stack: Vec<String>,
/// Set of import specifier nodes that should be elided from JavaScript output.
/// These are imports that reference type-only declarations (interfaces, type aliases).
/// Populated during type checking and consulted by the emitter.
pub type_only_nodes: FxHashSet<NodeIndex>,
/// Symbol resolution depth counter for preventing stack overflow.
/// Tracks how many nested `get_type_of_symbol` calls we've made.
pub symbol_resolution_depth: Cell<u32>,
/// Maximum symbol resolution depth before we give up (prevents stack overflow).
pub max_symbol_resolution_depth: u32,
/// Lib file contexts for global type resolution (lib.es5.d.ts, lib.dom.d.ts, etc.).
/// Each entry is a (arena, binder) pair from a pre-parsed lib file.
/// Used as a fallback when resolving type references not found in the main file.
pub lib_contexts: Vec<LibContext>,
/// Number of actual lib files loaded (not including user files).
/// Used by `has_lib_loaded()` to correctly determine if standard library is available.
/// This is separate from `lib_contexts.len()` because `lib_contexts` may also include
/// user file contexts for cross-file type resolution in multi-file tests.
pub actual_lib_file_count: usize,
/// Control flow graph for definite assignment analysis and type narrowing.
/// This is built during the binding phase and used by the checker.
pub flow_graph: Option<FlowGraph<'a>>,
/// Async context depth - tracks nesting of async functions.
/// Used to check if await expressions are within async context (TS1359).
pub async_depth: u32,
/// Stack of symbols being resolved via typeof to detect cycles.
/// Prevents infinite loops in typeof X where X's type computation depends on typeof X.
pub typeof_resolution_stack: RefCell<FxHashSet<u32>>,
/// Closure depth - tracks nesting of function expressions, arrow functions, and method expressions.
/// Used to apply Rule #42: CFA Invalidation in Closures.
/// When > 0, mutable variables (let/var) lose narrowing in closures.
pub inside_closure_depth: u32,
/// When true, we're inside a const assertion (as const) and should preserve literal types.
/// This prevents widening of literal types in object/array literals.
pub in_const_assertion: bool,
/// When true, preserve literal types instead of widening.
/// Set during evaluation of compound expression branches (conditional `?:`,
/// logical `||`/`&&`/`??`) so that `const x = cond ? "a" : "b"` infers
/// `"a" | "b"` instead of `string`.
pub preserve_literal_types: bool,
// --- Control Flow Validation ---
/// Depth of nested iteration statements (for/while/do-while).
/// Used to validate break/continue statements.
pub iteration_depth: u32,
/// Depth of nested switch statements.
/// Used to validate break statements (break is valid in switch).
pub switch_depth: u32,
/// Depth of nested functions.
/// Used to detect when labeled jumps cross function boundaries.
pub function_depth: u32,
/// Track whether current code path is syntactically unreachable.
pub is_unreachable: bool,
/// Track whether we have already reported an unreachable error in this block/scope.
pub has_reported_unreachable: bool,
/// Stack of labels in scope.
/// Each entry contains (`label_name`, `is_iteration`, `function_depth_when_defined`).
/// Used for labeled break/continue validation.
pub label_stack: Vec<LabelInfo>,
/// Whether there was a loop/switch in an outer function scope.
/// Used to determine TS1107 vs TS1105 for unlabeled break statements.
/// When true, an unlabeled break inside a function should emit TS1107,
/// because the break is "trying" to exit the outer loop but can't cross
/// the function boundary.
pub had_outer_loop: bool,
/// When true, suppress definite assignment errors (TS2454).
/// This is used during return type inference to avoid duplicate errors.
/// The function body is checked twice: once for return type inference
/// and once for actual statement checking. We only want to emit TS2454
/// errors during the second pass.
pub suppress_definite_assignment_errors: bool,
/// Set to true during function body checking when the body references `arguments`.
/// Used in JS files to add an implicit rest parameter, allowing extra arguments.
/// Save/restore pattern ensures correct handling across nested functions.
pub js_body_uses_arguments: bool,
/// Track which (node, symbol) pairs have already emitted TS2454 errors
/// to avoid duplicate errors when the same usage is checked multiple times.
/// Key: (`node_position`, `symbol_id`)
pub emitted_ts2454_errors: FxHashSet<(u32, SymbolId)>,
/// Fuel counter for type resolution operations.
/// Decremented on each type resolution to prevent timeout on pathological types.
/// When exhausted, type resolution returns ERROR to prevent infinite loops.
pub type_resolution_fuel: RefCell<u32>,
/// Whether type resolution fuel was exhausted (for timeout detection).
pub fuel_exhausted: RefCell<bool>,
// NOTE: Freshness is now tracked on the TypeId via ObjectFlags.
// This fixes the "Zombie Freshness" bug by interning fresh vs non-fresh
// object shapes distinctly.
}
/// Context for a lib file (arena + binder) for global type resolution.
#[derive(Clone, Debug)]
pub struct LibContext {
/// The AST arena for this lib file.
pub arena: Arc<NodeArena>,
/// The binder state with symbols from this lib file.
pub binder: Arc<BinderState>,
}
impl<'a> CheckerContext<'a> {
/// Set lib contexts for global type resolution.
/// Note: `lib_contexts` may include both actual lib files AND user files for cross-file
/// resolution. Use `set_actual_lib_file_count()` to track how many are actual lib files.
pub fn set_lib_contexts(&mut self, lib_contexts: Vec<LibContext>) {
self.lib_contexts = lib_contexts;
}
/// Set the count of actual lib files loaded (not including user files).
/// This is used by `has_lib_loaded()` to correctly determine if standard library is available.
pub const fn set_actual_lib_file_count(&mut self, count: usize) {
self.actual_lib_file_count = count;
}
/// Set all arenas for cross-file resolution.
pub fn set_all_arenas(&mut self, arenas: Arc<Vec<Arc<NodeArena>>>) {
self.all_arenas = Some(arenas);
}
/// Set all binders for cross-file resolution.
pub fn set_all_binders(&mut self, binders: Arc<Vec<Arc<BinderState>>>) {
self.all_binders = Some(binders);
}
/// Set resolved module paths map for cross-file import resolution.
pub fn set_resolved_module_paths(&mut self, paths: Arc<FxHashMap<(usize, String), usize>>) {
self.resolved_module_paths = Some(paths);
}
/// Set resolved module specifiers (module names that exist in the project).
/// Used to suppress TS2307 errors for known modules.
pub fn set_resolved_modules(&mut self, modules: FxHashSet<String>) {
self.resolved_modules = Some(modules);
}
/// Set resolved module errors map for cross-file import resolution.
/// Populated by the driver when `ModuleResolver` returns specific errors (TS2834, TS2835, TS2792, etc.).
pub fn set_resolved_module_errors(
&mut self,
errors: Arc<FxHashMap<(usize, String), ResolutionError>>,
) {
self.resolved_module_errors = Some(errors);
}
/// Get the resolution error for a specifier, if any.
/// Returns the specific error (TS2834, TS2835, TS2792, etc.) if the module resolution failed with a known error.
pub fn get_resolution_error(&self, specifier: &str) -> Option<&ResolutionError> {
let errors = self.resolved_module_errors.as_ref()?;
for candidate in module_specifier_candidates(specifier) {
if let Some(error) = errors.get(&(self.current_file_idx, candidate)) {
return Some(error);
}
}
None
}
/// Set the current file index.
pub const fn set_current_file_idx(&mut self, idx: usize) {
self.current_file_idx = idx;
}
/// Get the arena for a specific file index.
/// Returns the current arena if `file_idx` is `u32::MAX` (single-file mode).
pub fn get_arena_for_file(&self, file_idx: u32) -> &NodeArena {
if file_idx == u32::MAX {
return self.arena;
}
if let Some(arenas) = self.all_arenas.as_ref()
&& let Some(arena) = arenas.get(file_idx as usize)
{
return arena.as_ref();
}
self.arena
}
/// Get the binder for a specific file index.
/// Returns None if `file_idx` is out of bounds or `all_binders` is not set.
pub fn get_binder_for_file(&self, file_idx: usize) -> Option<&BinderState> {
self.all_binders
.as_ref()
.and_then(|binders| binders.get(file_idx))
.map(Arc::as_ref)
}
/// Resolve an import specifier to its target file index.
/// Uses the `resolved_module_paths` map populated by the driver.
/// Returns None if the import cannot be resolved (e.g., external module).
pub fn resolve_import_target(&self, specifier: &str) -> Option<usize> {
self.resolve_import_target_from_file(self.current_file_idx, specifier)
}
/// Resolve an import specifier from a specific file to its target file index.
/// Like `resolve_import_target` but for any source file, not just the current one.
pub fn resolve_import_target_from_file(
&self,
source_file_idx: usize,
specifier: &str,
) -> Option<usize> {
let paths = self.resolved_module_paths.as_ref()?;
for candidate in module_specifier_candidates(specifier) {
if let Some(target_idx) = paths.get(&(source_file_idx, candidate)) {
return Some(*target_idx);
}
}
None
}
/// Returns true if an augmentation target resolves to an `export =` value without
/// namespace/module shape (TS2671/TS2649 cases).
pub fn module_resolves_to_non_module_entity(&self, module_specifier: &str) -> bool {
let candidates = module_specifier_candidates(module_specifier);
let lookup_cached = |binder: &BinderState, key: &str| {
binder.module_export_equals_non_module.get(key).copied()
};
if let Some(target_idx) = self.resolve_import_target(module_specifier)
&& let Some(target_binder) = self.get_binder_for_file(target_idx)
{
for candidate in &candidates {
if let Some(non_module) = lookup_cached(target_binder, candidate) {
return non_module;
}
}
}
for candidate in &candidates {
if let Some(non_module) = lookup_cached(self.binder, candidate) {
return non_module;
}
}
if let Some(all_binders) = self.all_binders.as_ref() {
for binder in all_binders.iter() {
for candidate in &candidates {
if let Some(non_module) = lookup_cached(binder, candidate) {
return non_module;
}
}
}
}
let export_equals_is_non_module = |binder: &BinderState,
exports: &tsz_binder::SymbolTable|
-> Option<bool> {
let export_equals_sym_id = exports.get("export=")?;
let has_named_exports = exports.iter().any(|(name, _)| name != "export=");
tracing::trace!(
module_specifier = module_specifier,
export_equals_sym_id = export_equals_sym_id.0,
has_named_exports,
"module_resolves_to_non_module_entity: checking exports table"
);
let mut candidate_symbols = Vec::with_capacity(2);
if let Some(sym) = binder.get_symbol(export_equals_sym_id) {
candidate_symbols.push((binder, sym));
} else if let Some(sym) = self.binder.get_symbol(export_equals_sym_id) {
candidate_symbols.push((self.binder, sym));
} else if let Some(all_binders) = self.all_binders.as_ref() {
for other in all_binders.iter() {
if let Some(sym) = other.get_symbol(export_equals_sym_id) {
candidate_symbols.push((other.as_ref(), sym));
break;
}
}
}
let has_namespace_shape = |sym_binder: &BinderState, sym: &tsz_binder::Symbol| {
let has_namespace_decl = sym.declarations.iter().any(|decl_idx| {
if decl_idx.is_none() {
return false;
}
sym_binder
.declaration_arenas
.get(&(sym.id, *decl_idx))
.and_then(|v| v.first())
.is_some_and(|arena| {
let Some(node) = arena.get(*decl_idx) else {
return false;
};
if node.kind != syntax_kind_ext::MODULE_DECLARATION {
return false;
}
let Some(module_decl) = arena.get_module(node) else {
return false;
};
if module_decl.body.is_none() {
return false;
}
let Some(body_node) = arena.get(module_decl.body) else {
return false;
};
if body_node.kind == syntax_kind_ext::MODULE_BLOCK
&& let Some(block) = arena.get_module_block(body_node)
&& let Some(statements) = block.statements.as_ref()
{
return !statements.nodes.is_empty();
}
true
})
});
sym.exports.as_ref().is_some_and(|tbl| !tbl.is_empty())
|| sym.members.as_ref().is_some_and(|tbl| !tbl.is_empty())
|| has_namespace_decl
};
let export_assignment_target_name =
|sym_binder: &BinderState, sym: &tsz_binder::Symbol| -> Option<String> {
let mut decls = sym.declarations.clone();
if sym.value_declaration.is_some() {
decls.push(sym.value_declaration);
}
for decl_idx in decls {
if decl_idx.is_none() {
continue;
}
let Some(arena) = sym_binder
.declaration_arenas
.get(&(sym.id, decl_idx))
.and_then(|v| v.first())
else {
continue;
};
let Some(node) = arena.get(decl_idx) else {
continue;
};
if node.kind != syntax_kind_ext::EXPORT_ASSIGNMENT {
continue;
}
let Some(assign) = arena.get_export_assignment(node) else {
continue;
};
if !assign.is_export_equals {
continue;
}
let Some(expr_node) = arena.get(assign.expression) else {
continue;
};
if let Some(id) = arena.get_identifier(expr_node) {
return Some(id.escaped_text.clone());
}
}
None
};
let symbol_has_namespace_shape =
candidate_symbols.into_iter().any(|(sym_binder, sym)| {
tracing::trace!(
module_specifier = module_specifier,
symbol_name = sym.escaped_name.as_str(),
symbol_flags = sym.flags,
"module_resolves_to_non_module_entity: candidate symbol"
);
if has_namespace_shape(sym_binder, sym) {
return true;
}
if sym_binder
.get_symbols()
.find_all_by_name(&sym.escaped_name)
.into_iter()
.filter_map(|candidate_id| sym_binder.get_symbol(candidate_id))
.any(|candidate| has_namespace_shape(sym_binder, candidate))
{
return true;
}
let Some(target_name) = export_assignment_target_name(sym_binder, sym) else {
return false;
};
tracing::trace!(
module_specifier = module_specifier,
target_name = target_name.as_str(),
"module_resolves_to_non_module_entity: export assignment target"
);
sym_binder
.get_symbols()
.find_all_by_name(&target_name)
.into_iter()
.filter_map(|target_sym_id| sym_binder.get_symbol(target_sym_id))
.any(|target_sym| has_namespace_shape(sym_binder, target_sym))
});
tracing::trace!(
module_specifier = module_specifier,
symbol_has_namespace_shape,
"module_resolves_to_non_module_entity: namespace shape computed"
);
Some(!has_named_exports && !symbol_has_namespace_shape)
};
let has_namespace_shape = |binder: &BinderState, sym: &tsz_binder::Symbol| {
let has_namespace_decl = sym.declarations.iter().any(|decl_idx| {
if decl_idx.is_none() {
return false;
}
binder
.declaration_arenas
.get(&(sym.id, *decl_idx))
.and_then(|v| v.first())
.is_some_and(|arena| {
let Some(node) = arena.get(*decl_idx) else {
return false;
};
if node.kind != syntax_kind_ext::MODULE_DECLARATION {
return false;
}
let Some(module_decl) = arena.get_module(node) else {
return false;
};
if module_decl.body.is_none() {
return false;
}
let Some(body_node) = arena.get(module_decl.body) else {
return false;
};
if body_node.kind == syntax_kind_ext::MODULE_BLOCK
&& let Some(block) = arena.get_module_block(body_node)
&& let Some(statements) = block.statements.as_ref()
{
return !statements.nodes.is_empty();
}
true
})
});
sym.exports.as_ref().is_some_and(|tbl| !tbl.is_empty())
|| sym.members.as_ref().is_some_and(|tbl| !tbl.is_empty())
|| has_namespace_decl
};
fn contains_namespace_decl_named(
arena: &NodeArena,
idx: NodeIndex,
target_name: &str,
depth: usize,
) -> bool {
if depth > 128 {
return false;
}
let Some(node) = arena.get(idx) else {
return false;
};
if node.kind == syntax_kind_ext::MODULE_DECLARATION {
let Some(module_decl) = arena.get_module(node) else {
return false;
};
if let Some(name_node) = arena.get(module_decl.name)
&& let Some(id) = arena.get_identifier(name_node)
&& id.escaped_text == target_name
{
if module_decl.body.is_none() {
return false;
}
if let Some(body_node) = arena.get(module_decl.body)
&& body_node.kind == syntax_kind_ext::MODULE_BLOCK
&& let Some(block) = arena.get_module_block(body_node)
&& let Some(stmts) = block.statements.as_ref()
{
return !stmts.nodes.is_empty();
}
return true;
}
if module_decl.body.is_some() {
return contains_namespace_decl_named(
arena,
module_decl.body,
target_name,
depth + 1,
);
}
return false;
}
if node.kind == syntax_kind_ext::MODULE_BLOCK
&& let Some(block) = arena.get_module_block(node)
&& let Some(statements) = block.statements.as_ref()
{
for &stmt in &statements.nodes {
if contains_namespace_decl_named(arena, stmt, target_name, depth + 1) {
return true;
}
}
}
false
}
fn collect_export_equals_targets(
arena: &NodeArena,
idx: NodeIndex,
out: &mut Vec<String>,
depth: usize,
) {
if depth > 128 {
return;
}
let Some(node) = arena.get(idx) else {
return;
};
if node.kind == syntax_kind_ext::EXPORT_ASSIGNMENT {
if let Some(assign) = arena.get_export_assignment(node)
&& assign.is_export_equals
&& let Some(expr_node) = arena.get(assign.expression)
&& let Some(id) = arena.get_identifier(expr_node)
{
out.push(id.escaped_text.clone());
}
return;
}
if node.kind == syntax_kind_ext::MODULE_DECLARATION {
if let Some(module_decl) = arena.get_module(node)
&& module_decl.body.is_some()
{
collect_export_equals_targets(arena, module_decl.body, out, depth + 1);
}
return;
}
if node.kind == syntax_kind_ext::MODULE_BLOCK
&& let Some(block) = arena.get_module_block(node)
&& let Some(statements) = block.statements.as_ref()
{
for &stmt in &statements.nodes {
collect_export_equals_targets(arena, stmt, out, depth + 1);
}
}
}
let export_assignment_targets_namespace_via_source =
|binder: &BinderState, arena: &NodeArena| {
for source_file in &arena.source_files {
let mut export_targets = Vec::new();
for &stmt_idx in &source_file.statements.nodes {
collect_export_equals_targets(arena, stmt_idx, &mut export_targets, 0);
}
for target_name in export_targets {
let has_matching_namespace_decl = source_file
.statements
.nodes
.iter()
.copied()
.any(|top_stmt| {
contains_namespace_decl_named(arena, top_stmt, &target_name, 0)
});
if has_matching_namespace_decl {
return true;
}
if binder
.get_symbols()
.find_all_by_name(&target_name)
.into_iter()
.filter_map(|target_id| binder.get_symbol(target_id))
.any(|target_sym| has_namespace_shape(binder, target_sym))
{
return true;
}
}
}
false
};
if let Some(target_idx) = self.resolve_import_target(module_specifier)
&& let Some(target_binder) = self.get_binder_for_file(target_idx)
{
let target_arena = self.get_arena_for_file(target_idx as u32);
for candidate in &candidates {
if let Some(exports) = target_binder.module_exports.get(candidate)
&& let Some(non_module) = export_equals_is_non_module(target_binder, exports)
{
tracing::trace!(
module_specifier = module_specifier,
candidate = candidate.as_str(),
branch = "target_specifier_key",
non_module,
"module_resolves_to_non_module_entity: branch result"
);
if non_module
&& export_assignment_targets_namespace_via_source(
target_binder,
target_arena,
)
{
tracing::trace!(
module_specifier = module_specifier,
candidate = candidate.as_str(),
branch = "target_specifier_key",
"module_resolves_to_non_module_entity: source fallback override"
);
return false;
}
return non_module;
}
}
if let Some(target_file_name) = self
.get_arena_for_file(target_idx as u32)
.source_files
.first()
.map(|sf| sf.file_name.as_str())
&& let Some(exports) = target_binder.module_exports.get(target_file_name)
&& let Some(non_module) = export_equals_is_non_module(target_binder, exports)
{
tracing::trace!(
module_specifier = module_specifier,
branch = "target_file_key",
non_module,
"module_resolves_to_non_module_entity: branch result"
);
if non_module
&& export_assignment_targets_namespace_via_source(target_binder, target_arena)
{
tracing::trace!(
module_specifier = module_specifier,
branch = "target_file_key",
"module_resolves_to_non_module_entity: source fallback override"
);
return false;
}
return non_module;
}
}
let mut saw_non_module = false;
if let Some(exports) = self.binder.module_exports.get(module_specifier)
&& let Some(non_module) = export_equals_is_non_module(self.binder, exports)
{
tracing::trace!(
module_specifier = module_specifier,
branch = "self_binder",
non_module,
"module_resolves_to_non_module_entity: branch result"
);
if non_module && export_assignment_targets_namespace_via_source(self.binder, self.arena)
{
tracing::trace!(
module_specifier = module_specifier,
branch = "self_binder",
"module_resolves_to_non_module_entity: source fallback override"
);
return false;
}
if !non_module {
return false;
}
saw_non_module = true;
}
if let Some(all_binders) = self.all_binders.as_ref() {
for (idx, binder) in all_binders.iter().enumerate() {
if let Some(exports) = binder.module_exports.get(module_specifier)
&& let Some(non_module) = export_equals_is_non_module(binder, exports)
{
tracing::trace!(
module_specifier = module_specifier,
branch = "all_binders",
binder_idx = idx,
non_module,
"module_resolves_to_non_module_entity: branch result"
);
if non_module
&& let Some(all_arenas) = self.all_arenas.as_ref()
&& let Some(arena) = all_arenas.get(idx)
&& export_assignment_targets_namespace_via_source(binder, arena.as_ref())
{
tracing::trace!(
module_specifier = module_specifier,
branch = "all_binders",
binder_idx = idx,
"module_resolves_to_non_module_entity: source fallback override"
);
return false;
}
if !non_module {
return false;
}
saw_non_module = true;
}
}
}
saw_non_module
}
/// Extract the persistent cache from this context.
/// This allows saving type checking results for future queries.
pub fn extract_cache(self) -> TypeCache {
TypeCache {
symbol_types: self.symbol_types,
symbol_instance_types: self.symbol_instance_types,
node_types: self.node_types,
symbol_dependencies: self.symbol_dependencies,
def_to_symbol: self.def_to_symbol.into_inner(),
flow_analysis_cache: self.flow_analysis_cache.into_inner(),
class_instance_type_to_decl: self.class_instance_type_to_decl,
class_instance_type_cache: self.class_instance_type_cache,
class_constructor_type_cache: self.class_constructor_type_cache,
type_only_nodes: self.type_only_nodes,
}
}
/// Add an error diagnostic (with deduplication).
/// Diagnostics with the same (start, code) are only emitted once.
pub fn error(&mut self, start: u32, length: u32, message: String, code: u32) {
// Check if we've already emitted this diagnostic
let key = (start, code);
if self.emitted_diagnostics.contains(&key) {
return;
}
self.emitted_diagnostics.insert(key);
tracing::debug!(
code,
start,
length,
file = %self.file_name,
message = %message,
"diagnostic"
);
self.diagnostics.push(Diagnostic::error(
self.file_name.clone(),
start,
length,
message,
code,
));
}
/// Push a diagnostic with deduplication.
/// Diagnostics with the same (start, code) are only emitted once.
/// Exception: TS2318 (missing global type) at position 0 uses message hash
/// to allow multiple distinct global type errors.
pub fn push_diagnostic(&mut self, diag: Diagnostic) {
// For TS2318 at position 0, include message hash in key to allow distinct errors
// (e.g., "Cannot find global type 'Array'" vs "Cannot find global type 'Object'")
let key = if diag.code == 2318 && diag.start == 0 {
// Use a hash of the message to distinguish different TS2318 errors
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
diag.message_text.hash(&mut hasher);
(hasher.finish() as u32, diag.code)
} else {
(diag.start, diag.code)
};
if self.emitted_diagnostics.contains(&key) {
return;
}
self.emitted_diagnostics.insert(key);
tracing::debug!(
code = diag.code,
start = diag.start,
length = diag.length,
file = %diag.file,
message = %diag.message_text,
"diagnostic"
);
self.diagnostics.push(diag);
}
/// Get node span (pos, end) from index.
pub fn get_node_span(&self, idx: NodeIndex) -> Option<(u32, u32)> {
let node = self.arena.get(idx)?;
Some((node.pos, node.end))
}
/// Push an expected return type onto the stack.
pub fn push_return_type(&mut self, return_type: TypeId) {
self.return_type_stack.push(return_type);
}
/// Pop the expected return type from the stack.
pub fn pop_return_type(&mut self) {
self.return_type_stack.pop();
}
/// Get the current expected return type.
pub fn current_return_type(&self) -> Option<TypeId> {
self.return_type_stack.last().copied()
}
/// Push a contextual yield type for a generator function.
pub fn push_yield_type(&mut self, yield_type: Option<TypeId>) {
self.yield_type_stack.push(yield_type);
}
/// Pop the contextual yield type from the stack.
pub fn pop_yield_type(&mut self) {
self.yield_type_stack.pop();
}
/// Get the current contextual yield type for the enclosing generator.
pub fn current_yield_type(&self) -> Option<TypeId> {
self.yield_type_stack.last().copied().flatten()
}
/// Enter an async context (increment async depth).
pub const fn enter_async_context(&mut self) {
self.async_depth += 1;
}
/// Exit an async context (decrement async depth).
pub const fn exit_async_context(&mut self) {
if self.async_depth > 0 {
self.async_depth -= 1;
}
}
/// Check if we're currently inside an async function.
pub const fn in_async_context(&self) -> bool {
self.async_depth > 0
}
/// Consume one unit of type resolution fuel.
/// Returns true if fuel is still available, false if exhausted.
/// When exhausted, type resolution should return ERROR to prevent timeout.
pub fn consume_fuel(&self) -> bool {
let mut fuel = self.type_resolution_fuel.borrow_mut();
if *fuel == 0 {
*self.fuel_exhausted.borrow_mut() = true;
return false;
}
*fuel -= 1;
true
}
/// Check if type resolution fuel has been exhausted.
pub fn is_fuel_exhausted(&self) -> bool {
*self.fuel_exhausted.borrow()
}
/// Enter a recursive call. Returns true if recursion is allowed,
/// false if the depth limit has been reached (caller should bail out).
#[inline]
pub fn enter_recursion(&self) -> bool {
self.recursion_depth.borrow_mut().enter()
}
/// Leave a recursive call (decrement depth counter).
#[inline]
pub fn leave_recursion(&self) {
self.recursion_depth.borrow_mut().leave();
}
// =========================================================================
// Flow Graph Queries
// =========================================================================
/// Check flow usage at a specific AST node.
///
/// This method queries the control flow graph to determine flow-sensitive
/// information at a given node. Returns `None` if flow graph is not available.
///
/// # Arguments
/// * `node_idx` - The AST node to query flow information for
///
/// # Returns
/// * `Some(FlowNodeId)` - The flow node ID at this location
/// * `None` - If flow graph is not available or node has no flow info
pub fn check_flow_usage(&self, node_idx: NodeIndex) -> Option<tsz_binder::FlowNodeId> {
if let Some(ref _graph) = self.flow_graph {
// Look up the flow node for this AST node from the binder's node_flow mapping
self.binder.node_flow.get(&node_idx.0).copied()
} else {
None
}
}
/// Get a reference to the flow graph.
pub const fn flow_graph(&self) -> Option<&FlowGraph<'a>> {
self.flow_graph.as_ref()
}
}