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
//! Conditional type evaluation.
//!
//! Handles TypeScript's conditional types: `T extends U ? X : Y`
//! Including distributive conditional types over union types.
use crate::instantiate::{TypeSubstitution, instantiate_type_with_infer};
use crate::subtype::{SubtypeChecker, TypeResolver};
use crate::types::{
ConditionalType, ObjectShapeId, PropertyInfo, TupleElement, TypeData, TypeId, TypeParamInfo,
};
use rustc_hash::{FxHashMap, FxHashSet};
use tracing::trace;
use super::super::evaluate::TypeEvaluator;
impl<'a, R: TypeResolver> TypeEvaluator<'a, R> {
/// Maximum depth for tail-recursive conditional evaluation.
/// This allows patterns like `type Loop<T> = T extends [...infer R] ? Loop<R> : never`
/// to work with up to 1000 recursive calls instead of being limited to `MAX_EVALUATE_DEPTH`.
const MAX_TAIL_RECURSION_DEPTH: usize = 1000;
/// Evaluate a conditional type: T extends U ? X : Y
///
/// Algorithm:
/// 1. If `check_type` is a union and the conditional is distributive, distribute
/// 2. Otherwise, check if `check_type` <: `extends_type`
/// 3. If true -> return `true_type`
/// 4. If false (disjoint) -> return `false_type`
/// 5. If ambiguous (unresolved type param) -> return deferred conditional
///
/// ## Tail-Recursion Elimination
/// If the chosen branch (true/false) evaluates to another `ConditionalType`,
/// we immediately evaluate it in the current stack frame instead of recursing.
/// This allows tail-recursive patterns to work with up to `MAX_TAIL_RECURSION_DEPTH`
/// iterations instead of being limited by `MAX_EVALUATE_DEPTH`.
pub fn evaluate_conditional(&mut self, initial_cond: &ConditionalType) -> TypeId {
// Setup loop state for tail-recursion elimination
let mut current_cond = initial_cond.clone();
let mut tail_recursion_count = 0;
loop {
let cond = ¤t_cond;
// Pre-evaluation Application-level infer matching.
// When both check and extends are Applications (e.g., Promise<string> vs
// Promise<infer U>), match type arguments directly before expanding.
// After evaluation, Application types become structural Object/Callable types,
// which may fail structural infer matching for complex interfaces like Promise.
if let Some(result) = self.try_application_infer_match(cond) {
return result;
}
let check_type = self.evaluate(cond.check_type);
let extends_type = self.evaluate(cond.extends_type);
trace!(
check_raw = cond.check_type.0,
check_eval = check_type.0,
check_key = ?self.interner().lookup(check_type),
extends_raw = cond.extends_type.0,
extends_eval = extends_type.0,
extends_key = ?self.interner().lookup(extends_type),
"evaluate_conditional"
);
if cond.is_distributive && check_type == TypeId::NEVER {
return TypeId::NEVER;
}
if check_type == TypeId::ANY {
// For `any extends X ? T : F`, return union of both branches.
// When X contains infer patterns, perform infer pattern matching
// so the infer variables get bound to `any` and properly substituted.
// e.g., `any extends infer U ? U : never` → union(any, never) → any
if self.type_contains_infer(extends_type) {
let mut bindings = FxHashMap::default();
let mut visited = FxHashSet::default();
let mut checker =
SubtypeChecker::with_resolver(self.interner(), self.resolver());
checker.allow_bivariant_rest = true;
self.match_infer_pattern(
check_type,
extends_type,
&mut bindings,
&mut visited,
&mut checker,
);
let true_sub = self.substitute_infer(cond.true_type, &bindings);
let false_sub = self.substitute_infer(cond.false_type, &bindings);
let true_eval = self.evaluate(true_sub);
let false_eval = self.evaluate(false_sub);
return self.interner().union2(true_eval, false_eval);
}
let true_eval = self.evaluate(cond.true_type);
let false_eval = self.evaluate(cond.false_type);
return self.interner().union2(true_eval, false_eval);
}
// Step 1: Check for distributivity
// Only distribute for naked type parameters (recorded at lowering time).
if cond.is_distributive
&& let Some(TypeData::Union(members)) = self.interner().lookup(check_type)
{
let members = self.interner().type_list(members);
return self.distribute_conditional(
members.as_ref(),
check_type, // Pass original check_type for substitution
extends_type,
cond.true_type,
cond.false_type,
);
}
if let Some(TypeData::Infer(info)) = self.interner().lookup(extends_type) {
if matches!(
self.interner().lookup(check_type),
Some(TypeData::TypeParameter(_) | TypeData::Infer(_))
) {
return self.interner().conditional(cond.clone());
}
if check_type == TypeId::ANY {
let mut subst = TypeSubstitution::new();
subst.insert(info.name, check_type);
let true_eval = self.evaluate(instantiate_type_with_infer(
self.interner(),
cond.true_type,
&subst,
));
let false_eval = self.evaluate(instantiate_type_with_infer(
self.interner(),
cond.false_type,
&subst,
));
return self.interner().union2(true_eval, false_eval);
}
let mut subst = TypeSubstitution::new();
subst.insert(info.name, check_type);
let mut inferred = check_type;
if let Some(constraint) = info.constraint {
let mut checker =
SubtypeChecker::with_resolver(self.interner(), self.resolver());
checker.allow_bivariant_rest = true;
let Some(filtered) =
self.filter_inferred_by_constraint(inferred, constraint, &mut checker)
else {
let false_inst =
instantiate_type_with_infer(self.interner(), cond.false_type, &subst);
return self.evaluate(false_inst);
};
inferred = filtered;
}
subst.insert(info.name, inferred);
let true_inst =
instantiate_type_with_infer(self.interner(), cond.true_type, &subst);
return self.evaluate(true_inst);
}
let extends_unwrapped = match self.interner().lookup(extends_type) {
Some(TypeData::ReadonlyType(inner)) => inner,
_ => extends_type,
};
let check_unwrapped = match self.interner().lookup(check_type) {
Some(TypeData::ReadonlyType(inner)) => inner,
_ => check_type,
};
// Handle array extends pattern with infer
if let Some(TypeData::Array(ext_elem)) = self.interner().lookup(extends_unwrapped)
&& let Some(TypeData::Infer(info)) = self.interner().lookup(ext_elem)
{
return self.eval_conditional_array_infer(cond, check_unwrapped, info);
}
// Handle tuple extends pattern with infer
if let Some(TypeData::Tuple(extends_elements)) =
self.interner().lookup(extends_unwrapped)
{
let extends_elements = self.interner().tuple_list(extends_elements);
if extends_elements.len() == 1
&& !extends_elements[0].rest
&& let Some(TypeData::Infer(info)) =
self.interner().lookup(extends_elements[0].type_id)
{
return self.eval_conditional_tuple_infer(
cond,
check_unwrapped,
&extends_elements[0],
info,
);
}
}
// Handle object extends pattern with infer
if let Some(extends_shape_id) = match self.interner().lookup(extends_unwrapped) {
Some(TypeData::Object(shape_id) | TypeData::ObjectWithIndex(shape_id)) => {
Some(shape_id)
}
_ => None,
} && let Some(result) =
self.eval_conditional_object_infer(cond, check_unwrapped, extends_shape_id)
{
return result;
}
// Step 2: Check for naked type parameter
if let Some(TypeData::TypeParameter(param)) = self.interner().lookup(check_type) {
// Simplification: T extends never ? X : Y → Y
// A type parameter T cannot extend `never` (only `never` extends `never`),
// so the conditional always takes the false branch.
if extends_type == TypeId::NEVER {
return self.evaluate(cond.false_type);
}
// Simplification: T extends T ? X : Y → X
// A type parameter always extends itself, so the conditional always takes
// the true branch.
if check_type == extends_type {
return self.evaluate(cond.true_type);
}
// If extends_type contains infer patterns and the type parameter has a constraint,
// try to infer from the constraint. This handles cases like:
// R extends Reducer<infer S, any> ? S : never
// where R is constrained to Reducer<any, any>
if self.type_contains_infer(extends_type)
&& let Some(constraint) = param.constraint
{
let mut checker =
SubtypeChecker::with_resolver(self.interner(), self.resolver());
checker.allow_bivariant_rest = true;
let mut bindings = FxHashMap::default();
let mut visited = FxHashSet::default();
if self.match_infer_pattern(
constraint,
extends_type,
&mut bindings,
&mut visited,
&mut checker,
) {
let substituted_true = self.substitute_infer(cond.true_type, &bindings);
return self.evaluate(substituted_true);
}
}
// When the type parameter has a constraint, use it to determine
// which branch to take. This matches tsc's "restrictive instantiation"
// approach: if the constraint definitely doesn't extend the extends type,
// evaluate to the false branch. This is critical for types like
// `Awaited<T>` where T extends Record<string, unknown> — since Record
// doesn't have a `then` method, Awaited<T> evaluates to T.
if let Some(constraint) = param.constraint {
let evaluated_constraint = self.evaluate(constraint);
if !self.type_contains_infer(extends_type) {
let mut checker =
SubtypeChecker::with_resolver(self.interner(), self.resolver());
if !checker.is_subtype_of(evaluated_constraint, extends_type) {
// Constraint doesn't satisfy the condition → false branch
// For tail-recursion, check if false branch is another conditional
if tail_recursion_count < Self::MAX_TAIL_RECURSION_DEPTH
&& let Some(TypeData::Conditional(next_cond_id)) =
self.interner().lookup(cond.false_type)
{
let next_cond = self.interner().conditional_type(next_cond_id);
current_cond = (*next_cond).clone();
tail_recursion_count += 1;
continue;
}
return self.evaluate(cond.false_type);
}
// Constraint satisfies the condition → true branch.
// When T's constraint is assignable to extends_type, every
// possible value of T satisfies the condition, so the conditional
// always takes the true branch. For example:
// type Foo<T extends string> = T extends string ? string : number
// Foo<T> resolves to string because string <: string.
//
// For distributive conditionals, only resolve if the constraint
// is not a union — a union constraint means T could be different
// union members and we need to distribute individually.
let constraint_is_union = matches!(
self.interner().lookup(evaluated_constraint),
Some(TypeData::Union(_))
);
if !constraint_is_union || !cond.is_distributive {
// For tail-recursion on the true branch
if tail_recursion_count < Self::MAX_TAIL_RECURSION_DEPTH
&& let Some(TypeData::Conditional(next_cond_id)) =
self.interner().lookup(cond.true_type)
{
let next_cond = self.interner().conditional_type(next_cond_id);
current_cond = (*next_cond).clone();
tail_recursion_count += 1;
continue;
}
return self.evaluate(cond.true_type);
}
}
}
// Type parameter hasn't been substituted - defer evaluation
return self.interner().conditional(cond.clone());
}
// Step 3: Perform subtype check or infer pattern matching
let mut checker = SubtypeChecker::with_resolver(self.interner(), self.resolver());
checker.allow_bivariant_rest = true;
if self.type_contains_infer(extends_type) {
let mut bindings = FxHashMap::default();
let mut visited = FxHashSet::default();
if self.match_infer_pattern(
check_type,
extends_type,
&mut bindings,
&mut visited,
&mut checker,
) {
let substituted_true = self.substitute_infer(cond.true_type, &bindings);
return self.evaluate(substituted_true);
}
// Check if the result branch is directly a conditional for tail-recursion
// IMPORTANT: Check BEFORE calling evaluate to avoid incrementing depth
if tail_recursion_count < Self::MAX_TAIL_RECURSION_DEPTH {
if let Some(TypeData::Conditional(next_cond_id)) =
self.interner().lookup(cond.false_type)
{
let next_cond = self.interner().conditional_type(next_cond_id);
current_cond = (*next_cond).clone();
tail_recursion_count += 1;
continue;
}
// Also detect Application that expands to Conditional (common pattern):
// type TrimLeft<T> = T extends ` ${infer R}` ? TrimLeft<R> : T;
// The true branch `TrimLeft<R>` is an Application, not a Conditional.
if let Some(TypeData::Application(_)) = self.interner().lookup(cond.false_type)
{
let expanded = self.evaluate(cond.false_type);
if let Some(TypeData::Conditional(next_cond_id)) =
self.interner().lookup(expanded)
{
let next_cond = self.interner().conditional_type(next_cond_id);
current_cond = (*next_cond).clone();
tail_recursion_count += 1;
continue;
}
return expanded;
}
}
// Not a tail-recursive case - evaluate normally
return self.evaluate(cond.false_type);
}
// Subtype check path — use strict checking (no bivariant rest)
// to match tsc's `isTypeAssignableTo` which respects strictFunctionTypes.
let mut strict_checker =
SubtypeChecker::with_resolver(self.interner(), self.resolver());
let is_sub = strict_checker.is_subtype_of(check_type, extends_type);
trace!(
check = check_type.0,
extends = extends_type.0,
is_subtype = is_sub,
"conditional subtype check result"
);
let result_branch = if is_sub {
// T <: U -> true branch
cond.true_type
} else {
// Check if types are definitely disjoint
// For now, we use a simple heuristic: if not subtype, assume disjoint
// More sophisticated: check if intersection is never
cond.false_type
};
// Check if the result branch is directly a conditional for tail-recursion
// IMPORTANT: Check BEFORE calling evaluate to avoid incrementing depth
if tail_recursion_count < Self::MAX_TAIL_RECURSION_DEPTH {
if let Some(TypeData::Conditional(next_cond_id)) =
self.interner().lookup(result_branch)
{
let next_cond = self.interner().conditional_type(next_cond_id);
current_cond = (*next_cond).clone();
tail_recursion_count += 1;
continue;
}
// Also detect Application that expands to Conditional (tail-call through
// type alias like `TrimLeft<R>` which is Application, not Conditional)
if let Some(TypeData::Application(_)) = self.interner().lookup(result_branch) {
let expanded = self.evaluate(result_branch);
if let Some(TypeData::Conditional(next_cond_id)) =
self.interner().lookup(expanded)
{
let next_cond = self.interner().conditional_type(next_cond_id);
current_cond = (*next_cond).clone();
tail_recursion_count += 1;
continue;
}
return expanded;
}
}
// Not a tail-recursive case - evaluate normally
return self.evaluate(result_branch);
}
}
/// Distribute a conditional type over a union.
/// (A | B) extends U ? X : Y -> (A extends U ? X : Y) | (B extends U ? X : Y)
pub(crate) fn distribute_conditional(
&mut self,
members: &[TypeId],
original_check_type: TypeId,
extends_type: TypeId,
true_type: TypeId,
false_type: TypeId,
) -> TypeId {
// Limit distribution to prevent OOM with large unions
const MAX_DISTRIBUTION_SIZE: usize = 100;
if members.len() > MAX_DISTRIBUTION_SIZE {
self.mark_depth_exceeded();
return TypeId::ERROR;
}
let mut results: Vec<TypeId> = Vec::with_capacity(members.len());
for &member in members {
// Check if depth was exceeded during previous iterations
if self.is_depth_exceeded() {
return TypeId::ERROR;
}
// Substitute the specific member if true_type or false_type references the original check_type
// This handles cases like: NonNullable<T> = T extends null ? never : T
// When T = A | B, we need (A extends null ? never : A) | (B extends null ? never : B)
let substituted_true_type = if true_type == original_check_type {
member
} else {
true_type
};
let substituted_false_type = if false_type == original_check_type {
member
} else {
false_type
};
// Create conditional for this union member
let member_cond = ConditionalType {
check_type: member,
extends_type,
true_type: substituted_true_type,
false_type: substituted_false_type,
is_distributive: false,
};
// Recursively evaluate via evaluate() to respect depth limits
let cond_type = self.interner().conditional(member_cond);
let result = self.evaluate(cond_type);
// Check if evaluation hit depth limit
if result == TypeId::ERROR && self.is_depth_exceeded() {
return TypeId::ERROR;
}
results.push(result);
}
// Combine results into a union
self.interner().union(results)
}
/// Handle array extends pattern: T extends (infer U)[] ? ...
fn eval_conditional_array_infer(
&mut self,
cond: &ConditionalType,
check_unwrapped: TypeId,
info: TypeParamInfo,
) -> TypeId {
if matches!(
self.interner().lookup(check_unwrapped),
Some(TypeData::TypeParameter(_) | TypeData::Infer(_))
) {
return self.interner().conditional(cond.clone());
}
let inferred = match self.interner().lookup(check_unwrapped) {
Some(TypeData::Array(elem)) => Some(elem),
Some(TypeData::Tuple(elements)) => {
let elements = self.interner().tuple_list(elements);
let mut parts = Vec::new();
for element in elements.iter() {
if element.rest {
let rest_type = self.rest_element_type(element.type_id);
parts.push(rest_type);
} else {
let elem_type = if element.optional {
self.interner().union2(element.type_id, TypeId::UNDEFINED)
} else {
element.type_id
};
parts.push(elem_type);
}
}
if parts.is_empty() {
None
} else {
Some(self.interner().union(parts))
}
}
Some(TypeData::Union(members)) => {
let members = self.interner().type_list(members);
let mut parts = Vec::new();
for &member in members.iter() {
match self.interner().lookup(member) {
Some(TypeData::Array(elem)) => parts.push(elem),
Some(TypeData::ReadonlyType(inner)) => {
let Some(TypeData::Array(elem)) = self.interner().lookup(inner) else {
return self.evaluate(cond.false_type);
};
parts.push(elem);
}
_ => return self.evaluate(cond.false_type),
}
}
if parts.is_empty() {
None
} else if parts.len() == 1 {
Some(parts[0])
} else {
Some(self.interner().union(parts))
}
}
_ => None,
};
let Some(mut inferred) = inferred else {
return self.evaluate(cond.false_type);
};
let mut subst = TypeSubstitution::new();
subst.insert(info.name, inferred);
if let Some(constraint) = info.constraint {
let mut checker = SubtypeChecker::with_resolver(self.interner(), self.resolver());
checker.allow_bivariant_rest = true;
let is_union = matches!(self.interner().lookup(inferred), Some(TypeData::Union(_)));
if is_union && !cond.is_distributive {
// For unions in non-distributive conditionals, use filter that adds undefined
inferred = self.filter_inferred_by_constraint_or_undefined(
inferred,
constraint,
&mut checker,
);
} else {
// For single values or distributive conditionals, fail if constraint doesn't match
if !checker.is_subtype_of(inferred, constraint) {
return self.evaluate(cond.false_type);
}
}
subst.insert(info.name, inferred);
}
let true_inst = instantiate_type_with_infer(self.interner(), cond.true_type, &subst);
self.evaluate(true_inst)
}
/// Handle tuple extends pattern: T extends [infer U] ? ...
fn eval_conditional_tuple_infer(
&mut self,
cond: &ConditionalType,
check_unwrapped: TypeId,
extends_elem: &TupleElement,
info: TypeParamInfo,
) -> TypeId {
if matches!(
self.interner().lookup(check_unwrapped),
Some(TypeData::TypeParameter(_) | TypeData::Infer(_))
) {
return self.interner().conditional(cond.clone());
}
let inferred = match self.interner().lookup(check_unwrapped) {
Some(TypeData::Tuple(check_elements)) => {
let check_elements = self.interner().tuple_list(check_elements);
if check_elements.is_empty() {
extends_elem.optional.then_some(TypeId::UNDEFINED)
} else if check_elements.len() == 1 && !check_elements[0].rest {
let elem = &check_elements[0];
Some(if elem.optional {
self.interner().union2(elem.type_id, TypeId::UNDEFINED)
} else {
elem.type_id
})
} else {
None
}
}
Some(TypeData::Union(members)) => {
let members = self.interner().type_list(members);
let mut inferred_members = Vec::new();
for &member in members.iter() {
let member_type = match self.interner().lookup(member) {
Some(TypeData::ReadonlyType(inner)) => inner,
_ => member,
};
match self.interner().lookup(member_type) {
Some(TypeData::Tuple(check_elements)) => {
let check_elements = self.interner().tuple_list(check_elements);
if check_elements.is_empty() {
if extends_elem.optional {
inferred_members.push(TypeId::UNDEFINED);
continue;
}
return self.evaluate(cond.false_type);
}
if check_elements.len() == 1 && !check_elements[0].rest {
let elem = &check_elements[0];
let elem_type = if elem.optional {
self.interner().union2(elem.type_id, TypeId::UNDEFINED)
} else {
elem.type_id
};
inferred_members.push(elem_type);
} else {
return self.evaluate(cond.false_type);
}
}
_ => return self.evaluate(cond.false_type),
}
}
if inferred_members.is_empty() {
None
} else if inferred_members.len() == 1 {
Some(inferred_members[0])
} else {
Some(self.interner().union(inferred_members))
}
}
_ => None,
};
let Some(mut inferred) = inferred else {
return self.evaluate(cond.false_type);
};
let mut subst = TypeSubstitution::new();
subst.insert(info.name, inferred);
if let Some(constraint) = info.constraint {
let mut checker = SubtypeChecker::with_resolver(self.interner(), self.resolver());
checker.allow_bivariant_rest = true;
let Some(filtered) =
self.filter_inferred_by_constraint(inferred, constraint, &mut checker)
else {
let false_inst =
instantiate_type_with_infer(self.interner(), cond.false_type, &subst);
return self.evaluate(false_inst);
};
inferred = filtered;
subst.insert(info.name, inferred);
}
let true_inst = instantiate_type_with_infer(self.interner(), cond.true_type, &subst);
self.evaluate(true_inst)
}
/// Handle object extends pattern: T extends { prop: infer U } ? ...
fn eval_conditional_object_infer(
&mut self,
cond: &ConditionalType,
check_unwrapped: TypeId,
extends_shape_id: ObjectShapeId,
) -> Option<TypeId> {
let extends_shape = self.interner().object_shape(extends_shape_id);
let mut infer_prop = None;
let mut infer_nested = None;
for prop in &extends_shape.properties {
if let Some(TypeData::Infer(info)) = self.interner().lookup(prop.type_id) {
if infer_prop.is_some() || infer_nested.is_some() {
return None;
}
infer_prop = Some((prop.name, info, prop.optional));
continue;
}
let nested_type = match self.interner().lookup(prop.type_id) {
Some(TypeData::ReadonlyType(inner)) => inner,
_ => prop.type_id,
};
if let Some(nested_shape_id) = match self.interner().lookup(nested_type) {
Some(TypeData::Object(shape_id) | TypeData::ObjectWithIndex(shape_id)) => {
Some(shape_id)
}
_ => None,
} {
let nested_shape = self.interner().object_shape(nested_shape_id);
let mut nested_infer = None;
for nested_prop in &nested_shape.properties {
if let Some(TypeData::Infer(info)) = self.interner().lookup(nested_prop.type_id)
{
if nested_infer.is_some() {
nested_infer = None;
break;
}
nested_infer = Some((nested_prop.name, info));
}
}
if let Some((nested_name, info)) = nested_infer {
if infer_prop.is_some() || infer_nested.is_some() {
return None;
}
infer_nested = Some((prop.name, nested_name, info));
}
}
}
if let Some((prop_name, info, prop_optional)) = infer_prop {
return Some(self.eval_conditional_object_prop_infer(
cond,
check_unwrapped,
prop_name,
info,
prop_optional,
));
}
if let Some((outer_name, inner_name, info)) = infer_nested {
return Some(self.eval_conditional_object_nested_infer(
cond,
check_unwrapped,
outer_name,
inner_name,
info,
));
}
None
}
/// Handle object property infer pattern
fn eval_conditional_object_prop_infer(
&mut self,
cond: &ConditionalType,
check_unwrapped: TypeId,
prop_name: tsz_common::interner::Atom,
info: TypeParamInfo,
prop_optional: bool,
) -> TypeId {
if matches!(
self.interner().lookup(check_unwrapped),
Some(TypeData::TypeParameter(_) | TypeData::Infer(_))
) {
return self.interner().conditional(cond.clone());
}
let inferred = match self.interner().lookup(check_unwrapped) {
Some(TypeData::Object(shape_id) | TypeData::ObjectWithIndex(shape_id)) => {
let shape = self.interner().object_shape(shape_id);
shape
.properties
.iter()
.find(|prop| prop.name == prop_name)
.map(|prop| {
if prop_optional {
self.optional_property_type(prop)
} else {
prop.type_id
}
})
.or_else(|| prop_optional.then_some(TypeId::UNDEFINED))
}
Some(TypeData::Union(members)) => {
let members = self.interner().type_list(members);
let mut inferred_members = Vec::new();
for &member in members.iter() {
let member_unwrapped = match self.interner().lookup(member) {
Some(TypeData::ReadonlyType(inner)) => inner,
_ => member,
};
match self.interner().lookup(member_unwrapped) {
Some(TypeData::Object(shape_id) | TypeData::ObjectWithIndex(shape_id)) => {
let shape = self.interner().object_shape(shape_id);
if let Some(prop) =
PropertyInfo::find_in_slice(&shape.properties, prop_name)
{
inferred_members.push(if prop_optional {
self.optional_property_type(prop)
} else {
prop.type_id
});
} else if prop_optional {
inferred_members.push(TypeId::UNDEFINED);
} else {
return self.evaluate(cond.false_type);
}
}
_ => return self.evaluate(cond.false_type),
}
}
if inferred_members.is_empty() {
None
} else if inferred_members.len() == 1 {
Some(inferred_members[0])
} else {
Some(self.interner().union(inferred_members))
}
}
_ => None,
};
let Some(mut inferred) = inferred else {
return self.evaluate(cond.false_type);
};
let mut subst = TypeSubstitution::new();
subst.insert(info.name, inferred);
if let Some(constraint) = info.constraint {
let mut checker = SubtypeChecker::with_resolver(self.interner(), self.resolver());
checker.allow_bivariant_rest = true;
let is_union = matches!(self.interner().lookup(inferred), Some(TypeData::Union(_)));
if prop_optional {
let Some(filtered) =
self.filter_inferred_by_constraint(inferred, constraint, &mut checker)
else {
let false_inst =
instantiate_type_with_infer(self.interner(), cond.false_type, &subst);
return self.evaluate(false_inst);
};
inferred = filtered;
} else if is_union || cond.is_distributive {
// For unions or distributive conditionals, use filter that adds undefined
inferred = self.filter_inferred_by_constraint_or_undefined(
inferred,
constraint,
&mut checker,
);
} else {
// For non-distributive single values, fail if constraint doesn't match
if !checker.is_subtype_of(inferred, constraint) {
return self.evaluate(cond.false_type);
}
}
subst.insert(info.name, inferred);
}
let true_inst = instantiate_type_with_infer(self.interner(), cond.true_type, &subst);
self.evaluate(true_inst)
}
/// Handle nested object infer pattern
fn eval_conditional_object_nested_infer(
&mut self,
cond: &ConditionalType,
check_unwrapped: TypeId,
outer_name: tsz_common::interner::Atom,
inner_name: tsz_common::interner::Atom,
info: TypeParamInfo,
) -> TypeId {
if matches!(
self.interner().lookup(check_unwrapped),
Some(TypeData::TypeParameter(_) | TypeData::Infer(_))
) {
return self.interner().conditional(cond.clone());
}
let inferred = match self.interner().lookup(check_unwrapped) {
Some(TypeData::Object(shape_id) | TypeData::ObjectWithIndex(shape_id)) => {
let shape = self.interner().object_shape(shape_id);
shape
.properties
.iter()
.find(|prop| prop.name == outer_name)
.and_then(|prop| {
let inner_type = match self.interner().lookup(prop.type_id) {
Some(TypeData::ReadonlyType(inner)) => inner,
_ => prop.type_id,
};
match self.interner().lookup(inner_type) {
Some(
TypeData::Object(inner_shape_id)
| TypeData::ObjectWithIndex(inner_shape_id),
) => {
let inner_shape = self.interner().object_shape(inner_shape_id);
inner_shape
.properties
.iter()
.find(|prop| prop.name == inner_name)
.map(|prop| prop.type_id)
}
_ => None,
}
})
}
Some(TypeData::Union(members)) => {
let members = self.interner().type_list(members);
let mut inferred_members = Vec::new();
for &member in members.iter() {
let member_unwrapped = match self.interner().lookup(member) {
Some(TypeData::ReadonlyType(inner)) => inner,
_ => member,
};
let Some(TypeData::Object(shape_id) | TypeData::ObjectWithIndex(shape_id)) =
self.interner().lookup(member_unwrapped)
else {
return self.evaluate(cond.false_type);
};
let shape = self.interner().object_shape(shape_id);
let Some(prop) = PropertyInfo::find_in_slice(&shape.properties, outer_name)
else {
return self.evaluate(cond.false_type);
};
let inner_type = match self.interner().lookup(prop.type_id) {
Some(TypeData::ReadonlyType(inner)) => inner,
_ => prop.type_id,
};
let Some(
TypeData::Object(inner_shape_id)
| TypeData::ObjectWithIndex(inner_shape_id),
) = self.interner().lookup(inner_type)
else {
return self.evaluate(cond.false_type);
};
let inner_shape = self.interner().object_shape(inner_shape_id);
let Some(inner_prop) = inner_shape
.properties
.iter()
.find(|prop| prop.name == inner_name)
else {
return self.evaluate(cond.false_type);
};
inferred_members.push(inner_prop.type_id);
}
if inferred_members.is_empty() {
None
} else if inferred_members.len() == 1 {
Some(inferred_members[0])
} else {
Some(self.interner().union(inferred_members))
}
}
_ => None,
};
let Some(mut inferred) = inferred else {
return self.evaluate(cond.false_type);
};
let mut subst = TypeSubstitution::new();
subst.insert(info.name, inferred);
if let Some(constraint) = info.constraint {
let mut checker = SubtypeChecker::with_resolver(self.interner(), self.resolver());
checker.allow_bivariant_rest = true;
let is_union = matches!(self.interner().lookup(inferred), Some(TypeData::Union(_)));
if is_union || cond.is_distributive {
// For unions or distributive conditionals, use filter that adds undefined
inferred = self.filter_inferred_by_constraint_or_undefined(
inferred,
constraint,
&mut checker,
);
} else {
// For non-distributive single values, fail if constraint doesn't match
if !checker.is_subtype_of(inferred, constraint) {
return self.evaluate(cond.false_type);
}
}
subst.insert(info.name, inferred);
}
let true_inst = instantiate_type_with_infer(self.interner(), cond.true_type, &subst);
self.evaluate(true_inst)
}
/// Try to match conditional types at the Application level before structural expansion.
///
/// When both `check_type` and `extends_type` are Applications with the same base type
/// (e.g., `Promise<string>` vs `Promise<infer U>`), we can match type arguments
/// directly without expanding the interface structure. This is critical for complex
/// generic interfaces like Promise, Map, Set where structural expansion makes the
/// infer pattern matching fail.
fn try_application_infer_match(&mut self, cond: &ConditionalType) -> Option<TypeId> {
// Only proceed if extends_type is an Application containing infer.
// Keep extends_type as-is (unevaluated) so match_infer_pattern can handle
// it at the Application level. This is critical for complex generic interfaces
// like Promise, Map, Set where structural expansion loses the ability to
// match type arguments directly.
let Some(TypeData::Application(_)) = self.interner().lookup(cond.extends_type) else {
return None;
};
if !self.type_contains_infer(cond.extends_type) {
return None;
}
// Use the raw (unevaluated) check_type — it may still be an Application
// which enables Application-vs-Application matching in match_infer_pattern.
let check_type = cond.check_type;
// Skip for special types
if check_type == TypeId::ANY || check_type == TypeId::NEVER {
return None;
}
if matches!(
self.interner().lookup(check_type),
Some(TypeData::TypeParameter(_))
) {
return None;
}
// Try infer pattern matching with unevaluated types.
// match_infer_pattern handles Application vs Application matching
// by comparing base types and recursing on type arguments.
let mut checker = SubtypeChecker::with_resolver(self.interner(), self.resolver());
checker.allow_bivariant_rest = true;
let mut bindings = FxHashMap::default();
let mut visited = FxHashSet::default();
if self.match_infer_pattern(
check_type,
cond.extends_type,
&mut bindings,
&mut visited,
&mut checker,
) && !bindings.is_empty()
{
let substituted_true = self.substitute_infer(cond.true_type, &bindings);
return Some(self.evaluate(substituted_true));
}
None
}
}