tsz-checker 0.1.9

TypeScript type checker for the tsz compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! # `CheckerState` - Type Checker Orchestration Layer
//!
//! This module serves as the orchestration layer for the TypeScript type checker.
//! It coordinates between various specialized checking modules while maintaining
//! shared state and caching for performance.
//!
//! ## Architecture - Modular Design
//!
//! The checker has been decomposed into focused modules, each responsible for
//! a specific aspect of type checking:
//!
//! ### Core Orchestration (This Module - state.rs)
//! - **Entry Points**: `check_source_file`, `check_statement`
//! - **Type Resolution**: `get_type_of_node`, `get_type_of_symbol`
//! - **Caching & Lifecycle**: `cache_symbol_type`, node type cache management
//! - **Delegation**: Coordinates calls to specialized modules
//!
//! ## Extracted Modules
//!
//! ### Type Computation (`type_computation.rs` - 3,189 lines)
//! - `get_type_of_binary_expression`
//! - `get_type_of_call_expression`
//! - `get_type_of_property_access`
//! - `get_type_of_element_access`
//! - `get_type_of_object_literal`
//! - `get_type_of_array_literal`
//! - And 30+ other type computation functions
//!
//! ### Type Checking (`type_checking.rs` - 9,556 lines)
//! - **Section 1-54**: Organized by functionality
//! - Declaration checking (classes, interfaces, enums)
//! - Statement checking (if, while, for, return)
//! - Property access validation
//! - Constructor checking
//! - Function signature validation
//!
//! ### Symbol Resolution (`symbol_resolver.rs` - 1,380 lines)
//! - `resolve_type_to_symbol`
//! - `resolve_value_symbol`
//! - `resolve_heritage_symbol`
//! - Private brand checking
//! - Import/Export resolution
//!
//! ### Flow Analysis (`flow_analysis.rs` - 1,511 lines)
//! - Definite assignment checking
//! - Type narrowing (typeof, discriminant)
//! - Control flow analysis
//! - TDZ (temporal dead zone) detection
//!
//! ### Error Reporting (`error_reporter.rs` - 1,923 lines)
//! - All `error_*` methods
//! - Diagnostic formatting
//! - Error reporting with detailed reasons
//!
//! ## Remaining in state.rs (~12,974 lines)
//!
//! The code remaining in this file is primarily:
//! 1. **Orchestration** (~4,000 lines): Entry points that coordinate between modules
//! 2. **Caching** (~2,000 lines): Node type cache, symbol type cache management
//! 3. **Dispatchers** (~3,000 lines): `compute_type_of_node` delegates to `type_computation` functions
//! 4. **Type Relations** (~2,000 lines): `is_assignable_to`, `is_subtype_of` (wrapper around solver)
//! 5. **Constructor/Class Helpers** (~2,000 lines): Complex type resolution for classes and inheritance
//!
//! ## Performance Optimizations
//!
//! - **Node Type Cache**: Avoids recomputing types for the same node
//! - **Symbol Type Cache**: Caches computed types for symbols
//! - **Fuel Management**: Prevents infinite loops and timeouts
//! - **Cycle Detection**: Detects circular type references
//!
//! ## Usage
//!
//! ```rust,ignore
//! use crate::state::CheckerState;
//!
//! let mut checker = CheckerState::new(&arena, &binder, &types, file_name, options);
//! checker.check_source_file(root_idx);
//! ```
//!
//! # Step 12: Orchestration Layer Documentation ✅ COMPLETE
//!
//! **Date**: 2026-01-24
//! **Status**: Documentation complete
//! **Lines**: 12,974 (50.5% reduction from 26,217 original)
//! **Extracted**: 17,559 lines across 5 specialized modules
//!
//! The 2,000 line target was deemed unrealistic as the remaining code is
//! necessary orchestration that cannot be extracted without:
//! - Breaking the clean delegation pattern to specialized modules
//! - Creating circular dependencies between modules
//! - Duplicating shared state management code

use crate::CheckerContext;
use crate::context::CheckerOptions;
use tsz_binder::BinderState;
use tsz_binder::SymbolId;
use tsz_parser::parser::NodeIndex;
use tsz_parser::parser::node::NodeArena;
use tsz_parser::parser::syntax_kind_ext;
use tsz_solver::{QueryDatabase, TypeId, substitute_this_type};

thread_local! {
    /// Shared depth counter for all cross-arena delegation points.
    /// Prevents stack overflow from deeply nested CheckerState creation.
    static CROSS_ARENA_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

// =============================================================================
// CheckerState
// =============================================================================

/// Type checker state using `NodeArena` and Solver type system.
///
/// This is a performance-optimized checker that works directly with the
/// cache-friendly Node architecture and uses the solver's `TypeInterner`
/// for structural type equality.
///
/// The state is stored in a `CheckerContext` which can be shared with
/// specialized checker modules (expressions, statements, declarations).
pub struct CheckerState<'a> {
    /// Shared checker context containing all state.
    pub ctx: CheckerContext<'a>,
}

// Re-export from centralized limits — do NOT redefine these here.
pub use tsz_common::limits::MAX_CALL_DEPTH;
pub use tsz_common::limits::MAX_INSTANTIATION_DEPTH;
pub use tsz_common::limits::MAX_TREE_WALK_ITERATIONS;
pub use tsz_common::limits::MAX_TYPE_RESOLUTION_OPS;

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum EnumKind {
    Numeric,
    String,
    Mixed,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum MemberAccessLevel {
    Private,
    Protected,
}

#[derive(Clone, Debug)]
pub(crate) struct MemberAccessInfo {
    pub(crate) level: MemberAccessLevel,
    pub(crate) declaring_class_idx: NodeIndex,
    pub(crate) declaring_class_name: String,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum MemberLookup {
    NotFound,
    Public,
    Restricted(MemberAccessLevel),
}

// Re-export flow analysis types for internal use
pub(crate) use crate::flow_analysis::{ComputedKey, PropertyKey};

/// Mode for resolving parameter types during extraction.
/// Used to consolidate duplicate parameter extraction functions.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum ParamTypeResolutionMode {
    /// Use `get_type_from_type_node_in_type_literal` - for type literal contexts
    InTypeLiteral,
    /// Use `get_type_from_type_node` - for declaration contexts
    FromTypeNode,
    /// Use `get_type_of_node` - for expression/general contexts
    OfNode,
}

// =============================================================================
// AssignabilityOverrideProvider Implementation
// =============================================================================

/// Helper struct that implements `AssignabilityOverrideProvider` by delegating
/// to `CheckerState` methods. Captures the `TypeEnvironment` reference.
pub(crate) struct CheckerOverrideProvider<'a, 'b> {
    checker: &'a CheckerState<'b>,
    env: Option<&'a tsz_solver::TypeEnvironment>,
}

impl<'a, 'b> CheckerOverrideProvider<'a, 'b> {
    pub(crate) const fn new(
        checker: &'a CheckerState<'b>,
        env: Option<&'a tsz_solver::TypeEnvironment>,
    ) -> Self {
        Self { checker, env }
    }
}

impl<'a, 'b> tsz_solver::AssignabilityOverrideProvider for CheckerOverrideProvider<'a, 'b> {
    fn enum_assignability_override(&self, _source: TypeId, _target: TypeId) -> Option<bool> {
        // Delegate to Solver's enumeration assignability override.
        // The Solver's CompatChecker now has complete enumeration logic:
        // - Parent identity checks (E.A -> E)
        // - String enumeration opacity (StringEnum -> string rejected)
        // - Member -> member nominality (E.A -> E.B rejected)
        // - Rule #7 numeric enumeration assignability (number -> numeric enumeration TYPE allowed)
        // Returning None allows the Solver to handle all enumeration assignability checks.
        None
    }

    fn abstract_constructor_assignability_override(
        &self,
        source: TypeId,
        target: TypeId,
    ) -> Option<bool> {
        self.checker
            .abstract_constructor_assignability_override(source, target, self.env)
    }

    fn constructor_accessibility_override(&self, source: TypeId, target: TypeId) -> Option<bool> {
        self.checker
            .constructor_accessibility_override(source, target, self.env)
    }
}

impl<'a> CheckerState<'a> {
    /// Create a new `CheckerState`.
    ///
    /// # Arguments
    /// * `arena` - The AST node arena
    /// * `binder` - The binder state with symbols
    /// * `types` - The shared type interner (for thread-safe type deduplication)
    /// * `file_name` - The source file name
    /// * `compiler_options` - Compiler options for type checking
    pub fn new(
        arena: &'a NodeArena,
        binder: &'a BinderState,
        types: &'a dyn QueryDatabase,
        file_name: String,
        compiler_options: CheckerOptions,
    ) -> Self {
        CheckerState {
            ctx: CheckerContext::new(arena, binder, types, file_name, compiler_options),
        }
    }

    /// Create a new `CheckerState` with a shared `DefinitionStore`.
    ///
    /// This ensures that all type definitions (interfaces, type aliases, etc.) across
    /// different files and lib contexts share the same `DefId` namespace, preventing
    /// `DefId` collisions.
    ///
    /// # Arguments
    /// * `definition_store` - Shared `DefinitionStore` (wrapped in Arc for thread-safety)
    /// * Other args same as `new()`
    pub fn new_with_shared_def_store(
        arena: &'a NodeArena,
        binder: &'a BinderState,
        types: &'a dyn QueryDatabase,
        file_name: String,
        compiler_options: CheckerOptions,
        definition_store: std::sync::Arc<tsz_solver::def::DefinitionStore>,
    ) -> Self {
        CheckerState {
            ctx: CheckerContext::new_with_shared_def_store(
                arena,
                binder,
                types,
                file_name,
                compiler_options,
                definition_store,
            ),
        }
    }

    /// Create a new `CheckerState` with a persistent cache.
    /// This allows reusing type checking results from previous queries.
    ///
    /// # Arguments
    /// * `arena` - The AST node arena
    /// * `binder` - The binder state with symbols
    /// * `types` - The shared type interner
    /// * `file_name` - The source file name
    /// * `cache` - The persistent type cache from previous queries
    /// * `compiler_options` - Compiler options for type checking
    pub fn with_cache(
        arena: &'a NodeArena,
        binder: &'a BinderState,
        types: &'a dyn QueryDatabase,
        file_name: String,
        cache: crate::TypeCache,
        compiler_options: CheckerOptions,
    ) -> Self {
        CheckerState {
            ctx: CheckerContext::with_cache(
                arena,
                binder,
                types,
                file_name,
                cache,
                compiler_options,
            ),
        }
    }

    /// Create a child `CheckerState` that shares the parent's caches.
    /// This is used for temporary checkers (e.g., cross-file symbol resolution)
    /// to ensure cache results are not lost (fixes Cache Isolation Bug).
    pub fn with_parent_cache(
        arena: &'a NodeArena,
        binder: &'a BinderState,
        types: &'a dyn QueryDatabase,
        file_name: String,
        compiler_options: CheckerOptions,
        parent: &Self,
    ) -> Self {
        CheckerState {
            ctx: CheckerContext::with_parent_cache(
                arena,
                binder,
                types,
                file_name,
                compiler_options,
                &parent.ctx,
            ),
        }
    }

    /// Thread-local guard for cross-arena delegation depth.
    /// All cross-arena delegation points (`delegate_cross_arena_symbol_resolution`,
    /// `get_type_params_for_symbol`, `type_of_value_declaration`) MUST call this
    /// before creating a child `CheckerState`. Returns true if delegation is allowed.
    pub(crate) fn enter_cross_arena_delegation() -> bool {
        let d = CROSS_ARENA_DEPTH.with(std::cell::Cell::get);
        if d >= 5 {
            return false;
        }
        CROSS_ARENA_DEPTH.with(|c| c.set(d + 1));
        true
    }

    /// Decrement the cross-arena delegation depth counter.
    pub(crate) fn leave_cross_arena_delegation() {
        CROSS_ARENA_DEPTH.with(|c| c.set(c.get().saturating_sub(1)));
    }

    fn should_apply_flow_narrowing_for_identifier(&self, idx: NodeIndex) -> bool {
        use tsz_binder::symbol_flags;
        use tsz_scanner::SyntaxKind;

        if self.ctx.skip_flow_narrowing {
            return false;
        }

        let Some(node) = self.ctx.arena.get(idx) else {
            return false;
        };

        if node.kind == SyntaxKind::ThisKeyword as u16 {
            return true;
        }

        if node.kind != SyntaxKind::Identifier as u16 {
            return false;
        }

        let Some(sym_id) = self
            .ctx
            .binder
            .get_node_symbol(idx)
            .or_else(|| self.ctx.binder.resolve_identifier(self.ctx.arena, idx))
        else {
            return false;
        };
        let Some(symbol) = self.ctx.binder.get_symbol(sym_id) else {
            return false;
        };

        if (symbol.flags & symbol_flags::VARIABLE) == 0 {
            return false;
        }

        let mut value_decl = symbol.value_declaration;
        if value_decl.is_none() {
            return true;
        }

        let Some(mut decl_node) = self.ctx.arena.get(value_decl) else {
            return true;
        };
        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 {
            return true;
        }
        if !self.is_const_variable_declaration(value_decl) {
            return true;
        }

        let Some(var_decl) = self.ctx.arena.get_variable_declaration(decl_node) else {
            return true;
        };
        if var_decl.type_annotation.is_some() || var_decl.initializer.is_none() {
            return true;
        }

        let Some(init_node) = self.ctx.arena.get(var_decl.initializer) else {
            return true;
        };
        !(init_node.kind == syntax_kind_ext::OBJECT_LITERAL_EXPRESSION
            || init_node.kind == syntax_kind_ext::ARRAY_LITERAL_EXPRESSION)
    }

    /// Check if we are currently inside a cross-arena delegation.
    /// Used to skip position-based checks (like TDZ) that compare node positions
    /// from different arenas.
    pub(crate) fn is_in_cross_arena_delegation() -> bool {
        CROSS_ARENA_DEPTH.with(|c| c.get() > 0)
    }

    /// Check if the source file has any parse errors.
    ///
    /// This flag is set by the driver before type checking based on parse diagnostics.
    /// It's used to suppress certain type-level diagnostics when the file
    /// has syntax errors (e.g., JSON files parsed as TypeScript).
    pub(crate) const fn has_parse_errors(&self) -> bool {
        self.ctx.has_parse_errors
    }

    /// Check if the source file has real syntax errors (not just conflict markers).
    /// Conflict markers (TS1185) are treated as trivia and don't affect AST structure,
    /// so they should not suppress TS2304 errors.
    pub(crate) const fn has_syntax_parse_errors(&self) -> bool {
        self.ctx.has_syntax_parse_errors
    }

    /// Check if a node's span overlaps with or is very close to a parse error position.
    /// Used to suppress cascading checker diagnostics (e.g. TS2391, TS2364) when the
    /// node is likely a parser-recovery artifact.
    /// Check if a parse error falls directly within the node's span (no margin).
    /// Used for tight suppression checks where the generous margin of
    /// `node_has_nearby_parse_error` would cause false positives.
    pub(crate) fn node_span_contains_parse_error(&self, idx: NodeIndex) -> bool {
        if !self.has_syntax_parse_errors() || self.ctx.syntax_parse_error_positions.is_empty() {
            return false;
        }
        let Some(node) = self.ctx.arena.get(idx) else {
            return false;
        };
        for &err_pos in &self.ctx.syntax_parse_error_positions {
            if err_pos >= node.pos && err_pos < node.end {
                return true;
            }
        }
        false
    }

    pub(crate) fn node_has_nearby_parse_error(&self, idx: NodeIndex) -> bool {
        if !self.has_syntax_parse_errors() || self.ctx.syntax_parse_error_positions.is_empty() {
            return false;
        }
        let Some(node) = self.ctx.arena.get(idx) else {
            return false;
        };
        // A generous window: if any parse error is within the node's span or up to
        // 8 bytes beyond it, consider the node tainted by parser recovery.
        const MARGIN: u32 = 8;
        let node_start = node.pos.saturating_sub(MARGIN);
        let node_end = node.end.saturating_add(MARGIN);
        for &err_pos in &self.ctx.syntax_parse_error_positions {
            if err_pos >= node_start && err_pos <= node_end {
                return true;
            }
        }
        false
    }

    /// Apply `this` type substitution to a method call's return type.
    ///
    /// When a method returns `this`, the return type should be the type of the receiver.
    /// For `obj.method()` where method returns `this`, we substitute `ThisType` with typeof obj.
    pub(crate) fn apply_this_substitution_to_call_return(
        &mut self,
        return_type: tsz_solver::TypeId,
        call_expression: tsz_parser::parser::NodeIndex,
    ) -> tsz_solver::TypeId {
        use tsz_solver::TypeId;

        // Fast path: intrinsic types can't contain ThisType
        if return_type.is_intrinsic() {
            return return_type;
        }

        // Try to extract the receiver from the call expression.
        // The call_expression parameter is actually the callee expression (call.expression),
        // which for method calls is a PropertyAccessExpression.
        // For `obj.method()`, this is `obj.method`, whose `.expression` is `obj`.
        let node = match self.ctx.arena.get(call_expression) {
            Some(n) => n,
            None => return return_type,
        };

        if let Some(access) = self.ctx.arena.get_access_expr(node) {
            let receiver_type = self.get_type_of_node(access.expression);
            if receiver_type != TypeId::ERROR && receiver_type != TypeId::ANY {
                return substitute_this_type(self.ctx.types, return_type, receiver_type);
            }
        }

        return_type
    }

    /// Create a new `CheckerState` with explicit compiler options.
    ///
    /// # Arguments
    /// * `arena` - The AST node arena
    /// * `binder` - The binder state with symbols
    /// * `types` - The shared type interner
    /// * `file_name` - The source file name
    /// * `compiler_options` - Compiler options for type checking
    pub fn with_options(
        arena: &'a NodeArena,
        binder: &'a BinderState,
        types: &'a dyn QueryDatabase,
        file_name: String,
        compiler_options: &CheckerOptions,
    ) -> Self {
        CheckerState {
            ctx: CheckerContext::with_options(arena, binder, types, file_name, compiler_options),
        }
    }

    /// Create a new `CheckerState` with explicit compiler options and a shared `DefinitionStore`.
    ///
    /// This is used in parallel checking to ensure all files share the same `DefId` namespace.
    pub fn with_options_and_shared_def_store(
        arena: &'a NodeArena,
        binder: &'a BinderState,
        types: &'a dyn QueryDatabase,
        file_name: String,
        compiler_options: &CheckerOptions,
        definition_store: std::sync::Arc<tsz_solver::def::DefinitionStore>,
    ) -> Self {
        let compiler_options = compiler_options.clone().apply_strict_defaults();
        CheckerState {
            ctx: CheckerContext::new_with_shared_def_store(
                arena,
                binder,
                types,
                file_name,
                compiler_options,
                definition_store,
            ),
        }
    }

    /// Create a new `CheckerState` with explicit compiler options and a persistent cache.
    pub fn with_cache_and_options(
        arena: &'a NodeArena,
        binder: &'a BinderState,
        types: &'a dyn QueryDatabase,
        file_name: String,
        cache: crate::TypeCache,
        compiler_options: &CheckerOptions,
    ) -> Self {
        CheckerState {
            ctx: CheckerContext::with_cache_and_options(
                arena,
                binder,
                types,
                file_name,
                cache,
                compiler_options,
            ),
        }
    }

    /// Extract the persistent cache from this checker.
    /// This allows saving type checking results for future queries.
    pub fn extract_cache(self) -> crate::TypeCache {
        self.ctx.extract_cache()
    }

    // =========================================================================
    // Symbol Type Caching
    // =========================================================================

    /// Cache a computed symbol type for fast lookup and incremental type checking.
    ///
    /// This function stores the computed type of a symbol in the `symbol_types` cache,
    /// allowing subsequent lookups to avoid recomputing the type.
    ///
    /// ## Caching Strategy:
    /// - Types are cached after first computation
    /// - Cache key is the `SymbolId`
    /// - Cache persists for the lifetime of the type check
    ///
    /// ## Incremental Type Checking:
    /// - When a symbol changes, its cache entry is invalidated
    /// - Dependent symbols are re-computed on next access
    /// - Enables efficient re-typechecking of modified files
    ///
    /// ## Cache Invalidation:
    /// - Symbol modifications trigger dependency tracking
    /// - Dependent symbols are tracked via `record_symbol_dependency`
    /// - Cache is cleared for invalidated symbols
    ///
    /// ## Performance:
    /// - Avoids expensive type recomputation
    /// - Critical for performance in large codebases
    /// - Most symbol types are looked up multiple times
    ///
    /// ## TypeScript Examples:
    /// ```typescript
    /// interface User {
    ///   name: string;
    ///   age: number;
    /// }
    /// let user: User;
    /// // First lookup: computes User type, caches it
    /// // Second lookup: returns cached User type (fast)
    ///
    /// function process(u: User) {
    ///   // User type parameter is cached
    ///   // Multiple uses of u resolve to the same cached type
    /// }
    /// ```
    pub(crate) fn cache_symbol_type(&mut self, sym_id: SymbolId, type_id: TypeId) {
        self.ctx.symbol_types.insert(sym_id, type_id);
    }

    pub(crate) fn record_symbol_dependency(&mut self, dependency: SymbolId) {
        let Some(&current) = self.ctx.symbol_dependency_stack.last() else {
            return;
        };
        if current == dependency {
            return;
        }
        self.ctx
            .symbol_dependencies
            .entry(current)
            .or_default()
            .insert(dependency);
    }

    pub(crate) fn push_symbol_dependency(&mut self, sym_id: SymbolId, clear_deps: bool) {
        if clear_deps {
            self.ctx.symbol_dependencies.remove(&sym_id);
        }
        self.ctx.symbol_dependency_stack.push(sym_id);
    }

    pub(crate) fn pop_symbol_dependency(&mut self) {
        self.ctx.symbol_dependency_stack.pop();
    }

    /// Infer and cache parameter types using contextual typing.
    ///
    /// This is needed for cases like:
    /// `export function filter<T>(arr: T[], predicate: (item: T) => boolean) { for (const item of arr) { ... } }`
    /// where `item`'s type comes from the contextual type of `arr`.
    pub(crate) fn infer_parameter_types_from_context(&mut self, params: &[NodeIndex]) {
        for &param_idx in params {
            let Some(param_node) = self.ctx.arena.get(param_idx) else {
                continue;
            };
            let Some(param) = self.ctx.arena.get_parameter(param_node) else {
                continue;
            };

            // Only infer when there's no annotation and no default value.
            if param.type_annotation.is_some() || param.initializer.is_some() {
                continue;
            }

            let Some(sym_id) = self
                .ctx
                .binder
                .get_node_symbol(param.name)
                .or_else(|| self.ctx.binder.get_node_symbol(param_idx))
            else {
                continue;
            };

            // Skip destructuring parameters here (they are handled separately by binding pattern inference).
            if let Some(name_node) = self.ctx.arena.get(param.name)
                && (name_node.kind == syntax_kind_ext::OBJECT_BINDING_PATTERN
                    || name_node.kind == syntax_kind_ext::ARRAY_BINDING_PATTERN)
            {
                continue;
            }

            // If we already have a concrete cached type, keep it.
            if let Some(&cached) = self.ctx.symbol_types.get(&sym_id)
                && cached != TypeId::UNKNOWN
                && cached != TypeId::ANY
                && cached != TypeId::ERROR
            {
                continue;
            }

            // Use contextual typing by resolving the parameter's identifier in its function scope.
            let inferred = self.get_type_of_identifier(param.name);
            if inferred != TypeId::UNKNOWN && inferred != TypeId::ERROR {
                self.cache_symbol_type(sym_id, inferred);
            }
        }
    }

    /// Push an expected return type onto the stack when entering a function.
    ///
    /// This function is called when entering a function to track the expected
    /// return type. The stack is used to validate that all return statements
    /// are compatible with the function's declared return type.
    ///
    /// **Return Type Stack:**
    /// - Functions can be nested (inner functions, closures)
    /// - Stack tracks return type for each nesting level
    /// - Pushed when entering function, popped when exiting
    ///
    /// **Use Cases:**
    /// - Function declarations: `function foo(): string {}`
    /// - Function expressions: `const f = function(): number {}`
    /// - Arrow functions: `const f = (): boolean => {}`
    /// - Method declarations
    ///
    /// **Validation:**
    /// - Return statements are checked against the top of stack
    /// - Enables early error detection for mismatched return types
    ///
    pub fn push_return_type(&mut self, return_type: TypeId) {
        self.ctx.push_return_type(return_type);
    }

    /// Pop an expected return type from the stack when exiting a function.
    ///
    /// This function is called when exiting a function to remove the expected
    /// return type from the stack. This restores the previous return type for
    /// nested functions.
    ///
    /// **Stack Management:**
    /// - Pops the most recently pushed return type
    /// - Restores previous return type (for nested functions)
    /// - Must be called once per push (balanced push/pop)
    ///
    pub fn pop_return_type(&mut self) {
        self.ctx.pop_return_type();
    }

    /// Get the current expected return type if in a function.
    ///
    /// Returns the return type at the top of the return type stack.
    /// Returns None if not inside a function (stack is empty).
    ///
    /// **Use Cases:**
    /// - Validating return statements: `return value;`
    /// - Checking function body completeness
    /// - Contextual typing for return expressions
    ///
    /// **Nesting:**
    /// - Returns the innermost function's return type
    /// - Handles nested functions and closures correctly
    ///
    pub fn current_return_type(&self) -> Option<TypeId> {
        self.ctx.current_return_type()
    }

    // =========================================================================
    // Diagnostics (delegated to CheckerContext)
    // =========================================================================

    /// Add an error diagnostic to the diagnostics collection.
    ///
    /// This is the main entry point for reporting type errors. All error reporting
    /// flows through this function (directly or through helper functions).
    ///
    /// **Diagnostic Components:**
    /// - **start**: Byte offset of error start in file
    /// - **length**: Length of the error span in bytes
    /// - **message**: Human-readable error message
    /// - **code**: TypeScript error code (`TSxxxx`)
    ///
    /// **Error Categories:**
    /// - **Error**: Type errors that prevent compilation
    /// - **Warning**: Potential issues that don't prevent compilation
    /// - **Suggestion**: Code quality suggestions
    ///
    /// **Error Codes:**
    /// - TS2304: Cannot find name
    /// - TS2322: Type is not assignable
    /// - TS2339: Property does not exist
    /// - And many more...
    ///
    /// **Use Cases:**
    /// - Direct error emission: `self.error(start, length, message, 2304)`
    /// - Through helper functions: `error_cannot_find_name_at`, `error_type_not_assignable_at`, etc.
    /// - Error messages are formatted with type information
    ///
    pub fn error(&mut self, start: u32, length: u32, message: String, code: u32) {
        self.ctx.error(start, length, message, code);
    }

    /// Get the (start, end) span of a node for error reporting.
    ///
    /// This function retrieves the position information of an AST node,
    /// which is used for error reporting and IDE features.
    ///
    /// **Span Information:**
    /// - Returns `(start, end)` tuple of byte offsets
    /// - Start is the byte offset of the node's first character
    /// - End is the byte offset of the node's last character
    /// - Returns None if node doesn't exist in arena
    ///
    /// **Use Cases:**
    /// - Error reporting: `self.error(start, end - start, message, code)`
    /// - Diagnostic spans: Point to the problematic code
    /// - Quick info: Hover information for IDE
    /// - Code navigation: Jump to definition references
    ///
    pub fn get_node_span(&self, idx: NodeIndex) -> Option<(u32, u32)> {
        self.ctx.get_node_span(idx)
    }

    /// Emit an error diagnostic at a specific source position.
    pub fn emit_error_at(&mut self, start: u32, length: u32, message: &str, code: u32) {
        self.ctx
            .diagnostics
            .push(crate::diagnostics::Diagnostic::error(
                self.ctx.file_name.clone(),
                start,
                length,
                message.to_string(),
                code,
            ));
    }

    // =========================================================================
    // Symbol Resolution
    // =========================================================================

    /// Get the symbol for a node index.
    pub fn get_symbol_at_node(&self, idx: NodeIndex) -> Option<SymbolId> {
        self.ctx.binder.get_node_symbol(idx)
    }

    /// Get the symbol by name from file locals.
    pub fn get_symbol_by_name(&self, name: &str) -> Option<SymbolId> {
        self.ctx.binder.file_locals.get(name)
    }

    // =========================================================================
    // Type Resolution - Core Methods
    // =========================================================================

    /// Get the type of a node.
    /// Get the type of an AST node with caching and circular reference detection.
    ///
    /// This is the main entry point for type computation. All type checking ultimately
    /// flows through this function to get the type of AST nodes.
    ///
    /// ## Caching:
    /// - Types are cached in `ctx.node_types` by node index
    /// - Subsequent calls for the same node return the cached type
    /// - Cache is checked first before computation
    ///
    /// ## Fuel Management:
    /// - Consumes fuel on each call to prevent infinite loops
    /// - Returns ERROR if fuel is exhausted (prevents type checker timeout)
    /// - Fuel is reset between file check operations
    ///
    /// ## Circular Reference Detection:
    /// - Tracks currently resolving nodes in `ctx.node_resolution_set`
    /// - Returns ERROR if a circular reference is detected
    /// - Helps expose type resolution bugs early
    ///
    /// ## Examples:
    /// ```typescript
    /// let x = 42;           // Type: number
    /// let y = x;            // Type: number (from cache)
    /// let z = x + y;        // Types: x=number, y=number, result=number
    /// ```
    ///
    /// ## Performance:
    /// - Caching prevents redundant type computation
    /// - Circular reference detection prevents infinite recursion
    /// - Fuel management ensures termination even for malformed code
    pub fn get_type_of_node(&mut self, idx: NodeIndex) -> TypeId {
        // Check cache first
        if let Some(&cached) = self.ctx.node_types.get(&idx.0) {
            // CRITICAL FIX: For identifiers, apply flow narrowing to the cached type
            // Identifiers can have different types in different control flow branches.
            // Example: if (typeof x === "string") { x.toUpperCase(); }
            // The cache stores the declared type "string | number", but inside the if block,
            // x should have the narrowed type "string".
            //
            // Only apply narrowing if skip_flow_narrowing is false (respects testing/special contexts)
            let should_narrow = self.should_apply_flow_narrowing_for_identifier(idx);

            if should_narrow {
                // Apply flow narrowing to get the context-specific type
                let narrowed = self.apply_flow_narrowing(idx, cached);
                // FIX: If flow analysis returns a widened version of a literal cached type
                // (e.g., cached="foo" but flow returns string), use the cached type.
                // This prevents zombie freshness where flow analysis undoes literal preservation.
                // IMPORTANT: Evaluate the cached type first to expand type aliases
                // and lazy references, so widen_type can see the actual union members.
                if narrowed != cached && narrowed != TypeId::ERROR {
                    let evaluated_cached = self.evaluate_type_for_assignability(cached);
                    let widened_cached =
                        tsz_solver::widening::widen_type(self.ctx.types, evaluated_cached);
                    if widened_cached == narrowed {
                        return cached;
                    }
                }
                return narrowed;
            }

            // TS 5.1+ divergent accessor types: when in a write context
            // (skip_flow_narrowing is true, used by get_type_of_assignment_target),
            // property/element access nodes may have a different write type
            // than the cached read type. Bypass the cache so
            // get_type_of_property_access can return the write_type.
            if self.ctx.skip_flow_narrowing
                && self.ctx.arena.get(idx).is_some_and(|node| {
                    use tsz_parser::parser::syntax_kind_ext;
                    node.kind == syntax_kind_ext::PROPERTY_ACCESS_EXPRESSION
                        || node.kind == syntax_kind_ext::ELEMENT_ACCESS_EXPRESSION
                })
            {
                // Fall through to recompute with write-type awareness
            } else {
                tracing::trace!(idx = idx.0, type_id = cached.0, "(cached) get_type_of_node");
                return cached;
            }
        }

        // Check fuel - return ERROR if exhausted to prevent timeout
        if !self.ctx.consume_fuel() {
            // CRITICAL: Cache ERROR immediately to prevent repeated deep recursion
            self.ctx.node_types.insert(idx.0, TypeId::ERROR);
            return TypeId::ERROR;
        }

        // Check for circular reference - return ERROR to expose resolution bugs
        if self.ctx.node_resolution_set.contains(&idx) {
            // CRITICAL: Cache ERROR immediately to prevent repeated deep recursion
            self.ctx.node_types.insert(idx.0, TypeId::ERROR);
            return TypeId::ERROR;
        }

        // Push onto resolution stack
        self.ctx.node_resolution_stack.push(idx);
        self.ctx.node_resolution_set.insert(idx);

        // CRITICAL: Pre-cache ERROR placeholder to break deep recursion chains
        // This ensures that mid-resolution lookups get cached ERROR immediately
        // We'll overwrite this with the real result later (line 650)
        self.ctx.node_types.insert(idx.0, TypeId::ERROR);

        let result = self.compute_type_of_node(idx);

        // Pop from resolution stack
        self.ctx.node_resolution_stack.pop();
        self.ctx.node_resolution_set.remove(&idx);

        // Cache result - identifiers cache their DECLARED type,
        // but get_type_of_node applies flow narrowing when returning cached identifier types
        self.ctx.node_types.insert(idx.0, result);

        let should_narrow_computed = self.should_apply_flow_narrowing_for_identifier(idx);

        if should_narrow_computed {
            let mut narrowed = self.apply_flow_narrowing(idx, result);
            // FIX: Flow narrowing may return the original fresh type from the initializer
            // expression, undoing the freshness stripping that get_type_of_identifier
            // already performed. Re-apply freshness stripping to prevent "Zombie Freshness"
            // where excess property checks fire on non-literal variable references.
            if !self.ctx.compiler_options.sound_mode {
                use tsz_solver::relations::freshness::{is_fresh_object_type, widen_freshness};
                if is_fresh_object_type(self.ctx.types, narrowed) {
                    narrowed = widen_freshness(self.ctx.types, narrowed);
                }
            }
            // FIX: For mutable variables with non-widened literal declared types
            // (e.g., `declare var a: "foo"; let b = a` → b has declared type "foo"),
            // flow analysis may return the widened primitive (string) even though
            // there's no actual narrowing. Detect this case: if widen(result) == narrowed,
            // the flow is just widening our literal, not genuinely narrowing.
            // IMPORTANT: Evaluate the result type first to expand type aliases
            // and lazy references, so widen_type can see the actual union members.
            if narrowed != result && narrowed != TypeId::ERROR {
                let evaluated_result = self.evaluate_type_for_assignability(result);
                let widened_result =
                    tsz_solver::widening::widen_type(self.ctx.types, evaluated_result);
                if widened_result == narrowed {
                    // Flow just widened our literal type - use the original result
                    narrowed = result;
                }
            }
            tracing::trace!(
                idx = idx.0,
                type_id = result.0,
                narrowed_type_id = narrowed.0,
                "get_type_of_node (computed+narrowed)"
            );
            return narrowed;
        }

        tracing::trace!(idx = idx.0, type_id = result.0, "get_type_of_node");
        result
    }

    /// Clear type cache for a node and all its children recursively.
    ///
    /// This is used when we need to recompute types with different contextual information,
    /// such as when checking return statements with contextual return types.
    pub(crate) fn clear_type_cache_recursive(&mut self, idx: NodeIndex) {
        use tsz_parser::parser::syntax_kind_ext;

        if idx.is_none() {
            return;
        }

        // Clear this node's cache
        self.ctx.node_types.remove(&idx.0);

        // Recursively clear children
        let Some(node) = self.ctx.arena.get(idx) else {
            return;
        };

        match node.kind {
            k if k == syntax_kind_ext::ARRAY_LITERAL_EXPRESSION => {
                if let Some(array) = self.ctx.arena.get_literal_expr(node) {
                    for &elem_idx in &array.elements.nodes {
                        self.clear_type_cache_recursive(elem_idx);
                    }
                }
            }
            k if k == syntax_kind_ext::OBJECT_LITERAL_EXPRESSION => {
                if let Some(obj) = self.ctx.arena.get_literal_expr(node) {
                    for &prop_idx in &obj.elements.nodes {
                        self.clear_type_cache_recursive(prop_idx);
                    }
                }
            }
            k if k == syntax_kind_ext::PROPERTY_ASSIGNMENT => {
                if let Some(prop) = self.ctx.arena.get_property_assignment(node) {
                    self.clear_type_cache_recursive(prop.initializer);
                }
            }
            k if k == syntax_kind_ext::PARENTHESIZED_EXPRESSION => {
                if let Some(paren) = self.ctx.arena.get_parenthesized(node) {
                    self.clear_type_cache_recursive(paren.expression);
                }
            }
            k if k == syntax_kind_ext::CALL_EXPRESSION => {
                if let Some(call) = self.ctx.arena.get_call_expr(node) {
                    self.clear_type_cache_recursive(call.expression);
                    if let Some(ref args) = call.arguments {
                        for &arg_idx in &args.nodes {
                            self.clear_type_cache_recursive(arg_idx);
                        }
                    }
                }
            }
            k if k == syntax_kind_ext::BINARY_EXPRESSION => {
                if let Some(bin) = self.ctx.arena.get_binary_expr(node) {
                    self.clear_type_cache_recursive(bin.left);
                    self.clear_type_cache_recursive(bin.right);
                }
            }
            k if k == syntax_kind_ext::CONDITIONAL_EXPRESSION => {
                if let Some(cond) = self.ctx.arena.get_conditional_expr(node) {
                    self.clear_type_cache_recursive(cond.condition);
                    self.clear_type_cache_recursive(cond.when_true);
                    self.clear_type_cache_recursive(cond.when_false);
                }
            }
            k if k == syntax_kind_ext::SPREAD_ELEMENT => {
                if let Some(spread) = self.ctx.arena.get_unary_expr_ex(node) {
                    self.clear_type_cache_recursive(spread.expression);
                }
            }
            k if k == syntax_kind_ext::AS_EXPRESSION => {
                if let Some(as_expr) = self.ctx.arena.get_type_assertion(node) {
                    self.clear_type_cache_recursive(as_expr.expression);
                }
            }
            _ => {}
        }
    }

    pub(crate) fn is_keyword_type_used_as_value_position(&self, idx: NodeIndex) -> bool {
        use tsz_parser::parser::syntax_kind_ext;

        let Some(ext) = self.ctx.arena.get_extended(idx) else {
            return false;
        };
        let parent = ext.parent;
        if parent.is_none() {
            return false;
        }
        let Some(parent_node) = self.ctx.arena.get(parent) else {
            return false;
        };

        if matches!(
            parent_node.kind,
            k if k == syntax_kind_ext::EXPRESSION_STATEMENT
                || k == syntax_kind_ext::LABELED_STATEMENT
                || k == syntax_kind_ext::PROPERTY_ACCESS_EXPRESSION
                || k == syntax_kind_ext::ELEMENT_ACCESS_EXPRESSION
                || k == syntax_kind_ext::CALL_EXPRESSION
                || k == syntax_kind_ext::NEW_EXPRESSION
                || k == syntax_kind_ext::BINARY_EXPRESSION
                || k == syntax_kind_ext::RETURN_STATEMENT
                || k == syntax_kind_ext::VARIABLE_DECLARATION
                || k == syntax_kind_ext::PROPERTY_ASSIGNMENT
                || k == syntax_kind_ext::SHORTHAND_PROPERTY_ASSIGNMENT
                || k == syntax_kind_ext::ARRAY_LITERAL_EXPRESSION
                || k == syntax_kind_ext::PARENTHESIZED_EXPRESSION
                || k == syntax_kind_ext::CONDITIONAL_EXPRESSION
        ) {
            return true;
        }

        // Recovery path: malformed value expressions like `number[]` are parsed
        // through ARRAY_TYPE wrappers, but still need TS2693 at the keyword.
        if parent_node.kind == syntax_kind_ext::ARRAY_TYPE {
            let Some(parent_ext) = self.ctx.arena.get_extended(parent) else {
                return false;
            };
            let grandparent = parent_ext.parent;
            if grandparent.is_none() {
                return false;
            }
            let Some(grandparent_node) = self.ctx.arena.get(grandparent) else {
                return false;
            };
            return matches!(
                grandparent_node.kind,
                k if k == syntax_kind_ext::EXPRESSION_STATEMENT
                    || k == syntax_kind_ext::LABELED_STATEMENT
                    || k == syntax_kind_ext::PROPERTY_ACCESS_EXPRESSION
                    || k == syntax_kind_ext::ELEMENT_ACCESS_EXPRESSION
                    || k == syntax_kind_ext::CALL_EXPRESSION
                    || k == syntax_kind_ext::NEW_EXPRESSION
                    || k == syntax_kind_ext::BINARY_EXPRESSION
                    || k == syntax_kind_ext::RETURN_STATEMENT
                    || k == syntax_kind_ext::VARIABLE_DECLARATION
                    || k == syntax_kind_ext::PROPERTY_ASSIGNMENT
                    || k == syntax_kind_ext::SHORTHAND_PROPERTY_ASSIGNMENT
                    || k == syntax_kind_ext::ARRAY_LITERAL_EXPRESSION
                    || k == syntax_kind_ext::PARENTHESIZED_EXPRESSION
                    || k == syntax_kind_ext::CONDITIONAL_EXPRESSION
            );
        }

        false
    }

    /// Compute the type of a node (internal, not cached).
    ///
    /// This method first delegates to `ExpressionChecker` for expression type checking.
    /// If `ExpressionChecker` returns `TypeId::DELEGATE`, we fall back to the full
    /// `CheckerState` implementation that has access to symbol resolution, contextual
    /// typing, and other complex type checking features.
    pub(crate) fn compute_type_of_node(&mut self, idx: NodeIndex) -> TypeId {
        use crate::ExpressionChecker;

        // First, try ExpressionChecker for simple expression types
        // ExpressionChecker handles expressions that don't need full CheckerState context
        let expr_result = {
            let mut expr_checker = ExpressionChecker::new(&mut self.ctx);
            expr_checker.compute_type_uncached(idx)
        };

        let result = if expr_result != TypeId::DELEGATE {
            expr_result
        } else {
            // ExpressionChecker returned DELEGATE - use full CheckerState implementation
            self.compute_type_of_node_complex(idx)
        };

        // Validate regex literal flags against compilation target (TS1501)
        self.validate_regex_literal_flags(idx);

        result
    }

    /// Complex type computation that needs full `CheckerState` context.
    ///
    /// This is called when `ExpressionChecker` returns `TypeId::DELEGATE`,
    /// indicating the expression needs symbol resolution, contextual typing,
    /// or other features only available in `CheckerState`.
    fn compute_type_of_node_complex(&mut self, idx: NodeIndex) -> TypeId {
        use crate::dispatch::ExpressionDispatcher;

        let mut dispatcher = ExpressionDispatcher::new(self);
        dispatcher.dispatch_type_computation(idx)
    }

    // Type resolution, type analysis, type environment, and checking methods
    // are in state_type_resolution.rs, state_type_analysis.rs,
    // state_type_environment.rs, state_checking.rs, and state_checking_members.rs
}