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
//! Mapped type evaluation.
//!
//! Handles TypeScript's mapped types: `{ [K in keyof T]: T[K] }`
//! Including homomorphic mapped types that preserve modifiers.

use crate::instantiate::{TypeSubstitution, instantiate_type};
use crate::objects::{PropertyCollectionResult, collect_properties};
use crate::subtype::TypeResolver;
use crate::types::Visibility;
use crate::types::{
    IndexSignature, IntrinsicKind, LiteralValue, MappedModifier, MappedType, ObjectFlags,
    ObjectShape, PropertyInfo, TupleListId, TypeData, TypeId,
};
use rustc_hash::FxHashMap;
use tsz_common::interner::Atom;

use super::super::evaluate::TypeEvaluator;

pub(crate) struct MappedKeys {
    pub string_literals: Vec<Atom>,
    pub has_string: bool,
    pub has_number: bool,
}

impl<'a, R: TypeResolver> TypeEvaluator<'a, R> {
    /// Helper for key remapping in mapped types.
    /// Returns Ok(Some(remapped)) if remapping succeeded,
    /// Ok(None) if the key should be filtered (remapped to never),
    /// Err(()) if we can't process and should return the original mapped type.
    #[tracing::instrument(level = "trace", skip(self), fields(
        param_name = ?mapped.type_param.name,
        key_type = key_type.0,
        has_name_type = mapped.name_type.is_some(),
    ))]
    fn remap_key_type_for_mapped(
        &mut self,
        mapped: &MappedType,
        key_type: TypeId,
    ) -> Result<Option<TypeId>, ()> {
        let Some(name_type) = mapped.name_type else {
            return Ok(Some(key_type));
        };

        tracing::trace!(
            key_type_lookup = ?self.interner().lookup(key_type),
            name_type_lookup = ?self.interner().lookup(name_type),
            "remap_key_type_for_mapped: before substitution"
        );

        let mut subst = TypeSubstitution::new();
        subst.insert(mapped.type_param.name, key_type);
        let remapped = instantiate_type(self.interner(), name_type, &subst);

        tracing::trace!(
            remapped_before_eval = remapped.0,
            remapped_lookup = ?self.interner().lookup(remapped),
            "remap_key_type_for_mapped: after substitution"
        );

        let remapped = self.evaluate(remapped);

        tracing::trace!(
            remapped_after_eval = remapped.0,
            remapped_eval_lookup = ?self.interner().lookup(remapped),
            is_never = remapped == TypeId::NEVER,
            "remap_key_type_for_mapped: after evaluation"
        );

        if remapped == TypeId::NEVER {
            return Ok(None);
        }
        Ok(Some(remapped))
    }

    /// Helper to compute modifiers for a mapped type property.
    fn get_mapped_modifiers(
        &mut self,
        mapped: &MappedType,
        is_homomorphic: bool,
        source_object: Option<TypeId>,
        key_name: Atom,
    ) -> (bool, bool) {
        // NOTE: This helper is now only used for index signatures.
        // Direct property modifiers are handled via the memoized map in evaluate_mapped.
        let source_mods = if let Some(source_obj) = source_object {
            match collect_properties(source_obj, self.interner(), self.resolver()) {
                PropertyCollectionResult::Properties { properties, .. } => properties
                    .iter()
                    .find(|p| p.name == key_name)
                    .map_or((false, false), |p| (p.optional, p.readonly)),
                _ => (false, false),
            }
        } else {
            (false, false)
        };

        let optional = match mapped.optional_modifier {
            Some(MappedModifier::Add) => true,
            Some(MappedModifier::Remove) => false,
            None => {
                // For homomorphic types with no explicit modifier, preserve original
                if is_homomorphic { source_mods.0 } else { false }
            }
        };

        let readonly = match mapped.readonly_modifier {
            Some(MappedModifier::Add) => true,
            Some(MappedModifier::Remove) => false,
            None => {
                // For homomorphic types with no explicit modifier, preserve original
                if is_homomorphic { source_mods.1 } else { false }
            }
        };

        (optional, readonly)
    }

    /// Evaluate a mapped type: { [K in Keys]: Template }
    ///
    /// Algorithm:
    /// 1. Extract the constraint (Keys) - this defines what keys to iterate over
    /// 2. For each key K in the constraint:
    ///    - Substitute K into the template type
    ///    - Apply readonly/optional modifiers
    /// 3. Construct a new object type with the resulting properties
    pub fn evaluate_mapped(&mut self, mapped: &MappedType) -> TypeId {
        // TODO: Array/Tuple Preservation for Homomorphic Mapped Types
        // If source_object is an Array or Tuple, we should construct a Mapped Array/Tuple
        // instead of degrading to a plain Object. This is required to preserve
        // Array.prototype methods (push, pop, map) and tuple-specific behavior.
        // Example: type Boxed<T> = { [K in keyof T]: Box<T[K]> }
        //   Boxed<[number, string]> should be [Box<number>, Box<string>] (Tuple)
        //   Boxed<number[]> should be Box<number>[] (Array)
        // Current implementation degrades both to plain Objects.

        // Check if depth was already exceeded
        if self.is_depth_exceeded() {
            return TypeId::ERROR;
        }

        // Get the constraint - this tells us what keys to iterate over
        let constraint = mapped.constraint;

        // SPECIAL CASE: Don't expand mapped types over type parameters.
        // When the constraint is `keyof T` where T is a type parameter, we should
        // keep the mapped type deferred. Even though we might be able to evaluate
        // `keyof T` to concrete keys (via T's constraint), the template instantiation
        // would fail because T[key] can't be resolved for a type parameter.
        //
        // This is critical for patterns like:
        //   function f<T extends any[]>(a: Boxified<T>) { a.pop(); }
        // where Boxified<T> = { [P in keyof T]: Box<T[P]> }
        //
        // If we expand this, T["pop"] becomes ERROR. We need to keep it deferred
        // and handle property access on the deferred mapped type specially.
        if self.is_mapped_type_over_type_parameter(mapped) {
            tracing::trace!(
                constraint = ?self.interner().lookup(constraint),
                "evaluate_mapped: DEFERRED - mapped type over type parameter"
            );
            return self.interner().mapped(mapped.clone());
        }

        // Evaluate the constraint to get concrete keys
        let keys = self.evaluate_keyof_or_constraint(constraint);

        // If we can't determine concrete keys, keep it as a mapped type (deferred)
        let key_set = match self.extract_mapped_keys(keys) {
            Some(keys) => keys,
            None => {
                tracing::trace!(
                    keys_lookup = ?self.interner().lookup(keys),
                    "evaluate_mapped: DEFERRED - could not extract concrete keys"
                );
                return self.interner().mapped(mapped.clone());
            }
        };

        // Limit number of keys to prevent OOM with large mapped types.
        // WASM environments have limited memory, but 100 is too restrictive for
        // real-world code (large SDKs, generated API types often have 150-250 keys).
        // 250 covers ~99% of real-world use cases while remaining safe for WASM.
        #[cfg(target_arch = "wasm32")]
        const MAX_MAPPED_KEYS: usize = 250;
        #[cfg(not(target_arch = "wasm32"))]
        const MAX_MAPPED_KEYS: usize = 500;
        if key_set.string_literals.len() > MAX_MAPPED_KEYS {
            self.mark_depth_exceeded();
            return TypeId::ERROR;
        }

        // Check if this is a homomorphic mapped type (template is T[K] indexed access)
        // In this case, we should preserve the original property modifiers
        let is_homomorphic = self.is_homomorphic_mapped_type(mapped);

        // Extract source object type from the constraint if it is `keyof T`
        // This is needed for homomorphic mapped types and for preserving Array/Tuple
        // structure in mapped types over arrays/tuples (even non-homomorphic ones).
        let source_object = self.extract_source_from_keyof(mapped.constraint);

        // PERF: Memoize source properties into a hash map for O(1) lookup during the key loop.
        // This avoids repeated O(N) collect_properties calls inside the loop.
        let mut source_prop_map = FxHashMap::default();
        if let Some(source) = source_object {
            match collect_properties(source, self.interner(), self.resolver()) {
                PropertyCollectionResult::Properties { properties, .. } => {
                    for prop in properties {
                        source_prop_map
                            .insert(prop.name, (prop.optional, prop.readonly, prop.type_id));
                    }
                }
                PropertyCollectionResult::Any | PropertyCollectionResult::NonObject => {
                    // Any type properties are treated as (false, false, ANY)
                }
            }
        }

        // HOMOMORPHIC ARRAY/TUPLE PRESERVATION
        // If source_object is an Array or Tuple, preserve the structure instead of
        // degrading to a plain Object. This preserves Array methods (push, pop, map)
        // and tuple-specific behavior.
        //
        // Example: type Partial<T> = { [P in keyof T]?: T[P] }
        //   Partial<[number, string]> should be [number?, string?] (Tuple)
        //   Partial<number[]> should be (number | undefined)[] (Array)
        //
        // CRITICAL: Only preserve if there's NO name remapping (as clause).
        // Name remapping breaks homomorphism and degrades to plain object.
        if let Some(source) = source_object {
            // Name remapping breaks homomorphism - don't preserve structure
            if mapped.name_type.is_none() {
                // Resolve the source to check if it's an Array or Tuple
                // Use evaluate() to resolve Lazy types (interfaces/classes)
                let resolved = self.evaluate(source);

                match self.interner().lookup(resolved) {
                    // Array type: map the element type
                    Some(TypeData::Array(element_type)) => {
                        return self.evaluate_mapped_array(mapped, element_type);
                    }

                    // Tuple type: map each element
                    Some(TypeData::Tuple(tuple_id)) => {
                        return self.evaluate_mapped_tuple(mapped, tuple_id);
                    }

                    // ReadonlyArray: map the element type and preserve readonly
                    Some(TypeData::ObjectWithIndex(shape_id)) => {
                        // Check if this is a ReadonlyArray (has readonly numeric index)
                        // Note: We DON'T check properties.is_empty() because ReadonlyArray<T>
                        // has methods like length, map, filter, etc. We only care about the index signature.
                        let shape = self.interner().object_shape(shape_id);
                        let has_readonly_index = shape
                            .number_index
                            .as_ref()
                            .is_some_and(|idx| idx.readonly && idx.key_type == TypeId::NUMBER);

                        if has_readonly_index {
                            // This is ReadonlyArray<T> - map element type
                            // Extract the element type from the number index signature
                            if let Some(index) = &shape.number_index {
                                return self.evaluate_mapped_array_with_readonly(
                                    mapped,
                                    index.value_type,
                                    true,
                                );
                            }
                        }
                    }

                    _ => {}
                }
            }
        }

        // Build the resulting object properties
        let mut properties = Vec::new();

        for key_name in key_set.string_literals {
            // Check if depth was exceeded during previous iterations
            if self.is_depth_exceeded() {
                return TypeId::ERROR;
            }

            // Create substitution: type_param.name -> literal key type
            // Use canonical constructor for O(1) equality
            let key_literal = self.interner().literal_string_atom(key_name);
            let remapped = match self.remap_key_type_for_mapped(mapped, key_literal) {
                Ok(Some(remapped)) => remapped,
                Ok(None) => continue,
                Err(()) => return self.interner().mapped(mapped.clone()),
            };
            // Extract property name(s) from remapped key.
            // Handle unions: `as \`${K}1\` | \`${K}2\`` produces multiple properties per key.
            let remapped_names: Vec<Atom> =
                if let Some(name) = crate::visitor::literal_string(self.interner(), remapped) {
                    vec![name]
                } else if let Some(TypeData::Union(list_id)) = self.interner().lookup(remapped) {
                    let members = self.interner().type_list(list_id);
                    let names: Vec<Atom> = members
                        .iter()
                        .filter_map(|&m| crate::visitor::literal_string(self.interner(), m))
                        .collect();
                    if names.is_empty() {
                        return self.interner().mapped(mapped.clone());
                    }
                    names
                } else {
                    return self.interner().mapped(mapped.clone());
                };

            let mut subst = TypeSubstitution::new();
            subst.insert(mapped.type_param.name, key_literal);

            // Substitute into the template
            let mut property_type =
                self.evaluate(instantiate_type(self.interner(), mapped.template, &subst));

            // Check if evaluation hit depth limit
            if property_type == TypeId::ERROR && self.is_depth_exceeded() {
                return TypeId::ERROR;
            }

            // Get modifiers for this specific key (preserves homomorphic behavior)
            // Use memoized source property info for O(1) lookup.
            let source_info = source_prop_map.get(&key_name);
            let (source_optional, source_readonly) =
                source_info.map_or((false, false), |(opt, ro, _)| (*opt, *ro));

            let optional = match mapped.optional_modifier {
                Some(MappedModifier::Add) => true,
                Some(MappedModifier::Remove) => false,
                None => {
                    if is_homomorphic {
                        source_optional
                    } else {
                        false
                    }
                }
            };

            let readonly = match mapped.readonly_modifier {
                Some(MappedModifier::Add) => true,
                Some(MappedModifier::Remove) => false,
                None => {
                    if is_homomorphic {
                        source_readonly
                    } else {
                        false
                    }
                }
            };

            // TypeScript homomorphic mapped type behavior: when `-?` removes optionality
            // from an optional source property, the property type should be the DECLARED
            // type (without the `| undefined` that IndexedAccess adds for optional properties).
            if !optional
                && matches!(mapped.optional_modifier, Some(MappedModifier::Remove))
                && is_homomorphic
                && source_optional
            {
                // Use the memoized declared type directly
                if let Some((_, _, declared_type)) = source_info {
                    property_type = *declared_type;
                }
            }

            for remapped_name in remapped_names {
                properties.push(PropertyInfo {
                    name: remapped_name,
                    type_id: property_type,
                    write_type: property_type,
                    optional,
                    readonly,
                    is_method: false,
                    visibility: Visibility::Public,
                    parent_id: None,
                });
            }
        }

        let string_index = if key_set.has_string {
            match self.remap_key_type_for_mapped(mapped, TypeId::STRING) {
                Ok(Some(remapped)) => {
                    if remapped != TypeId::STRING {
                        return self.interner().mapped(mapped.clone());
                    }
                    let key_type = TypeId::STRING;
                    let mut subst = TypeSubstitution::new();
                    subst.insert(mapped.type_param.name, key_type);
                    let mut value_type =
                        self.evaluate(instantiate_type(self.interner(), mapped.template, &subst));

                    // Get modifiers for string index
                    let empty_atom = self.interner().intern_string("");
                    let (idx_optional, idx_readonly) = self.get_mapped_modifiers(
                        mapped,
                        is_homomorphic,
                        source_object,
                        empty_atom,
                    );
                    if idx_optional {
                        value_type = self.interner().union2(value_type, TypeId::UNDEFINED);
                    }
                    Some(IndexSignature {
                        key_type,
                        value_type,
                        readonly: idx_readonly,
                    })
                }
                Ok(None) => None,
                Err(()) => return self.interner().mapped(mapped.clone()),
            }
        } else {
            None
        };

        let number_index = if key_set.has_number {
            match self.remap_key_type_for_mapped(mapped, TypeId::NUMBER) {
                Ok(Some(remapped)) => {
                    if remapped != TypeId::NUMBER {
                        return self.interner().mapped(mapped.clone());
                    }
                    let key_type = TypeId::NUMBER;
                    let mut subst = TypeSubstitution::new();
                    subst.insert(mapped.type_param.name, key_type);
                    let mut value_type =
                        self.evaluate(instantiate_type(self.interner(), mapped.template, &subst));

                    // Get modifiers for number index
                    let empty_atom = self.interner().intern_string("");
                    let (idx_optional, idx_readonly) = self.get_mapped_modifiers(
                        mapped,
                        is_homomorphic,
                        source_object,
                        empty_atom,
                    );
                    if idx_optional {
                        value_type = self.interner().union2(value_type, TypeId::UNDEFINED);
                    }
                    Some(IndexSignature {
                        key_type,
                        value_type,
                        readonly: idx_readonly,
                    })
                }
                Ok(None) => None,
                Err(()) => return self.interner().mapped(mapped.clone()),
            }
        } else {
            None
        };

        if string_index.is_some() || number_index.is_some() {
            self.interner().object_with_index(ObjectShape {
                flags: ObjectFlags::empty(),
                properties,
                string_index,
                number_index,
                symbol: None,
            })
        } else {
            self.interner().object(properties)
        }
    }

    /// Check if a mapped type's constraint is `keyof T` where T is a type parameter.
    ///
    /// When this is true, we should not expand the mapped type because the template
    /// instantiation would fail (T[key] can't be resolved for a type parameter).
    fn is_mapped_type_over_type_parameter(&self, mapped: &MappedType) -> bool {
        // Check if the constraint is `keyof T`
        let Some(TypeData::KeyOf(source)) = self.interner().lookup(mapped.constraint) else {
            return false;
        };

        // Check if the source is a type parameter
        matches!(
            self.interner().lookup(source),
            Some(TypeData::TypeParameter(_) | TypeData::Infer(_))
        )
    }

    /// Evaluate a keyof or constraint type for mapped type iteration.
    fn evaluate_keyof_or_constraint(&mut self, constraint: TypeId) -> TypeId {
        if let Some(TypeData::Conditional(cond_id)) = self.interner().lookup(constraint) {
            let cond = self.interner().conditional_type(cond_id);
            return self.evaluate_conditional(cond.as_ref());
        }

        // If constraint is already a union of literals, return it
        if let Some(TypeData::Union(_)) = self.interner().lookup(constraint) {
            return constraint;
        }

        // If constraint is a literal, return it
        if let Some(TypeData::Literal(LiteralValue::String(_))) = self.interner().lookup(constraint)
        {
            return constraint;
        }

        // If constraint is KeyOf, evaluate it
        if let Some(TypeData::KeyOf(operand)) = self.interner().lookup(constraint) {
            return self.evaluate_keyof(operand);
        }

        // Evaluate the constraint to resolve type aliases (Lazy), Applications, etc.
        // For example, `type Keys = "a" | "b"; { [P in Keys]: T }` has a Lazy(DefId)
        // constraint that must be evaluated to get the concrete union `"a" | "b"`.
        let evaluated = self.evaluate(constraint);
        if evaluated != constraint {
            return self.evaluate_keyof_or_constraint(evaluated);
        }

        // Otherwise return as-is
        constraint
    }

    /// Extract mapped keys from a type (for mapped type iteration).
    fn extract_mapped_keys(&self, type_id: TypeId) -> Option<MappedKeys> {
        let key = self.interner().lookup(type_id)?;

        let mut keys = MappedKeys {
            string_literals: Vec::new(),
            has_string: false,
            has_number: false,
        };

        match key {
            // NEW: Handle KeyOf types directly if evaluate_keyof deferred
            // This fixes Bug #1: Key Remapping with conditionals
            TypeData::KeyOf(operand) => {
                tracing::trace!(
                    operand = operand.0,
                    operand_lookup = ?self.interner().lookup(operand),
                    "extract_mapped_keys: handling KeyOf type"
                );
                // NORTH STAR: Use collect_properties to extract keys from KeyOf operand.
                // This handles interfaces, classes, intersections, and type parameters.
                let prop_result = collect_properties(operand, self.interner(), self.resolver());
                tracing::trace!(
                    operand = operand.0,
                    prop_result = ?std::mem::discriminant(&prop_result),
                    "extract_mapped_keys: collect_properties result"
                );
                match prop_result {
                    PropertyCollectionResult::Properties {
                        properties,
                        string_index,
                        number_index,
                    } => {
                        for prop in properties {
                            keys.string_literals.push(prop.name);
                        }
                        keys.has_string = string_index.is_some();
                        keys.has_number = number_index.is_some();
                        tracing::trace!(
                            string_literals = ?keys.string_literals,
                            has_string = keys.has_string,
                            has_number = keys.has_number,
                            "extract_mapped_keys: extracted keys from KeyOf"
                        );
                        Some(keys)
                    }
                    PropertyCollectionResult::Any => {
                        keys.has_string = true;
                        keys.has_number = true;
                        tracing::trace!("extract_mapped_keys: KeyOf is Any type");
                        Some(keys)
                    }
                    PropertyCollectionResult::NonObject => {
                        tracing::trace!("extract_mapped_keys: KeyOf operand is not an object");
                        None
                    }
                }
            }
            TypeData::Literal(LiteralValue::String(s)) => {
                keys.string_literals.push(s);
                Some(keys)
            }
            TypeData::Union(members) => {
                let members = self.interner().type_list(members);
                for &member in members.iter() {
                    if member == TypeId::STRING {
                        keys.has_string = true;
                        continue;
                    }
                    if member == TypeId::NUMBER {
                        keys.has_number = true;
                        continue;
                    }
                    if member == TypeId::SYMBOL {
                        // We don't model symbol index signatures yet; ignore symbol keys.
                        continue;
                    }
                    // Use visitor helper for data extraction (North Star Rule 3)
                    if let Some(s) = crate::visitor::literal_string(self.interner(), member) {
                        keys.string_literals.push(s);
                    } else if let Some(n) = crate::visitor::literal_number(self.interner(), member)
                    {
                        // Numeric literals become string property names (e.g., 0 → "0").
                        // This handles enum member values like `enum E { A = 0 }`.
                        let s = self.interner().intern_string(
                            &crate::subtype_rules::literals::format_number_for_template(n.0),
                        );
                        keys.string_literals.push(s);
                    } else {
                        // Non-literal in union - can't fully evaluate
                        return None;
                    }
                }
                if !keys.has_string && !keys.has_number && keys.string_literals.is_empty() {
                    // Only symbol keys (or nothing) - defer until we support symbol indices.
                    return None;
                }
                Some(keys)
            }
            TypeData::Intrinsic(IntrinsicKind::String) => {
                keys.has_string = true;
                Some(keys)
            }
            TypeData::Intrinsic(IntrinsicKind::Number) => {
                keys.has_number = true;
                Some(keys)
            }
            TypeData::Intrinsic(IntrinsicKind::Never) => {
                // Mapped over `never` yields an empty object.
                Some(keys)
            }
            TypeData::Enum(_def_id, members) => {
                // Enum used as mapped type constraint: extract keys from member union.
                // For `enum E { A, B }`, members is the union `0 | 1`, and the keys
                // are the enum values. Recursively extract from the members type.
                self.extract_mapped_keys(members)
            }
            // Can't extract literals from other types
            _ => None,
        }
    }

    /// Check if a mapped type is homomorphic (template is T[K] indexed access).
    /// Homomorphic mapped types preserve modifiers from the source type.
    ///
    /// A mapped type is homomorphic if:
    /// 1. The constraint is `keyof T` for some type T
    /// 2. The template is `T[K]` where T is the same type and K is the iteration parameter
    ///
    /// Also handles the post-instantiation case where the `keyof T` constraint was
    /// eagerly evaluated to a union of string literals during `instantiate_type`.
    /// In that case, we verify that `template = obj[P]` and `keyof obj == constraint`.
    fn is_homomorphic_mapped_type(&mut self, mapped: &MappedType) -> bool {
        // Method 1: Constraint is explicitly `keyof T` (pre-evaluation form)
        if let Some(source_from_constraint) = self.extract_source_from_keyof(mapped.constraint) {
            // Check if template is an IndexAccess type T[K]
            return match self.interner().lookup(mapped.template) {
                Some(TypeData::IndexAccess(obj, idx)) => {
                    if obj != source_from_constraint {
                        return false;
                    }
                    match self.interner().lookup(idx) {
                        Some(TypeData::TypeParameter(param)) => {
                            param.name == mapped.type_param.name
                        }
                        _ => false,
                    }
                }
                _ => false,
            };
        }

        // Method 2: Post-instantiation form where `keyof T` was eagerly evaluated
        // to a union of string literals. The template still has the original structure
        // `T[P]` with the concrete object. Verify by computing `keyof obj` and
        // comparing with the constraint.
        // Key remapping (`as` clause / name_type) breaks homomorphism.
        if mapped.name_type.is_none()
            && let Some(TypeData::IndexAccess(obj, idx)) = self.interner().lookup(mapped.template)
            && let Some(TypeData::TypeParameter(param)) = self.interner().lookup(idx)
            && param.name == mapped.type_param.name
        {
            // Don't match if obj is still a type parameter (not yet instantiated)
            if matches!(
                self.interner().lookup(obj),
                Some(TypeData::TypeParameter(_))
            ) {
                return false;
            }
            // Verify: the constraint is exactly the keys of obj
            let expected_keys = self.evaluate_keyof(obj);
            return expected_keys == mapped.constraint;
        }

        false
    }

    /// Extract the source type T from a `keyof T` constraint.
    /// Handles aliased constraints like `type Keys<T> = keyof T`.
    fn extract_source_from_keyof(&mut self, constraint: TypeId) -> Option<TypeId> {
        match self.interner().lookup(constraint) {
            Some(TypeData::KeyOf(source)) => Some(source),
            // Handle aliased constraints (Application)
            Some(TypeData::Application(_)) => {
                // Evaluate to resolve the alias
                let evaluated = self.evaluate(constraint);
                // Recursively check the evaluated type
                if evaluated != constraint {
                    self.extract_source_from_keyof(evaluated)
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    /// Evaluate a homomorphic mapped type over an Array type.
    ///
    /// For example: `type Partial<T> = { [P in keyof T]?: T[P] }`
    ///   `Partial<number[]>` should produce `(number | undefined)[]`
    ///
    /// We instantiate the template with `K = number` to get the mapped element type.
    fn evaluate_mapped_array(&mut self, mapped: &MappedType, _element_type: TypeId) -> TypeId {
        // Create substitution: type_param.name -> number
        let mut subst = TypeSubstitution::new();
        subst.insert(mapped.type_param.name, TypeId::NUMBER);

        // Substitute into the template to get the mapped element type
        let mut mapped_element =
            self.evaluate(instantiate_type(self.interner(), mapped.template, &subst));

        // CRITICAL: Handle optional modifier (Partial<T[]> case)
        // TypeScript adds undefined to the element type when ? modifier is present
        if matches!(mapped.optional_modifier, Some(MappedModifier::Add)) {
            mapped_element = self.interner().union2(mapped_element, TypeId::UNDEFINED);
        }

        // Check if readonly modifier should be applied
        let is_readonly = matches!(mapped.readonly_modifier, Some(MappedModifier::Add));

        // Create the new array type
        if is_readonly {
            // Wrap the array type in ReadonlyType to get readonly semantics
            let array_type = self.interner().array(mapped_element);
            self.interner().readonly_type(array_type)
        } else {
            self.interner().array(mapped_element)
        }
    }

    /// Evaluate a homomorphic mapped type over an Array type with explicit readonly flag.
    ///
    /// Used for `ReadonlyArray`<T> to preserve readonly semantics.
    fn evaluate_mapped_array_with_readonly(
        &mut self,
        mapped: &MappedType,
        _element_type: TypeId,
        is_readonly: bool,
    ) -> TypeId {
        // Create substitution: type_param.name -> number
        let mut subst = TypeSubstitution::new();
        subst.insert(mapped.type_param.name, TypeId::NUMBER);

        // Substitute into the template to get the mapped element type
        let mut mapped_element =
            self.evaluate(instantiate_type(self.interner(), mapped.template, &subst));

        // CRITICAL: Handle optional modifier (Partial<T[]> case)
        if matches!(mapped.optional_modifier, Some(MappedModifier::Add)) {
            mapped_element = self.interner().union2(mapped_element, TypeId::UNDEFINED);
        }

        // Apply readonly modifier if present
        let final_readonly = match mapped.readonly_modifier {
            Some(MappedModifier::Add) => true,
            Some(MappedModifier::Remove) => false,
            None => is_readonly, // Preserve original readonly status
        };

        if final_readonly {
            // Wrap the array type in ReadonlyType to get readonly semantics
            let array_type = self.interner().array(mapped_element);
            self.interner().readonly_type(array_type)
        } else {
            self.interner().array(mapped_element)
        }
    }

    /// Evaluate a homomorphic mapped type over a Tuple type.
    ///
    /// For example: `type Partial<T> = { [P in keyof T]?: T[P] }`
    ///   `Partial<[number, string]>` should produce `[number?, string?]`
    ///
    /// We instantiate the template with `K = 0, 1, 2...` for each tuple element.
    /// This preserves tuple structure including optional and rest elements.
    fn evaluate_mapped_tuple(&mut self, mapped: &MappedType, tuple_id: TupleListId) -> TypeId {
        use crate::types::TupleElement;

        let tuple_elements = self.interner().tuple_list(tuple_id);
        let mut mapped_elements = Vec::new();

        for (i, elem) in tuple_elements.iter().enumerate() {
            // CRITICAL: Handle rest elements specially
            // For rest elements (...T[]), we cannot use index substitution.
            // We must map the array type itself.
            if elem.rest {
                // Rest elements like ...number[] need to be mapped as arrays
                // Check if the rest type is an Array
                let rest_type = elem.type_id;
                let mapped_rest_type = match self.interner().lookup(rest_type) {
                    Some(TypeData::Array(inner_elem)) => {
                        // Map the inner array element
                        // Reuse the array mapping logic
                        self.evaluate_mapped_array(mapped, inner_elem)
                    }
                    Some(TypeData::Tuple(inner_tuple_id)) => {
                        // Nested tuple in rest - recurse
                        self.evaluate_mapped_tuple(mapped, inner_tuple_id)
                    }
                    _ => {
                        // Fallback: try index substitution (may not work correctly)
                        let index_type = self.interner().literal_number(i as f64);
                        let mut subst = TypeSubstitution::new();
                        subst.insert(mapped.type_param.name, index_type);
                        self.evaluate(instantiate_type(self.interner(), mapped.template, &subst))
                    }
                };

                // Handle optional modifier for rest elements
                let final_rest_type =
                    if matches!(mapped.optional_modifier, Some(MappedModifier::Add)) {
                        self.interner().union2(mapped_rest_type, TypeId::UNDEFINED)
                    } else {
                        mapped_rest_type
                    };

                mapped_elements.push(TupleElement {
                    type_id: final_rest_type,
                    name: elem.name,
                    optional: elem.optional,
                    rest: true,
                });
                continue;
            }

            // Non-rest elements: use index substitution
            // Create a literal number type for this tuple position
            let index_type = self.interner().literal_number(i as f64);

            // Create substitution: type_param.name -> literal number
            let mut subst = TypeSubstitution::new();
            subst.insert(mapped.type_param.name, index_type);

            // Substitute into the template to get the mapped element type
            let mapped_type =
                self.evaluate(instantiate_type(self.interner(), mapped.template, &subst));

            // Get the modifiers for this element
            // Note: readonly is currently unused for tuple elements, but we preserve the logic
            // in case TypeScript adds readonly tuple element support in the future
            // CRITICAL: Handle optional and readonly modifiers independently
            let optional = match mapped.optional_modifier {
                Some(MappedModifier::Add) => true,
                Some(MappedModifier::Remove) => false,
                None => elem.optional, // Preserve original optional
            };
            let _readonly = match mapped.readonly_modifier {
                Some(MappedModifier::Add) => true,
                Some(MappedModifier::Remove) | None => false,
                // Tuple elements don't have readonly in current TypeScript
            };

            mapped_elements.push(TupleElement {
                type_id: mapped_type,
                name: elem.name,
                optional,
                rest: elem.rest,
            });
        }

        self.interner().tuple(mapped_elements)
    }
}