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
//! Flow-based definite assignment and declaration ordering checks.
use std::rc::Rc;
use crate::FlowAnalyzer;
use crate::diagnostics::Diagnostic;
use crate::query_boundaries::definite_assignment::should_report_variable_use_before_assignment;
use crate::state::{CheckerState, MAX_TREE_WALK_ITERATIONS};
use tsz_binder::SymbolId;
use tsz_parser::parser::NodeIndex;
use tsz_parser::parser::node::NodeAccess;
use tsz_parser::parser::syntax_kind_ext;
use tsz_scanner::SyntaxKind;
use tsz_solver::TypeId;
impl<'a> CheckerState<'a> {
/// Check flow-aware usage of a variable (definite assignment + type narrowing).
///
/// This is the main entry point for flow analysis when variables are used.
/// It combines two critical TypeScript features:
/// 1. **Definite Assignment Analysis**: Catches use-before-assignment errors
/// 2. **Type Narrowing**: Refines types based on control flow
///
/// ## Definite Assignment Checking:
/// - Block-scoped variables (let/const) without initializers are checked
/// - Variables are tracked through all code paths
/// - TS2454 error emitted if variable might not be assigned
/// - Error: "Variable 'x' is used before being assigned"
///
/// ## Type Narrowing:
/// - If definitely assigned, applies flow-based type narrowing
/// - typeof guards, discriminant checks, null checks refine types
/// - Returns narrowed type for precise type checking
///
/// ## Rule #42 Integration:
/// - If inside a closure and variable is mutable (let/var): Returns declared type
/// - If inside a closure and variable is const: Applies narrowing
pub fn check_flow_usage(
&mut self,
idx: NodeIndex,
declared_type: TypeId,
sym_id: SymbolId,
) -> TypeId {
use tracing::trace;
trace!(?idx, ?declared_type, ?sym_id, "check_flow_usage called");
// Flow narrowing is only meaningful for variable-like bindings.
// Class/function/namespace symbols have stable declared types and
// do not participate in definite-assignment analysis.
if !self.symbol_participates_in_flow_analysis(sym_id) {
trace!("Symbol does not participate in flow analysis, returning declared type");
return declared_type;
}
// Const object/array literal bindings have a stable type shape and do not
// benefit from control-flow narrowing. Skipping CFG traversal for these
// bindings avoids O(N²) reference matching on large call-heavy files.
if self.should_skip_flow_narrowing_for_const_literal_binding(sym_id) {
return declared_type;
}
// Check definite assignment for block-scoped variables without initializers
if should_report_variable_use_before_assignment(self, idx, declared_type, sym_id) {
// Report TS2454 error: Variable used before assignment
self.emit_definite_assignment_error(idx, sym_id);
// Return declared type to avoid cascading errors
trace!("Definite assignment error, returning declared type");
return declared_type;
}
// Apply type narrowing based on control flow
trace!("Applying flow narrowing");
let result = self.apply_flow_narrowing(idx, declared_type);
trace!(?result, "check_flow_usage result");
result
}
fn symbol_participates_in_flow_analysis(&self, sym_id: SymbolId) -> bool {
use tsz_binder::symbol_flags;
self.ctx
.binder
.get_symbol(sym_id)
.is_some_and(|symbol| (symbol.flags & symbol_flags::VARIABLE) != 0)
}
fn should_skip_flow_narrowing_for_const_literal_binding(&self, sym_id: SymbolId) -> bool {
let Some(symbol) = self.ctx.binder.get_symbol(sym_id) else {
return false;
};
let mut value_decl = symbol.value_declaration;
if value_decl.is_none() {
return false;
}
let mut decl_node = match self.ctx.arena.get(value_decl) {
Some(node) => node,
None => return false,
};
// Binder symbols can point at the identifier node for the declaration name.
// Normalize to the enclosing VARIABLE_DECLARATION before checking const/init shape.
if decl_node.kind == SyntaxKind::Identifier as u16
&& let Some(ext) = self.ctx.arena.get_extended(value_decl)
&& ext.parent.is_some()
&& let Some(parent_node) = self.ctx.arena.get(ext.parent)
&& parent_node.kind == syntax_kind_ext::VARIABLE_DECLARATION
{
value_decl = ext.parent;
decl_node = parent_node;
}
if decl_node.kind != syntax_kind_ext::VARIABLE_DECLARATION
|| !self.is_const_variable_declaration(value_decl)
{
return false;
}
let Some(var_decl) = self.ctx.arena.get_variable_declaration(decl_node) else {
return false;
};
if var_decl.type_annotation.is_some() || var_decl.initializer.is_none() {
return false;
}
let Some(init_node) = self.ctx.arena.get(var_decl.initializer) else {
return false;
};
init_node.kind == syntax_kind_ext::OBJECT_LITERAL_EXPRESSION
|| init_node.kind == syntax_kind_ext::ARRAY_LITERAL_EXPRESSION
}
/// Emit TS2454 error for variable used before definite assignment.
fn emit_definite_assignment_error(&mut self, idx: NodeIndex, sym_id: SymbolId) {
// Get the location for error reporting and deduplication key
let Some(node) = self.ctx.arena.get(idx) else {
// If the node doesn't exist in the arena, we can't deduplicate by position
// Skip error emission to avoid potential duplicates
return;
};
let pos = node.pos;
// Deduplicate: check if we've already emitted an error for this (node, symbol) pair
let key = (pos, sym_id);
if !self.ctx.emitted_ts2454_errors.insert(key) {
// Already inserted - duplicate error, skip
return;
}
// Get the variable name for the error message
let name = self
.ctx
.binder
.get_symbol(sym_id)
.map_or_else(|| "<unknown>".to_string(), |s| s.escaped_name.clone());
// Get the location for error reporting
let length = node.end - node.pos;
self.ctx.diagnostics.push(Diagnostic::error(
self.ctx.file_name.clone(),
pos,
length,
format!("Variable '{name}' is used before being assigned."),
2454, // TS2454
));
}
/// Check if a node is within a parameter's default value initializer.
/// This is used to detect `await` used in default parameter values (TS2524).
pub(crate) fn is_in_default_parameter(&self, idx: NodeIndex) -> bool {
let mut current = idx;
let mut iterations = 0;
loop {
iterations += 1;
if iterations > MAX_TREE_WALK_ITERATIONS {
return false;
}
let ext = match self.ctx.arena.get_extended(current) {
Some(ext) => ext,
None => return false,
};
let parent_idx = ext.parent;
if parent_idx.is_none() {
return false;
}
// Check if parent is a parameter and we're in its initializer
if let Some(parent_node) = self.ctx.arena.get(parent_idx) {
if parent_node.kind == syntax_kind_ext::PARAMETER
&& let Some(param) = self.ctx.arena.get_parameter(parent_node)
{
// Check if current node is within the initializer
if param.initializer.is_some() {
let init_idx = param.initializer;
// Check if idx is within the initializer subtree
if self.is_node_within(idx, init_idx) {
return true;
}
}
}
// Stop at function/arrow boundaries - parameters are only at the top level
if parent_node.is_function_like() {
return false;
}
}
current = parent_idx;
}
}
// =========================================================================
// Definite Assignment Checking
// =========================================================================
/// Check if definite assignment checking should be skipped for a given type.
/// TypeScript skips TS2454 when the declared type is `any`, `unknown`, or includes `undefined`.
pub(crate) fn skip_definite_assignment_for_type(&self, declared_type: TypeId) -> bool {
use tsz_solver::TypeId;
use tsz_solver::type_contains_undefined;
// Skip for any/unknown/error - these types allow uninitialized usage
if declared_type == TypeId::ANY
|| declared_type == TypeId::UNKNOWN
|| declared_type == TypeId::ERROR
{
return true;
}
// Skip if the type includes undefined or void (uninitialized variables are undefined)
type_contains_undefined(self.ctx.types, declared_type)
}
/// - Not in ambient contexts
/// - Not in type-only positions
pub(crate) fn should_check_definite_assignment(
&mut self,
sym_id: SymbolId,
idx: NodeIndex,
) -> bool {
use tsz_binder::symbol_flags;
use tsz_parser::parser::node::NodeAccess;
// TS2454 is only emitted under strictNullChecks (matches tsc behavior)
if !self.ctx.strict_null_checks() {
return false;
}
// Skip definite assignment check if this identifier is a for-in/for-of
// initializer — it's an assignment target, not a usage.
// e.g., `let x: number; for (x of items) { ... }` — the `x` in `for (x of ...)`
// is being written to, not read from.
if self.is_for_in_of_initializer(idx) {
return false;
}
// Skip definite assignment check if this identifier is an assignment target
// in a destructuring assignment — it's being written to, not read.
// e.g., `let x: string; [x] = items;` — the `x` is being assigned to.
if self.is_destructuring_assignment_target(idx) {
return false;
}
// Get the symbol
let Some(symbol) = self.ctx.binder.get_symbol(sym_id) else {
return false;
};
// Flow analysis operates within a single file's AST.
// We cannot prove assignment across files, so we assume it was assigned.
if symbol.decl_file_idx != u32::MAX
&& symbol.decl_file_idx != self.ctx.current_file_idx as u32
{
return false;
}
// Check both block-scoped (let/const) and function-scoped (var) variables.
// Parameters are excluded downstream (PARAMETER nodes ≠VARIABLE_DECLARATION).
if (symbol.flags & symbol_flags::VARIABLE) == 0 {
return false;
}
// Get the value declaration
let decl_id = symbol.value_declaration;
if decl_id.is_none() {
return false;
}
// Get the declaration node
let Some(decl_node) = self.ctx.arena.get(decl_id) else {
return false;
};
let mut decl_node = decl_node;
let mut decl_id_to_check = decl_id;
if decl_node.kind == tsz_scanner::SyntaxKind::Identifier as u16
&& let Some(info) = self.ctx.arena.node_info(decl_id)
&& let Some(parent) = self.ctx.arena.get(info.parent)
{
decl_node = parent;
decl_id_to_check = info.parent;
}
// If the declaration is a binding element that is ultimately a parameter,
// we should not perform definite assignment checking. Parameters are
// always definitely assigned.
if decl_node.kind == syntax_kind_ext::BINDING_ELEMENT {
let mut current = decl_id_to_check;
for _ in 0..10 {
if let Some(info) = self.ctx.arena.node_info(current) {
let parent = info.parent;
if let Some(parent_node) = self.ctx.arena.get(parent)
&& parent_node.kind == syntax_kind_ext::PARAMETER
{
return false;
}
current = parent;
} else {
break;
}
}
}
let (has_initializer, has_exclamation) =
if decl_node.kind == syntax_kind_ext::VARIABLE_DECLARATION {
let Some(var_data) = self.ctx.arena.get_variable_declaration(decl_node) else {
return false;
};
(var_data.initializer.is_some(), var_data.exclamation_token)
} else if decl_node.kind == syntax_kind_ext::BINDING_ELEMENT {
let Some(_var_data) = self.ctx.arena.get_binding_element(decl_node) else {
return false;
};
(true, false)
} else {
return false;
};
// If there's an initializer, skip definite assignment check — unless the variable
// is `var` (function-scoped) and the usage is before the declaration in source
// order. `var` hoists the binding but NOT the initializer, so at the usage
// point the variable is `undefined`. Block-scoped variables (let/const) don't
// need this: TDZ checks handle pre-declaration use separately.
if has_initializer {
let is_function_scoped =
symbol.flags & tsz_binder::symbol_flags::FUNCTION_SCOPED_VARIABLE != 0;
if let Some(usage_node) = self.ctx.arena.get(idx)
&& should_skip_daa_for_initialized_function_scoped_var(
is_function_scoped,
self.is_source_file_global_var_decl(decl_id_to_check),
self.enclosing_top_level_statement_kind(decl_id_to_check),
usage_node.pos,
decl_node.end,
)
{
return false;
}
if !is_function_scoped {
return false;
}
if let Some(_usage_node) = self.ctx.arena.get(idx) {
// Check if usage is textually inside the initializer expression of the variable.
// e.g. var x = f(() => x); // `x` inside is used before assignment completes!
// However, general usages after the declaration shouldn't be skipped just because of position,
// as they could be in a catch block or after a conditional return.
// The control flow graph should be the ultimate source of truth.
// If usage is inside a nested function relative to the declaration, skip
if self.find_enclosing_function_or_source_file(decl_id_to_check)
!= self.find_enclosing_function_or_source_file(idx)
{
return false;
}
}
}
// If there's a definite assignment assertion (!), skip check
if has_exclamation {
return false;
}
// If the variable is declared in a for-in or for-of loop header,
// it's assigned by the loop iteration itself - but only when usage is at or after the loop.
// A usage BEFORE the loop in source order (e.g. `v; for (var v of [0]) {}`) must still
// be checked for definite assignment.
if let Some(decl_list_info) = self.ctx.arena.node_info(decl_id_to_check) {
let decl_list_idx = decl_list_info.parent;
if let Some(decl_list_node) = self.ctx.arena.get(decl_list_idx)
&& decl_list_node.kind == syntax_kind_ext::VARIABLE_DECLARATION_LIST
&& let Some(for_info) = self.ctx.arena.node_info(decl_list_idx)
{
let for_idx = for_info.parent;
if let Some(for_node) = self.ctx.arena.get(for_idx)
&& (for_node.kind == syntax_kind_ext::FOR_IN_STATEMENT
|| for_node.kind == syntax_kind_ext::FOR_OF_STATEMENT)
{
// Only skip the check if the usage is at or after the start of the loop.
// If the usage precedes the loop in source order, fall through to DAA.
if let Some(usage_node) = self.ctx.arena.get(idx) {
if usage_node.pos >= for_node.pos {
return false;
}
// Usage is before the loop - continue to definite assignment check
} else {
return false;
}
}
}
}
// For source-file globals, skip TS2454 when the usage occurs inside a
// function-like body. The variable may be assigned before invocation.
if self.is_source_file_global_var_decl(decl_id_to_check)
&& self.is_inside_function_like(idx)
{
return false;
}
// For namespace-scoped variables, skip TS2454 when the usage is inside
// a nested namespace (MODULE_DECLARATION) relative to the declaration.
// Flow analysis can't cross namespace boundaries, and the variable may
// be assigned in the outer namespace before the inner namespace executes.
// Same-namespace usage still gets TS2454 (flow analysis works within a scope).
if self.is_usage_in_nested_namespace_from_decl(decl_id_to_check, idx) {
return false;
}
// 1. Skip definite assignment checks in ambient declarations (declare const/let, declare module)
if self.is_ambient_declaration(decl_id_to_check) {
return false;
}
// 2. Anchor checks to a function-like or source-file container
let mut current = decl_id_to_check;
let mut found_container_scope = false;
for _ in 0..50 {
let Some(info) = self.ctx.arena.node_info(current) else {
break;
};
if let Some(node) = self.ctx.arena.get(current) {
// Check if we're inside a function-like or source-file container scope
if node.is_function_like() || node.kind == syntax_kind_ext::SOURCE_FILE {
found_container_scope = true;
break;
}
}
current = info.parent;
if current.is_none() {
break;
}
}
// Only check definite assignment when we can anchor to a container scope.
found_container_scope
}
fn is_source_file_global_var_decl(&self, decl_id: NodeIndex) -> bool {
let Some(info) = self.ctx.arena.node_info(decl_id) else {
return false;
};
let mut current = info.parent;
for _ in 0..50 {
let Some(node) = self.ctx.arena.get(current) else {
return false;
};
if node.kind == syntax_kind_ext::SOURCE_FILE {
return true;
}
if node.is_function_like() {
return false;
}
let Some(next) = self.ctx.arena.node_info(current).map(|n| n.parent) else {
return false;
};
current = next;
if current.is_none() {
return false;
}
}
false
}
fn enclosing_top_level_statement_kind(&self, node_idx: NodeIndex) -> Option<u16> {
let mut current = node_idx;
for _ in 0..50 {
let info = self.ctx.arena.node_info(current)?;
let parent = info.parent;
let parent_node = self.ctx.arena.get(parent)?;
if parent_node.kind == syntax_kind_ext::SOURCE_FILE {
return self.ctx.arena.get(current).map(|n| n.kind);
}
current = parent;
if current.is_none() {
return None;
}
}
None
}
fn is_inside_function_like(&self, idx: NodeIndex) -> bool {
let mut current = idx;
for _ in 0..50 {
let Some(info) = self.ctx.arena.node_info(current) else {
return false;
};
current = info.parent;
let Some(node) = self.ctx.arena.get(current) else {
return false;
};
if node.is_function_like() {
return true;
}
if node.kind == syntax_kind_ext::SOURCE_FILE {
return false;
}
}
false
}
/// Check if a usage crosses a namespace boundary relative to its declaration.
/// Walk up from the usage node; if we encounter a `MODULE_DECLARATION` before
/// reaching the node that contains the declaration, the usage is in a nested
/// namespace and TS2454 should be suppressed (flow graph doesn't span across
/// namespace boundaries).
fn is_usage_in_nested_namespace_from_decl(
&self,
decl_id: NodeIndex,
usage_idx: NodeIndex,
) -> bool {
let Some(decl_node) = self.ctx.arena.get(decl_id) else {
return false;
};
let decl_pos = decl_node.pos;
let decl_end = decl_node.end;
let mut current = usage_idx;
for _ in 0..50 {
let Some(info) = self.ctx.arena.node_info(current) else {
break;
};
current = info.parent;
let Some(node) = self.ctx.arena.get(current) else {
break;
};
// If this node's span contains the declaration, we've reached the
// common container — no namespace boundary between usage and decl.
if node.pos <= decl_pos && node.end >= decl_end {
return false;
}
// Hit a MODULE_DECLARATION before reaching the declaration's container:
// usage is in a nested namespace.
if node.kind == syntax_kind_ext::MODULE_DECLARATION {
return true;
}
if current.is_none() {
break;
}
}
false
}
/// Check if a node is a for-in/for-of initializer (assignment target).
/// For `for (x of items)`, the identifier `x` is the initializer and is
/// being assigned to, not read from.
fn is_for_in_of_initializer(&self, idx: NodeIndex) -> bool {
use tsz_parser::parser::node::NodeAccess;
let Some(info) = self.ctx.arena.node_info(idx) else {
return false;
};
let parent = info.parent;
let Some(parent_node) = self.ctx.arena.get(parent) else {
return false;
};
if (parent_node.kind == syntax_kind_ext::FOR_IN_STATEMENT
|| parent_node.kind == syntax_kind_ext::FOR_OF_STATEMENT)
&& let Some(for_data) = self.ctx.arena.get_for_in_of(parent_node)
&& for_data.initializer == idx
{
return true;
}
false
}
/// Check if an identifier is an assignment target in a destructuring assignment.
/// e.g., `[x] = a` or `({x} = a)` — the `x` is being written to, not read.
fn is_destructuring_assignment_target(&self, idx: NodeIndex) -> bool {
let mut current = idx;
for _ in 0..10 {
let Some(info) = self.ctx.arena.node_info(current) else {
return false;
};
let parent = info.parent;
let Some(parent_node) = self.ctx.arena.get(parent) else {
return false;
};
match parent_node.kind {
k if k == syntax_kind_ext::ARRAY_LITERAL_EXPRESSION
|| k == syntax_kind_ext::OBJECT_LITERAL_EXPRESSION
|| k == syntax_kind_ext::SPREAD_ELEMENT
|| k == syntax_kind_ext::SPREAD_ASSIGNMENT
|| k == syntax_kind_ext::PROPERTY_ASSIGNMENT
|| k == syntax_kind_ext::SHORTHAND_PROPERTY_ASSIGNMENT =>
{
current = parent;
}
k if k == syntax_kind_ext::BINARY_EXPRESSION => {
// Check this is the LHS of a simple assignment (=)
if let Some(bin) = self.ctx.arena.get_binary_expr(parent_node)
&& bin.operator_token == SyntaxKind::EqualsToken as u16
&& bin.left == current
{
return true;
}
return false;
}
k if k == syntax_kind_ext::FOR_IN_STATEMENT
|| k == syntax_kind_ext::FOR_OF_STATEMENT =>
{
if let Some(for_node) = self.ctx.arena.get_for_in_of(parent_node)
&& for_node.initializer == current
{
return true;
}
return false;
}
_ => return false,
}
}
false
}
/// Check if a variable is definitely assigned at a given point.
///
/// This performs flow-sensitive analysis to determine if a variable
/// has been assigned on all code paths leading to the usage point.
pub(crate) fn is_definitely_assigned_at(&self, idx: NodeIndex) -> bool {
// Get the flow node for this identifier usage.
// Identifier reference nodes (e.g., `a` in `console.log(a)`) typically
// don't have direct flow nodes recorded — the binder only records flow
// for statements and declarations. Walk up the AST to find the nearest
// ancestor with a flow node, mirroring `apply_flow_narrowing`'s fallback.
let flow_node = if let Some(flow) = self.ctx.binder.get_node_flow(idx) {
flow
} else {
let mut current = self.ctx.arena.get_extended(idx).map(|ext| ext.parent);
let mut found = None;
while let Some(parent) = current {
if parent.is_none() {
break;
}
if let Some(flow) = self.ctx.binder.get_node_flow(parent) {
found = Some(flow);
break;
}
current = self.ctx.arena.get_extended(parent).map(|ext| ext.parent);
}
match found {
Some(flow) => flow,
None => {
tracing::debug!("No flow info for {idx:?} or its ancestors");
return true;
}
}
};
// Create a flow analyzer and check definite assignment
let analyzer = FlowAnalyzer::with_node_types(
self.ctx.arena,
self.ctx.binder,
self.ctx.types,
&self.ctx.node_types,
)
.with_flow_cache(&self.ctx.flow_analysis_cache)
.with_reference_match_cache(&self.ctx.flow_reference_match_cache)
.with_type_environment(Rc::clone(&self.ctx.type_environment));
analyzer.is_definitely_assigned(idx, flow_node)
}
// =========================================================================
// Temporal Dead Zone (TDZ) Checking
// =========================================================================
/// Check if a variable is used before its declaration in a static block.
///
/// This detects Temporal Dead Zone (TDZ) violations where a block-scoped variable
/// is accessed inside a class static block before it has been declared in the source.
///
/// # Example
/// ```typescript
/// class C {
/// static {
/// console.log(x); // Error: x used before declaration
/// }
/// }
/// let x = 1;
/// ```
pub(crate) fn is_variable_used_before_declaration_in_static_block(
&self,
sym_id: SymbolId,
usage_idx: NodeIndex,
) -> bool {
use tsz_binder::symbol_flags;
// 1. Get the symbol
let Some(symbol) = self.ctx.binder.symbols.get(sym_id) else {
return false;
};
// 2. Check if it is a block-scoped variable (let, const, class, enum)
// var and function are hoisted, so they don't have TDZ issues in this context.
// Imports (ALIAS) are also hoisted or handled differently.
let is_block_scoped = (symbol.flags
& (symbol_flags::BLOCK_SCOPED_VARIABLE | symbol_flags::CLASS | symbol_flags::ENUM))
!= 0;
if !is_block_scoped {
return false;
}
// Skip cross-file symbols — TDZ position comparison only valid within same file
if symbol.decl_file_idx != u32::MAX
&& symbol.decl_file_idx != self.ctx.current_file_idx as u32
{
return false;
}
// 3. Get the declaration node
// Prefer value_declaration, fall back to first declaration
let decl_idx = if symbol.value_declaration.is_some() {
symbol.value_declaration
} else if let Some(&first_decl) = symbol.declarations.first() {
first_decl
} else {
return false;
};
// 4. Check textual order: Usage must be textually before declaration
// We ensure both nodes exist in the current arena
let Some(usage_node) = self.ctx.arena.get(usage_idx) else {
return false;
};
let Some(decl_node) = self.ctx.arena.get(decl_idx) else {
return false;
};
// If usage is after declaration, it's valid
if usage_node.pos >= decl_node.end {
return false;
}
// For CLASS symbols: if the usage is inside the class body (usage_node.pos > decl_node.pos),
// the reference is a self-reference within the class's own static block and is NOT a TDZ
// violation. For example, inside `static {}` of class C, referencing C itself is valid.
// The class name is accessible within its own body.
if symbol.flags & symbol_flags::CLASS != 0 && usage_node.pos > decl_node.pos {
return false;
}
// 5. Check if usage is inside a static block
// Use find_enclosing_static_block which walks up the AST and stops at function boundaries.
// This ensures we only catch immediate usage, not usage inside a closure/function
// defined within the static block (which would execute later).
if self.find_enclosing_static_block(usage_idx).is_some() {
return true;
}
false
}
/// Check if a variable is used before its declaration in a computed property.
///
/// Computed property names are evaluated before the property declaration,
/// creating a TDZ for the class being declared.
pub(crate) fn is_variable_used_before_declaration_in_computed_property(
&self,
sym_id: SymbolId,
usage_idx: NodeIndex,
) -> bool {
use tsz_binder::symbol_flags;
// 1. Get the symbol
let Some(symbol) = self.ctx.binder.symbols.get(sym_id) else {
return false;
};
// 2. Check if it is a block-scoped variable (let, const, class, enum)
let is_block_scoped = (symbol.flags
& (symbol_flags::BLOCK_SCOPED_VARIABLE | symbol_flags::CLASS | symbol_flags::ENUM))
!= 0;
if !is_block_scoped {
return false;
}
// Skip cross-file symbols — TDZ position comparison only valid within same file
if symbol.decl_file_idx != u32::MAX
&& symbol.decl_file_idx != self.ctx.current_file_idx as u32
{
return false;
}
// 3. Get the declaration node
let decl_idx = if symbol.value_declaration.is_some() {
symbol.value_declaration
} else if let Some(&first_decl) = symbol.declarations.first() {
first_decl
} else {
return false;
};
// 4. Check textual order: Usage must be textually before declaration
let Some(usage_node) = self.ctx.arena.get(usage_idx) else {
return false;
};
let Some(decl_node) = self.ctx.arena.get(decl_idx) else {
return false;
};
if usage_node.pos >= decl_node.end {
return false;
}
// 5. Check if usage is inside a computed property name
if self.find_enclosing_computed_property(usage_idx).is_some() {
return true;
}
false
}
/// Check if a variable is used before its declaration in a heritage clause.
///
/// Heritage clauses (extends, implements) are evaluated before the class body,
/// creating a TDZ for the class being declared.
pub(crate) fn is_variable_used_before_declaration_in_heritage_clause(
&self,
sym_id: SymbolId,
usage_idx: NodeIndex,
) -> bool {
use tsz_binder::symbol_flags;
// 1. Get the symbol
let Some(symbol) = self.ctx.binder.symbols.get(sym_id) else {
return false;
};
// 2. Check if it is a block-scoped variable (let, const, class, enum)
let is_block_scoped = (symbol.flags
& (symbol_flags::BLOCK_SCOPED_VARIABLE | symbol_flags::CLASS | symbol_flags::ENUM))
!= 0;
if !is_block_scoped {
return false;
}
// Skip TDZ check for type-only contexts (interface extends, type parameters, etc.)
// Types are resolved at compile-time, so they don't have temporal dead zones.
if self.is_in_type_only_context(usage_idx) {
return false;
}
// Skip cross-file symbols — TDZ position comparison only makes sense
// within the same file.
if symbol.decl_file_idx != u32::MAX
&& symbol.decl_file_idx != self.ctx.current_file_idx as u32
{
return false;
}
// 3. Get the declaration node
let decl_idx = if symbol.value_declaration.is_some() {
symbol.value_declaration
} else if let Some(&first_decl) = symbol.declarations.first() {
first_decl
} else {
return false;
};
// 4. Check textual order: Usage must be textually before declaration
let Some(usage_node) = self.ctx.arena.get(usage_idx) else {
return false;
};
let Some(decl_node) = self.ctx.arena.get(decl_idx) else {
return false;
};
if usage_node.pos >= decl_node.end {
return false;
}
// 5. Check if usage is inside a heritage clause (extends/implements)
if self.find_enclosing_heritage_clause(usage_idx).is_some() {
return true;
}
false
}
/// TS2448/TS2449/TS2450: Check if a block-scoped declaration (class, enum,
/// let/const) is used before its declaration in immediately executing code
/// (not inside a function/method body).
pub(crate) fn is_class_or_enum_used_before_declaration(
&self,
sym_id: SymbolId,
usage_idx: NodeIndex,
) -> bool {
use tsz_binder::symbol_flags;
use tsz_parser::parser::syntax_kind_ext;
let Some(symbol) = self.ctx.binder.symbols.get(sym_id) else {
return false;
};
// Applies to block-scoped declarations: class, enum, let/const
let is_block_scoped = (symbol.flags
& (symbol_flags::CLASS | symbol_flags::ENUM | symbol_flags::BLOCK_SCOPED_VARIABLE))
!= 0;
if !is_block_scoped {
return false;
}
// Skip TDZ check for type-only contexts (type annotations, typeof in types, etc.)
// Types are resolved at compile-time, so they don't have temporal dead zones.
if self.is_in_type_only_context(usage_idx) {
return false;
}
// Skip check for cross-file symbols (imported from another file).
// Position comparison only makes sense within the same file.
if symbol.import_module.is_some() {
return false;
}
let is_cross_file = symbol.decl_file_idx != u32::MAX
&& symbol.decl_file_idx != self.ctx.current_file_idx as u32;
if is_cross_file && (self.ctx.current_file_idx as u32) > symbol.decl_file_idx {
return false;
}
// In multi-file mode, symbol declarations may reference nodes in another
// file's arena. `self.ctx.arena` only contains the *current* file, so
// looking up the declaration index would yield an unrelated node whose
// position comparison is meaningless. Detect this by verifying that the
// node found at the declaration index really IS a class / enum / variable
// declaration — if it isn't, the index came from a different arena.
let is_multi_file = self.ctx.all_arenas.is_some();
// Get the declaration position
let decl_idx = if symbol.value_declaration.is_some() {
symbol.value_declaration
} else if let Some(&first_decl) = symbol.declarations.first() {
first_decl
} else {
return false;
};
let Some(usage_node) = self.ctx.arena.get(usage_idx) else {
return false;
};
let mut decl_node_opt = self.ctx.arena.get(decl_idx);
let mut decl_arena = self.ctx.arena;
if is_cross_file
&& let Some(arenas) = self.ctx.all_arenas.as_ref()
&& let Some(arena) = arenas.get(symbol.decl_file_idx as usize)
{
decl_node_opt = arena.get(decl_idx);
decl_arena = arena.as_ref();
}
let Some(decl_node) = decl_node_opt else {
return false;
};
// In multi-file mode, validate the declaration node kind matches the
// symbol. A mismatch means the node index is from a different file's
// arena and should not be compared.
if is_multi_file && !is_cross_file {
let is_class = symbol.flags & symbol_flags::CLASS != 0;
let is_enum = symbol.flags & symbol_flags::ENUM != 0;
let is_var = symbol.flags & symbol_flags::BLOCK_SCOPED_VARIABLE != 0;
let kind_ok = (is_class
&& (decl_node.kind == syntax_kind_ext::CLASS_DECLARATION
|| decl_node.kind == syntax_kind_ext::CLASS_EXPRESSION))
|| (is_enum && decl_node.kind == syntax_kind_ext::ENUM_DECLARATION)
|| (is_var
&& (decl_node.kind == syntax_kind_ext::VARIABLE_DECLARATION
|| decl_node.kind == syntax_kind_ext::PARAMETER
|| decl_node.kind == syntax_kind_ext::BINDING_ELEMENT
|| decl_node.kind == tsz_scanner::SyntaxKind::Identifier as u16));
if !kind_ok {
return false;
}
}
// Skip ambient declarations — `declare class`/`declare enum` are type-level
// and have no TDZ. In multi-file mode, search all arenas since decl_idx may
// point to a node in another file's arena.
if is_cross_file {
if let Some(class) = decl_arena.get_class(decl_node)
&& self.has_declare_modifier_in_arena(decl_arena, &class.modifiers)
{
return false;
}
if let Some(enum_decl) = decl_arena.get_enum(decl_node)
&& self.has_declare_modifier_in_arena(decl_arena, &enum_decl.modifiers)
{
return false;
}
} else if self.is_ambient_declaration(decl_idx) {
return false;
}
// Only flag if usage is before declaration in source order
// EXCEPT for block-scoped variables, which are also in TDZ during their own initializer.
// For classes and enums, usage >= pos is always safe (handled by other specific TDZ checks
// for computed properties, heritage clauses, etc.).
let is_var = symbol.flags & symbol_flags::BLOCK_SCOPED_VARIABLE != 0;
let mut could_be_in_initializer = false;
if !is_cross_file && usage_node.pos >= decl_node.pos {
if is_var && usage_node.pos <= decl_node.end {
// It might be in the initializer. We will confirm via AST walk.
could_be_in_initializer = true;
} else {
return false;
}
}
// Find the declaration's enclosing function-like container (or source file).
// This is the scope that "owns" both the declaration and (potentially) the usage.
let decl_container = if is_cross_file {
None // Walk up to source file
} else {
Some(self.find_enclosing_function_or_source_file(decl_idx))
};
// Walk up from usage: if we hit a function-like boundary BEFORE reaching
// the declaration's container, the usage is in deferred code (a nested
// function/arrow/method) and is NOT a TDZ violation.
// If we reach the declaration's container without crossing a function
// boundary, the usage executes immediately and IS a violation.
let mut current = usage_idx;
let mut found_decl_in_path = false;
while current.is_some() {
let Some(node) = self.ctx.arena.get(current) else {
break;
};
if current == decl_idx {
found_decl_in_path = true;
}
// If we reached the declaration container, stop - same scope means TDZ
if Some(current) == decl_container {
break;
}
// If we reach a function-like boundary before the decl container,
// the usage is deferred and not a TDZ violation.
// Exception: IIFEs (immediately invoked function expressions) execute
// immediately, so they ARE TDZ violations.
if node.is_function_like() && !self.ctx.arena.is_immediately_invoked(current) {
return false;
}
// IIFE - continue walking up, this function executes immediately
// Non-static class property initializers run during constructor execution,
// which is deferred — not a TDZ violation for class declarations.
if node.kind == syntax_kind_ext::PROPERTY_DECLARATION
&& let Some(prop) = self.ctx.arena.get_property_decl(node)
&& !self.has_static_modifier(&prop.modifiers)
{
return false;
}
// Export assignments (`export = X` / `export default X`) are not TDZ
// violations: the compiler reorders them after all declarations, so
// the referenced class/variable is initialized by the time the export
// binding is created.
if node.kind == syntax_kind_ext::EXPORT_ASSIGNMENT {
return false;
}
// Stop at source file
if node.kind == syntax_kind_ext::SOURCE_FILE {
break;
}
// Walk to parent
let Some(ext) = self.ctx.arena.get_extended(current) else {
break;
};
if ext.parent.is_none() {
break;
}
current = ext.parent;
}
if could_be_in_initializer && !found_decl_in_path {
// It was >= pos, but wasn't actually inside the declaration's AST.
// This means it's strictly AFTER the declaration.
return false;
}
true
}
/// Check if a modifier list in a specific arena contains the `declare` keyword.
/// Used in multi-file mode where `self.ctx.arena` may not be the declaration's arena.
pub(crate) fn has_declare_modifier_in_arena(
&self,
arena: &tsz_parser::parser::NodeArena,
modifiers: &Option<tsz_parser::parser::NodeList>,
) -> bool {
arena.has_modifier(modifiers, tsz_scanner::SyntaxKind::DeclareKeyword)
}
/// Check if a node is in a type-only context (type annotation, type query, heritage clause).
/// References in type-only positions don't need TDZ checks because types are
/// resolved at compile-time, not runtime.
fn is_in_type_only_context(&self, idx: NodeIndex) -> bool {
use tsz_parser::parser::syntax_kind_ext;
let mut current = idx;
while current.is_some() {
let Some(ext) = self.ctx.arena.get_extended(current) else {
return false;
};
if ext.parent.is_none() {
return false;
}
let Some(parent_node) = self.ctx.arena.get(ext.parent) else {
return false;
};
// Type node kinds indicate we're in a type-only context
match parent_node.kind {
// Core type nodes
syntax_kind_ext::TYPE_PREDICATE
| syntax_kind_ext::TYPE_REFERENCE
| syntax_kind_ext::FUNCTION_TYPE
| syntax_kind_ext::CONSTRUCTOR_TYPE
| syntax_kind_ext::TYPE_QUERY // typeof T in type position
| syntax_kind_ext::TYPE_LITERAL
| syntax_kind_ext::ARRAY_TYPE
| syntax_kind_ext::TUPLE_TYPE
| syntax_kind_ext::OPTIONAL_TYPE
| syntax_kind_ext::REST_TYPE
| syntax_kind_ext::UNION_TYPE
| syntax_kind_ext::INTERSECTION_TYPE
| syntax_kind_ext::CONDITIONAL_TYPE
| syntax_kind_ext::INFER_TYPE
| syntax_kind_ext::PARENTHESIZED_TYPE
| syntax_kind_ext::THIS_TYPE
| syntax_kind_ext::TYPE_OPERATOR
| syntax_kind_ext::INDEXED_ACCESS_TYPE
| syntax_kind_ext::MAPPED_TYPE
| syntax_kind_ext::LITERAL_TYPE
| syntax_kind_ext::NAMED_TUPLE_MEMBER
| syntax_kind_ext::TEMPLATE_LITERAL_TYPE
| syntax_kind_ext::IMPORT_TYPE
| syntax_kind_ext::HERITAGE_CLAUSE
| syntax_kind_ext::EXPRESSION_WITH_TYPE_ARGUMENTS => return true,
// Stop at boundaries that separate type from value context
syntax_kind_ext::TYPE_OF_EXPRESSION // typeof x in value position
| syntax_kind_ext::SOURCE_FILE => return false,
_ => {
// Continue walking up
current = ext.parent;
}
}
}
false
}
/// Find the enclosing function-like node or source file for a given node.
fn find_enclosing_function_or_source_file(&self, idx: NodeIndex) -> NodeIndex {
use tsz_parser::parser::syntax_kind_ext;
let mut current = idx;
while current.is_some() {
let Some(node) = self.ctx.arena.get(current) else {
break;
};
if node.is_function_like() || node.kind == syntax_kind_ext::SOURCE_FILE {
return current;
}
let Some(ext) = self.ctx.arena.get_extended(current) else {
break;
};
if ext.parent.is_none() {
break;
}
current = ext.parent;
}
current
}
}
const fn is_unconditional_top_level_statement(kind: u16) -> bool {
kind == syntax_kind_ext::VARIABLE_STATEMENT || kind == syntax_kind_ext::FOR_STATEMENT
}
fn should_skip_daa_for_initialized_function_scoped_var(
is_function_scoped: bool,
is_source_file_global: bool,
top_level_statement_kind: Option<u16>,
usage_pos: u32,
declaration_end: u32,
) -> bool {
is_function_scoped
&& is_source_file_global
&& usage_pos >= declaration_end
&& top_level_statement_kind.is_some_and(is_unconditional_top_level_statement)
}
#[cfg(test)]
mod tests {
use super::{should_skip_daa_for_initialized_function_scoped_var, syntax_kind_ext};
#[test]
fn skips_after_top_level_var_initializer_runs() {
assert!(should_skip_daa_for_initialized_function_scoped_var(
true,
true,
Some(syntax_kind_ext::VARIABLE_STATEMENT),
100,
50
));
}
#[test]
fn skips_after_top_level_for_initializer_runs() {
assert!(should_skip_daa_for_initialized_function_scoped_var(
true,
true,
Some(syntax_kind_ext::FOR_STATEMENT),
200,
80
));
}
#[test]
fn does_not_skip_when_declaration_is_conditional() {
assert!(!should_skip_daa_for_initialized_function_scoped_var(
true,
true,
Some(syntax_kind_ext::IF_STATEMENT),
120,
40
));
}
#[test]
fn does_not_skip_when_usage_precedes_declaration_end() {
assert!(!should_skip_daa_for_initialized_function_scoped_var(
true,
true,
Some(syntax_kind_ext::VARIABLE_STATEMENT),
30,
40
));
}
}