tsz-solver 0.1.8

TypeScript type solver 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
//! Index access type evaluation.
//!
//! Handles TypeScript's index access types: `T[K]`
//! Including property access, array indexing, and tuple indexing.

use crate::instantiate::{TypeSubstitution, instantiate_type};
use crate::subtype::TypeResolver;
use crate::types::{
    IntrinsicKind, LiteralValue, MappedModifier, MappedTypeId, ObjectShape, ObjectShapeId,
    PropertyInfo, SymbolRef, TupleElement, TupleListId, TypeData, TypeId, TypeListId,
    TypeParamInfo,
};
use crate::utils;
use crate::visitor::{
    TypeVisitor, array_element_type, literal_number, literal_string, tuple_list_id, union_list_id,
};
use crate::{ApparentMemberKind, TypeDatabase};

use super::super::evaluate::{
    ARRAY_METHODS_RETURN_ANY, ARRAY_METHODS_RETURN_BOOLEAN, ARRAY_METHODS_RETURN_NUMBER,
    ARRAY_METHODS_RETURN_STRING, ARRAY_METHODS_RETURN_VOID, TypeEvaluator,
};
use super::apparent::make_apparent_method_type;

fn is_member(name: &str, list: &[&str]) -> bool {
    list.contains(&name)
}

/// Standalone helper to get array member kind.
/// Extracted from `TypeEvaluator` to be usable by visitors.
pub(crate) fn get_array_member_kind(name: &str) -> Option<ApparentMemberKind> {
    if name == "length" {
        return Some(ApparentMemberKind::Value(TypeId::NUMBER));
    }
    if is_member(name, ARRAY_METHODS_RETURN_ANY) {
        return Some(ApparentMemberKind::Method(TypeId::ANY));
    }
    if is_member(name, ARRAY_METHODS_RETURN_BOOLEAN) {
        return Some(ApparentMemberKind::Method(TypeId::BOOLEAN));
    }
    if is_member(name, ARRAY_METHODS_RETURN_NUMBER) {
        return Some(ApparentMemberKind::Method(TypeId::NUMBER));
    }
    if is_member(name, ARRAY_METHODS_RETURN_VOID) {
        return Some(ApparentMemberKind::Method(TypeId::VOID));
    }
    if is_member(name, ARRAY_METHODS_RETURN_STRING) {
        return Some(ApparentMemberKind::Method(TypeId::STRING));
    }
    None
}

struct IndexAccessVisitor<'a, 'b, R: TypeResolver> {
    evaluator: &'b mut TypeEvaluator<'a, R>,
    object_type: TypeId,
    index_type: TypeId,
}

impl<'a, 'b, R: TypeResolver> IndexAccessVisitor<'a, 'b, R> {
    fn evaluate_apparent_primitive(&mut self, kind: IntrinsicKind) -> Option<TypeId> {
        match kind {
            IntrinsicKind::String
            | IntrinsicKind::Number
            | IntrinsicKind::Boolean
            | IntrinsicKind::Bigint
            | IntrinsicKind::Symbol => {
                let shape = self.evaluator.apparent_primitive_shape(kind);
                Some(
                    self.evaluator
                        .evaluate_object_with_index(&shape, self.index_type),
                )
            }
            _ => None,
        }
    }

    /// Check if the index type is generic (deferrable).
    ///
    /// When evaluating an index access during generic instantiation,
    /// if the index is still a generic type (like a type parameter),
    /// we must defer evaluation instead of returning UNDEFINED.
    fn is_generic_index(&self) -> bool {
        let key = match self.evaluator.interner().lookup(self.index_type) {
            Some(k) => k,
            None => return false,
        };

        matches!(
            key,
            TypeData::TypeParameter(_)
                | TypeData::Infer(_)
                | TypeData::KeyOf(_)
                | TypeData::IndexAccess(_, _)
                | TypeData::Conditional(_)
                | TypeData::TemplateLiteral(_) // Templates might resolve to generic strings
                | TypeData::Intersection(_)
        )
    }

    fn evaluate_type_param(&mut self, param: &TypeParamInfo) -> Option<TypeId> {
        if let Some(constraint) = param.constraint {
            if constraint == self.object_type {
                Some(
                    self.evaluator
                        .interner()
                        .index_access(self.object_type, self.index_type),
                )
            } else {
                Some(
                    self.evaluator
                        .recurse_index_access(constraint, self.index_type),
                )
            }
        } else {
            Some(
                self.evaluator
                    .interner()
                    .index_access(self.object_type, self.index_type),
            )
        }
    }
}

impl<'a, 'b, R: TypeResolver> TypeVisitor for IndexAccessVisitor<'a, 'b, R> {
    type Output = Option<TypeId>;

    fn visit_intrinsic(&mut self, kind: IntrinsicKind) -> Self::Output {
        self.evaluate_apparent_primitive(kind)
    }

    fn visit_literal(&mut self, value: &LiteralValue) -> Self::Output {
        self.evaluator
            .apparent_literal_kind(value)
            .and_then(|kind| self.evaluate_apparent_primitive(kind))
    }

    fn visit_object(&mut self, shape_id: u32) -> Self::Output {
        let shape = self
            .evaluator
            .interner()
            .object_shape(ObjectShapeId(shape_id));

        let result = self
            .evaluator
            .evaluate_object_index(&shape.properties, self.index_type);

        // CRITICAL FIX: If we can't find the property, but the index is generic,
        // we must defer evaluation (return None) instead of returning UNDEFINED.
        // This prevents mapped type template evaluation from hardcoding UNDEFINED
        // during generic instantiation.
        if result == TypeId::UNDEFINED && self.is_generic_index() {
            return None;
        }

        Some(result)
    }

    fn visit_object_with_index(&mut self, shape_id: u32) -> Self::Output {
        let shape = self
            .evaluator
            .interner()
            .object_shape(ObjectShapeId(shape_id));

        let result = self
            .evaluator
            .evaluate_object_with_index(&shape, self.index_type);

        // CRITICAL FIX: Same deferral logic for objects with index signatures
        if result == TypeId::UNDEFINED && self.is_generic_index() {
            return None;
        }

        Some(result)
    }

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        let members = self.evaluator.interner().type_list(TypeListId(list_id));
        const MAX_UNION_INDEX_SIZE: usize = 100;
        if members.len() > MAX_UNION_INDEX_SIZE {
            self.evaluator.mark_depth_exceeded();
            return Some(TypeId::ERROR);
        }
        let mut results = Vec::new();
        for &member in members.iter() {
            if self.evaluator.is_depth_exceeded() {
                return Some(TypeId::ERROR);
            }
            let result = self.evaluator.recurse_index_access(member, self.index_type);
            if result == TypeId::ERROR && self.evaluator.is_depth_exceeded() {
                return Some(TypeId::ERROR);
            }
            if result != TypeId::UNDEFINED || self.evaluator.no_unchecked_indexed_access() {
                results.push(result);
            }
        }
        if results.is_empty() {
            return Some(TypeId::UNDEFINED);
        }
        Some(self.evaluator.interner().union(results))
    }

    fn visit_intersection(&mut self, list_id: u32) -> Self::Output {
        // For intersection types, evaluate all members and combine successful lookups.
        // Returning the first non-undefined result can incorrectly lock onto `never`
        // for mapped/index-signature helper intersections.
        let members = self.evaluator.interner().type_list(TypeListId(list_id));
        let mut results = Vec::new();
        for &member in members.iter() {
            let result = self.evaluator.recurse_index_access(member, self.index_type);
            if result == TypeId::ERROR {
                return Some(TypeId::ERROR);
            }
            if result != TypeId::UNDEFINED {
                results.push(result);
            }
        }
        if results.is_empty() {
            Some(TypeId::UNDEFINED)
        } else {
            Some(self.evaluator.interner().union(results))
        }
    }

    fn visit_lazy(&mut self, def_id: u32) -> Self::Output {
        // CRITICAL: Classes and interfaces are represented as Lazy types.
        // We must resolve them and then perform the index access lookup.
        let def_id = crate::def::DefId(def_id);
        if let Some(resolved) = self
            .evaluator
            .resolver()
            .resolve_lazy(def_id, self.evaluator.interner())
        {
            // CRITICAL: Use evaluate_index_access directly (not recurse) to perform property lookup
            // This resolves the class C and then finds the "foo" property within it
            return Some(
                self.evaluator
                    .evaluate_index_access(resolved, self.index_type),
            );
        }
        None
    }

    fn visit_array(&mut self, element_type: TypeId) -> Self::Output {
        Some(
            self.evaluator
                .evaluate_array_index(element_type, self.index_type),
        )
    }

    fn visit_tuple(&mut self, list_id: u32) -> Self::Output {
        let elements = self.evaluator.interner().tuple_list(TupleListId(list_id));
        Some(
            self.evaluator
                .evaluate_tuple_index(&elements, self.index_type),
        )
    }

    fn visit_ref(&mut self, symbol_ref: u32) -> Self::Output {
        let symbol_ref = SymbolRef(symbol_ref);
        let resolved = if let Some(def_id) = self.evaluator.resolver().symbol_to_def_id(symbol_ref)
        {
            self.evaluator
                .resolver()
                .resolve_lazy(def_id, self.evaluator.interner())?
        } else {
            self.evaluator
                .resolver()
                .resolve_symbol_ref(symbol_ref, self.evaluator.interner())?
        };
        if resolved == self.object_type {
            Some(
                self.evaluator
                    .interner()
                    .index_access(self.object_type, self.index_type),
            )
        } else {
            Some(
                self.evaluator
                    .recurse_index_access(resolved, self.index_type),
            )
        }
    }

    fn visit_type_parameter(&mut self, param_info: &TypeParamInfo) -> Self::Output {
        self.evaluate_type_param(param_info)
    }

    fn visit_infer(&mut self, param_info: &TypeParamInfo) -> Self::Output {
        self.evaluate_type_param(param_info)
    }

    fn visit_readonly_type(&mut self, inner_type: TypeId) -> Self::Output {
        Some(
            self.evaluator
                .recurse_index_access(inner_type, self.index_type),
        )
    }

    fn visit_mapped(&mut self, mapped_id: u32) -> Self::Output {
        let mapped = self
            .evaluator
            .interner()
            .mapped_type(MappedTypeId(mapped_id));

        // Optimization: Mapped[K] -> Template[P/K] where K matches constraint
        // This handles cases like `Ev<K>["callback"]` where Ev<K> is a mapped type
        // over K, without needing to expand the mapped type (which fails for TypeParameter K).

        // Only apply if no name remapping (as clause)
        if mapped.name_type.is_none() && mapped.constraint == self.index_type {
            let mut subst = TypeSubstitution::new();
            subst.insert(mapped.type_param.name, self.index_type);

            let mut value_type = self.evaluator.evaluate(instantiate_type(
                self.evaluator.interner(),
                mapped.template,
                &subst,
            ));

            // Handle optional modifier
            if matches!(mapped.optional_modifier, Some(MappedModifier::Add)) {
                value_type = self
                    .evaluator
                    .interner()
                    .union2(value_type, TypeId::UNDEFINED);
            }

            return Some(value_type);
        }

        None
    }

    fn visit_template_literal(&mut self, _template_id: u32) -> Self::Output {
        self.evaluate_apparent_primitive(IntrinsicKind::String)
    }

    fn default_output() -> Self::Output {
        None
    }
}

// =============================================================================
// Visitor Pattern Implementations for Index Type Evaluation
// =============================================================================

/// Visitor to handle array index access: `Array[K]`
///
/// Evaluates what type is returned when indexing an array with various key types.
/// Uses Option<TypeId> to signal "use default fallback" via None.
struct ArrayKeyVisitor<'a> {
    db: &'a dyn TypeDatabase,
    element_type: TypeId,
    array_member_types_cache: Option<Vec<TypeId>>,
}

impl<'a> ArrayKeyVisitor<'a> {
    fn new(db: &'a dyn TypeDatabase, element_type: TypeId) -> Self {
        Self {
            db,
            element_type,
            array_member_types_cache: None,
        }
    }

    /// Driver method that handles the fallback logic
    fn evaluate(&mut self, index_type: TypeId) -> TypeId {
        let result = self.visit_type(self.db, index_type);
        result.unwrap_or(self.element_type)
    }

    fn get_array_member_types(&mut self) -> Vec<TypeId> {
        self.array_member_types_cache
            .get_or_insert_with(|| {
                vec![
                    TypeId::NUMBER,
                    make_apparent_method_type(self.db, TypeId::ANY),
                    make_apparent_method_type(self.db, TypeId::BOOLEAN),
                    make_apparent_method_type(self.db, TypeId::NUMBER),
                    make_apparent_method_type(self.db, TypeId::VOID),
                    make_apparent_method_type(self.db, TypeId::STRING),
                ]
            })
            .clone()
    }
}

impl<'a> TypeVisitor for ArrayKeyVisitor<'a> {
    type Output = Option<TypeId>;

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        let members = self.db.type_list(TypeListId(list_id));
        let mut results = Vec::new();
        for &member in members.iter() {
            let result = self.evaluate(member);
            if result != TypeId::UNDEFINED {
                results.push(result);
            }
        }
        if results.is_empty() {
            Some(TypeId::UNDEFINED)
        } else {
            Some(self.db.union(results))
        }
    }

    fn visit_intrinsic(&mut self, kind: IntrinsicKind) -> Self::Output {
        match kind {
            IntrinsicKind::Number => Some(self.element_type),
            IntrinsicKind::String => Some(self.db.union(self.get_array_member_types())),
            _ => Some(TypeId::UNDEFINED),
        }
    }

    fn visit_literal(&mut self, value: &LiteralValue) -> Self::Output {
        match value {
            LiteralValue::Number(_) => Some(self.element_type),
            LiteralValue::String(atom) => {
                let name = self.db.resolve_atom_ref(*atom);
                if utils::is_numeric_property_name(self.db, *atom) {
                    return Some(self.element_type);
                }
                // Check for known array members
                if let Some(member) = get_array_member_kind(name.as_ref()) {
                    return match member {
                        ApparentMemberKind::Value(type_id) => Some(type_id),
                        ApparentMemberKind::Method(return_type) => {
                            Some(make_apparent_method_type(self.db, return_type))
                        }
                    };
                }
                Some(TypeId::UNDEFINED)
            }
            // Explicitly handle other literals to avoid incorrect fallback
            LiteralValue::Boolean(_) | LiteralValue::BigInt(_) => Some(TypeId::UNDEFINED),
        }
    }

    /// Signal "use the default fallback" for unhandled type variants
    fn default_output() -> Self::Output {
        None
    }
}

/// Visitor to handle tuple index access: `Tuple[K]`
///
/// Evaluates what type is returned when indexing a tuple with various key types.
/// Uses Option<TypeId> to signal "use default fallback" via None.
struct TupleKeyVisitor<'a> {
    db: &'a dyn TypeDatabase,
    elements: &'a [TupleElement],
    array_member_types_cache: Option<Vec<TypeId>>,
}

impl<'a> TupleKeyVisitor<'a> {
    fn new(db: &'a dyn TypeDatabase, elements: &'a [TupleElement]) -> Self {
        Self {
            db,
            elements,
            array_member_types_cache: None,
        }
    }

    /// Driver method that handles the fallback logic
    fn evaluate(&mut self, index_type: TypeId) -> TypeId {
        let result = self.visit_type(self.db, index_type);
        result.unwrap_or(TypeId::UNDEFINED)
    }

    /// Get the type of a tuple element, handling optional and rest elements
    fn tuple_element_type(&self, element: &TupleElement) -> TypeId {
        let mut type_id = if element.rest {
            self.rest_element_type(element.type_id)
        } else {
            element.type_id
        };

        if element.optional {
            type_id = self.db.union2(type_id, TypeId::UNDEFINED);
        }

        type_id
    }

    /// Get the element type of a rest element (handles nested rest and array types)
    fn rest_element_type(&self, type_id: TypeId) -> TypeId {
        if let Some(elem) = array_element_type(self.db, type_id) {
            return elem;
        }
        if let Some(elements) = tuple_list_id(self.db, type_id) {
            let elements = self.db.tuple_list(elements);
            let types: Vec<TypeId> = elements
                .iter()
                .map(|e| self.tuple_element_type(e))
                .collect();
            if types.is_empty() {
                TypeId::NEVER
            } else {
                self.db.union(types)
            }
        } else {
            type_id
        }
    }

    /// Get the type at a specific literal index, handling rest elements
    fn tuple_index_literal(&self, idx: usize) -> Option<TypeId> {
        for (logical_idx, element) in self.elements.iter().enumerate() {
            if element.rest {
                if let Some(rest_elements) = tuple_list_id(self.db, element.type_id) {
                    let rest_elements = self.db.tuple_list(rest_elements);
                    let inner_idx = idx.saturating_sub(logical_idx);
                    // Recursively search in rest elements
                    let inner_visitor = TupleKeyVisitor::new(self.db, &rest_elements);
                    return inner_visitor.tuple_index_literal(inner_idx);
                }
                return Some(self.tuple_element_type(element));
            }

            if logical_idx == idx {
                return Some(self.tuple_element_type(element));
            }
        }

        None
    }

    /// Get all tuple element types as a union
    fn get_all_element_types(&self) -> Vec<TypeId> {
        self.elements
            .iter()
            .map(|e| self.tuple_element_type(e))
            .collect()
    }

    /// Get array member types (cached)
    fn get_array_member_types(&mut self) -> Vec<TypeId> {
        self.array_member_types_cache
            .get_or_insert_with(|| {
                vec![
                    TypeId::NUMBER,
                    make_apparent_method_type(self.db, TypeId::ANY),
                    make_apparent_method_type(self.db, TypeId::BOOLEAN),
                    make_apparent_method_type(self.db, TypeId::NUMBER),
                    make_apparent_method_type(self.db, TypeId::VOID),
                    make_apparent_method_type(self.db, TypeId::STRING),
                ]
            })
            .clone()
    }

    /// Check for known array members (length, methods)
    fn get_array_member_kind(&self, name: &str) -> Option<ApparentMemberKind> {
        if name == "length" {
            return Some(ApparentMemberKind::Value(TypeId::NUMBER));
        }
        if is_member(name, ARRAY_METHODS_RETURN_ANY) {
            return Some(ApparentMemberKind::Method(TypeId::ANY));
        }
        if is_member(name, ARRAY_METHODS_RETURN_BOOLEAN) {
            return Some(ApparentMemberKind::Method(TypeId::BOOLEAN));
        }
        if is_member(name, ARRAY_METHODS_RETURN_NUMBER) {
            return Some(ApparentMemberKind::Method(TypeId::NUMBER));
        }
        if is_member(name, ARRAY_METHODS_RETURN_VOID) {
            return Some(ApparentMemberKind::Method(TypeId::VOID));
        }
        if is_member(name, ARRAY_METHODS_RETURN_STRING) {
            return Some(ApparentMemberKind::Method(TypeId::STRING));
        }
        None
    }
}

impl<'a> TypeVisitor for TupleKeyVisitor<'a> {
    type Output = Option<TypeId>;

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        let members = self.db.type_list(TypeListId(list_id));
        let mut results = Vec::new();
        for &member in members.iter() {
            let result = self.evaluate(member);
            if result != TypeId::UNDEFINED {
                results.push(result);
            }
        }
        if results.is_empty() {
            Some(TypeId::UNDEFINED)
        } else {
            Some(self.db.union(results))
        }
    }

    fn visit_intrinsic(&mut self, kind: IntrinsicKind) -> Self::Output {
        match kind {
            IntrinsicKind::String => {
                // Return union of all element types + array member types
                let mut types = self.get_all_element_types();
                types.extend(self.get_array_member_types());
                if types.is_empty() {
                    Some(TypeId::NEVER)
                } else {
                    Some(self.db.union(types))
                }
            }
            IntrinsicKind::Number => {
                // Return union of all element types
                let all_types = self.get_all_element_types();
                if all_types.is_empty() {
                    Some(TypeId::NEVER)
                } else {
                    Some(self.db.union(all_types))
                }
            }
            _ => Some(TypeId::UNDEFINED),
        }
    }

    fn visit_literal(&mut self, value: &LiteralValue) -> Self::Output {
        match value {
            LiteralValue::Number(n) => {
                let value = n.0;
                if !value.is_finite() || value.fract() != 0.0 || value < 0.0 {
                    return Some(TypeId::UNDEFINED);
                }
                let idx = value as usize;
                self.tuple_index_literal(idx).or(Some(TypeId::UNDEFINED))
            }
            LiteralValue::String(atom) => {
                // Check if it's a numeric property name (e.g., "0", "1", "42")
                if utils::is_numeric_property_name(self.db, *atom) {
                    let name = self.db.resolve_atom_ref(*atom);
                    if let Ok(idx) = name.as_ref().parse::<i64>()
                        && let Ok(idx) = usize::try_from(idx)
                    {
                        return self.tuple_index_literal(idx).or(Some(TypeId::UNDEFINED));
                    }
                    return Some(TypeId::UNDEFINED);
                }

                // Check for known array members
                let name = self.db.resolve_atom_ref(*atom);
                if let Some(member) = self.get_array_member_kind(name.as_ref()) {
                    return match member {
                        ApparentMemberKind::Value(type_id) => Some(type_id),
                        ApparentMemberKind::Method(return_type) => {
                            Some(make_apparent_method_type(self.db, return_type))
                        }
                    };
                }

                Some(TypeId::UNDEFINED)
            }
            // Explicitly handle other literals to avoid incorrect fallback
            LiteralValue::Boolean(_) | LiteralValue::BigInt(_) => Some(TypeId::UNDEFINED),
        }
    }

    /// Signal "use the default fallback" for unhandled type variants
    fn default_output() -> Self::Output {
        None
    }
}

impl<'a, R: TypeResolver> TypeEvaluator<'a, R> {
    /// Helper to recursively evaluate an index access while respecting depth limits.
    /// Creates an `IndexAccess` type and evaluates it through the main `evaluate()` method.
    pub(crate) fn recurse_index_access(
        &mut self,
        object_type: TypeId,
        index_type: TypeId,
    ) -> TypeId {
        let index_access = self.interner().index_access(object_type, index_type);
        self.evaluate(index_access)
    }

    /// Evaluate an index access type: T[K]
    ///
    /// This resolves property access on object types.
    pub fn evaluate_index_access(&mut self, object_type: TypeId, index_type: TypeId) -> TypeId {
        let evaluated_object = self.evaluate(object_type);
        let evaluated_index = self.evaluate(index_type);
        if evaluated_object != object_type || evaluated_index != index_type {
            // Use recurse_index_access to respect depth limits
            return self.recurse_index_access(evaluated_object, evaluated_index);
        }
        // Match tsc: index access involving `any` produces `any`.
        // (e.g. `any[string]` is `any`, not an error)
        if evaluated_object == TypeId::ANY || evaluated_index == TypeId::ANY {
            return TypeId::ANY;
        }

        // Rule #38: Distribute over index union at the top level (Cartesian product expansion)
        // T[A | B] -> T[A] | T[B]
        // This must happen before checking the object type to ensure full cross-product expansion
        // when both object and index are unions: (X | Y)[A | B] -> X[A] | X[B] | Y[A] | Y[B]
        if let Some(members_id) = union_list_id(self.interner(), index_type) {
            let members = self.interner().type_list(members_id);
            // Limit to prevent OOM with large unions
            const MAX_UNION_INDEX_SIZE: usize = 100;
            if members.len() > MAX_UNION_INDEX_SIZE {
                self.mark_depth_exceeded();
                return TypeId::ERROR;
            }
            let mut results = Vec::new();
            for &member in members.iter() {
                if self.is_depth_exceeded() {
                    return TypeId::ERROR;
                }
                let result = self.recurse_index_access(object_type, member);
                if result == TypeId::ERROR && self.is_depth_exceeded() {
                    return TypeId::ERROR;
                }
                if result != TypeId::UNDEFINED || self.no_unchecked_indexed_access() {
                    results.push(result);
                }
            }
            if results.is_empty() {
                return TypeId::UNDEFINED;
            }
            return self.interner().union(results);
        }

        let interner = self.interner();
        let mut visitor = IndexAccessVisitor {
            evaluator: self,
            object_type,
            index_type,
        };
        if let Some(result) = visitor.visit_type(interner, object_type) {
            return result;
        }

        // For other types, keep as IndexAccess (deferred)
        self.interner().index_access(object_type, index_type)
    }

    /// Evaluate property access on an object type
    pub(crate) fn evaluate_object_index(
        &self,
        props: &[PropertyInfo],
        index_type: TypeId,
    ) -> TypeId {
        // If index is a literal string, look up the property directly
        if let Some(name) = literal_string(self.interner(), index_type) {
            for prop in props {
                if prop.name == name {
                    return self.optional_property_type(prop);
                }
            }
            // Property not found
            return TypeId::UNDEFINED;
        }

        // If index is a union of literals, return union of property types
        if let Some(members) = union_list_id(self.interner(), index_type) {
            let members = self.interner().type_list(members);
            let mut results = Vec::new();
            for &member in members.iter() {
                let result = self.evaluate_object_index(props, member);
                if result != TypeId::UNDEFINED || self.no_unchecked_indexed_access() {
                    results.push(result);
                }
            }
            if results.is_empty() {
                return TypeId::UNDEFINED;
            }
            return self.interner().union(results);
        }

        // If index is string, return union of all property types (index signature behavior)
        if index_type == TypeId::STRING {
            let union = self.union_property_types(props);
            return self.add_undefined_if_unchecked(union);
        }

        TypeId::UNDEFINED
    }

    /// Evaluate property access on an object type with index signatures.
    pub(crate) fn evaluate_object_with_index(
        &self,
        shape: &ObjectShape,
        index_type: TypeId,
    ) -> TypeId {
        // If index is a union, evaluate each member
        if let Some(members) = union_list_id(self.interner(), index_type) {
            let members = self.interner().type_list(members);
            let mut results = Vec::new();
            for &member in members.iter() {
                let result = self.evaluate_object_with_index(shape, member);
                if result != TypeId::UNDEFINED || self.no_unchecked_indexed_access() {
                    results.push(result);
                }
            }
            if results.is_empty() {
                return TypeId::UNDEFINED;
            }
            return self.interner().union(results);
        }

        // If index is a literal string, look up the property first, then fallback to string index.
        if let Some(name) = literal_string(self.interner(), index_type) {
            for prop in &shape.properties {
                if prop.name == name {
                    return self.optional_property_type(prop);
                }
            }
            if utils::is_numeric_property_name(self.interner(), name)
                && let Some(number_index) = shape.number_index.as_ref()
            {
                return self.add_undefined_if_unchecked(number_index.value_type);
            }
            if let Some(string_index) = shape.string_index.as_ref() {
                return self.add_undefined_if_unchecked(string_index.value_type);
            }
            return TypeId::UNDEFINED;
        }

        // If index is a literal number, prefer number index, then string index.
        if literal_number(self.interner(), index_type).is_some() {
            if let Some(number_index) = shape.number_index.as_ref() {
                return self.add_undefined_if_unchecked(number_index.value_type);
            }
            if let Some(string_index) = shape.string_index.as_ref() {
                return self.add_undefined_if_unchecked(string_index.value_type);
            }
            return TypeId::UNDEFINED;
        }

        if index_type == TypeId::STRING {
            let result = if let Some(string_index) = shape.string_index.as_ref() {
                string_index.value_type
            } else {
                self.union_property_types(&shape.properties)
            };
            return self.add_undefined_if_unchecked(result);
        }

        if index_type == TypeId::NUMBER {
            let result = if let Some(number_index) = shape.number_index.as_ref() {
                number_index.value_type
            } else if let Some(string_index) = shape.string_index.as_ref() {
                string_index.value_type
            } else {
                self.union_property_types(&shape.properties)
            };
            return self.add_undefined_if_unchecked(result);
        }

        TypeId::UNDEFINED
    }

    pub(crate) fn union_property_types(&self, props: &[PropertyInfo]) -> TypeId {
        let all_types: Vec<TypeId> = props
            .iter()
            .map(|prop| self.optional_property_type(prop))
            .collect();
        if all_types.is_empty() {
            TypeId::UNDEFINED
        } else {
            self.interner().union(all_types)
        }
    }

    pub(crate) fn optional_property_type(&self, prop: &PropertyInfo) -> TypeId {
        if prop.optional {
            self.interner().union2(prop.type_id, TypeId::UNDEFINED)
        } else {
            prop.type_id
        }
    }

    pub(crate) fn add_undefined_if_unchecked(&self, type_id: TypeId) -> TypeId {
        if !self.no_unchecked_indexed_access() || type_id == TypeId::UNDEFINED {
            return type_id;
        }
        self.interner().union2(type_id, TypeId::UNDEFINED)
    }

    pub(crate) fn rest_element_type(&self, type_id: TypeId) -> TypeId {
        if let Some(elem) = array_element_type(self.interner(), type_id) {
            return elem;
        }
        if let Some(elements) = tuple_list_id(self.interner(), type_id) {
            let elements = self.interner().tuple_list(elements);
            let types: Vec<TypeId> = elements
                .iter()
                .map(|e| self.tuple_element_type(e))
                .collect();
            if types.is_empty() {
                TypeId::NEVER
            } else {
                self.interner().union(types)
            }
        } else {
            type_id
        }
    }

    pub(crate) fn tuple_element_type(&self, element: &TupleElement) -> TypeId {
        let mut type_id = if element.rest {
            self.rest_element_type(element.type_id)
        } else {
            element.type_id
        };

        if element.optional {
            type_id = self.interner().union2(type_id, TypeId::UNDEFINED);
        }

        type_id
    }

    /// Evaluate index access on a tuple type
    pub(crate) fn evaluate_tuple_index(
        &self,
        elements: &[TupleElement],
        index_type: TypeId,
    ) -> TypeId {
        // Use TupleKeyVisitor to handle the index type
        // The visitor handles Union distribution internally via visit_union
        let mut visitor = TupleKeyVisitor::new(self.interner(), elements);
        let result = visitor.evaluate(index_type);

        // Add undefined if unchecked indexed access is allowed
        self.add_undefined_if_unchecked(result)
    }

    pub(crate) fn evaluate_array_index(&self, elem: TypeId, index_type: TypeId) -> TypeId {
        // Use ArrayKeyVisitor to handle the index type
        // The visitor handles Union distribution internally via visit_union
        let mut visitor = ArrayKeyVisitor::new(self.interner(), elem);
        let result = visitor.evaluate(index_type);

        // Add undefined if unchecked indexed access is allowed
        self.add_undefined_if_unchecked(result)
    }
}