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
//! Comprehensive tests for intersection and union type normalization and edge cases.

use super::*;
use crate::intern::TypeInterner;

// =============================================================================
// Intersection Type Tests - Primitive to Never
// =============================================================================

#[test]
fn test_intersection_string_number_is_never() {
    let interner = TypeInterner::new();

    // string & number = never
    let result = interner.intersection2(TypeId::STRING, TypeId::NUMBER);
    assert_eq!(result, TypeId::NEVER, "string & number should be never");
}

#[test]
fn test_intersection_string_boolean_is_never() {
    let interner = TypeInterner::new();

    // string & boolean = never
    let result = interner.intersection2(TypeId::STRING, TypeId::BOOLEAN);
    assert_eq!(result, TypeId::NEVER, "string & boolean should be never");
}

#[test]
fn test_intersection_number_boolean_is_never() {
    let interner = TypeInterner::new();

    // number & boolean = never
    let result = interner.intersection2(TypeId::NUMBER, TypeId::BOOLEAN);
    assert_eq!(result, TypeId::NEVER, "number & boolean should be never");
}

#[test]
fn test_intersection_string_bigint_is_never() {
    let interner = TypeInterner::new();

    // string & bigint = never
    let result = interner.intersection2(TypeId::STRING, TypeId::BIGINT);
    assert_eq!(result, TypeId::NEVER, "string & bigint should be never");
}

#[test]
fn test_intersection_symbol_string_is_never() {
    let interner = TypeInterner::new();

    // symbol & string = never
    let result = interner.intersection2(TypeId::SYMBOL, TypeId::STRING);
    assert_eq!(result, TypeId::NEVER, "symbol & string should be never");
}

#[test]
fn test_intersection_null_undefined_is_never() {
    let interner = TypeInterner::new();

    // null & undefined = never
    let result = interner.intersection2(TypeId::NULL, TypeId::UNDEFINED);
    assert_eq!(result, TypeId::NEVER, "null & undefined should be never");
}

#[test]
fn test_intersection_literal_of_different_types_is_never() {
    let interner = TypeInterner::new();

    let hello = interner.literal_string("hello");
    let one = interner.literal_number(1.0);

    // "hello" & 1 = never
    let result = interner.intersection2(hello, one);
    assert_eq!(result, TypeId::NEVER, "\"hello\" & 1 should be never");
}

#[test]
fn test_intersection_same_primitive_is_itself() {
    let interner = TypeInterner::new();

    // string & string = string
    let result = interner.intersection2(TypeId::STRING, TypeId::STRING);
    assert_eq!(result, TypeId::STRING, "string & string should be string");
}

#[test]
fn test_intersection_different_string_literals_is_never() {
    let interner = TypeInterner::new();

    let hello = interner.literal_string("hello");
    let world = interner.literal_string("world");

    // "hello" & "world" = never
    let result = interner.intersection2(hello, world);
    assert_eq!(
        result,
        TypeId::NEVER,
        "\"hello\" & \"world\" should be never"
    );
}

#[test]
fn test_intersection_different_number_literals_is_never() {
    let interner = TypeInterner::new();

    let one = interner.literal_number(1.0);
    let two = interner.literal_number(2.0);

    // 1 & 2 = never
    let result = interner.intersection2(one, two);
    assert_eq!(result, TypeId::NEVER, "1 & 2 should be never");
}

#[test]
fn test_intersection_literal_with_primitive_is_literal() {
    let interner = TypeInterner::new();

    let hello = interner.literal_string("hello");

    // "hello" & string = "hello"
    let result = interner.intersection2(hello, TypeId::STRING);
    // The intersection should narrow to the literal type since "hello" is a subtype of string
    // But in TypeScript's type system, intersection of a literal with its primitive type
    // results in the literal type
    assert_eq!(result, hello, "\"hello\" & string should be \"hello\"");
}

// =============================================================================
// Intersection Type Tests - Object Property Merging
// =============================================================================

#[test]
fn test_intersection_object_merge_properties() {
    let interner = TypeInterner::new();

    let obj_a = interner.object(vec![PropertyInfo::new(
        interner.intern_string("a"),
        TypeId::STRING,
    )]);

    let obj_b = interner.object(vec![PropertyInfo::new(
        interner.intern_string("b"),
        TypeId::NUMBER,
    )]);

    // A & B should merge properties
    let result = interner.intersection2(obj_a, obj_b);

    // Result should have both properties
    if let Some(TypeData::Object(shape_id)) = interner.lookup(result) {
        let shape = interner.object_shape(shape_id);
        assert_eq!(shape.properties.len(), 2, "Should have both properties");

        // Check property "a"
        let prop_a = shape
            .properties
            .iter()
            .find(|p| p.name == interner.intern_string("a"));
        assert!(prop_a.is_some(), "Should have property 'a'");
        assert_eq!(prop_a.unwrap().type_id, TypeId::STRING);

        // Check property "b"
        let prop_b = shape
            .properties
            .iter()
            .find(|p| p.name == interner.intern_string("b"));
        assert!(prop_b.is_some(), "Should have property 'b'");
        assert_eq!(prop_b.unwrap().type_id, TypeId::NUMBER);
    } else {
        panic!("Expected object type");
    }
}

#[test]
fn test_intersection_object_same_property_intersect_types() {
    let interner = TypeInterner::new();

    let obj_a = interner.object(vec![PropertyInfo::new(
        interner.intern_string("x"),
        TypeId::STRING,
    )]);

    let obj_b = interner.object(vec![PropertyInfo::new(
        interner.intern_string("x"),
        TypeId::NUMBER,
    )]);

    // A & B should have property x: string & number = never
    let result = interner.intersection2(obj_a, obj_b);

    // The intersection creates an object with a property of type never
    // This is different from the whole intersection being never
    if let Some(TypeData::Object(shape_id)) = interner.lookup(result) {
        let shape = interner.object_shape(shape_id);
        let prop_x = shape
            .properties
            .iter()
            .find(|p| p.name == interner.intern_string("x"));
        assert!(prop_x.is_some());
        assert_eq!(
            prop_x.unwrap().type_id,
            TypeId::NEVER,
            "Property type should be never"
        );
    } else {
        panic!("Expected object type with never property");
    }
}

#[test]
fn test_intersection_required_wins_over_optional() {
    let interner = TypeInterner::new();

    let obj_optional = interner.object(vec![PropertyInfo::opt(
        interner.intern_string("x"),
        TypeId::STRING,
    )]);

    let obj_required = interner.object(vec![PropertyInfo::new(
        interner.intern_string("x"),
        TypeId::STRING,
    )]);

    // optional & required = required (required wins)
    let result = interner.intersection2(obj_optional, obj_required);

    if let Some(TypeData::Object(shape_id)) = interner.lookup(result) {
        let shape = interner.object_shape(shape_id);
        let prop_x = shape
            .properties
            .iter()
            .find(|p| p.name == interner.intern_string("x"));
        assert!(prop_x.is_some());
        assert!(!prop_x.unwrap().optional, "Property should be required");
    } else {
        panic!("Expected object type");
    }
}

#[test]
fn test_intersection_readonly_is_cumulative() {
    let interner = TypeInterner::new();

    let obj_readonly = interner.object(vec![PropertyInfo::readonly(
        interner.intern_string("x"),
        TypeId::STRING,
    )]);

    let obj_mutable = interner.object(vec![PropertyInfo::new(
        interner.intern_string("x"),
        TypeId::STRING,
    )]);

    // readonly & mutable = readonly (readonly is cumulative)
    let result = interner.intersection2(obj_readonly, obj_mutable);

    if let Some(TypeData::Object(shape_id)) = interner.lookup(result) {
        let shape = interner.object_shape(shape_id);
        let prop_x = shape
            .properties
            .iter()
            .find(|p| p.name == interner.intern_string("x"));
        assert!(prop_x.is_some());
        assert!(prop_x.unwrap().readonly, "Property should be readonly");
    } else {
        panic!("Expected object type");
    }
}

#[test]
fn test_intersection_both_optional_stays_optional() {
    let interner = TypeInterner::new();

    let obj_a = interner.object(vec![PropertyInfo::opt(
        interner.intern_string("x"),
        TypeId::STRING,
    )]);

    let obj_b = interner.object(vec![PropertyInfo::opt(
        interner.intern_string("x"),
        TypeId::STRING,
    )]);

    // optional & optional = optional
    let result = interner.intersection2(obj_a, obj_b);

    if let Some(TypeData::Object(shape_id)) = interner.lookup(result) {
        let shape = interner.object_shape(shape_id);
        let prop_x = shape
            .properties
            .iter()
            .find(|p| p.name == interner.intern_string("x"));
        assert!(prop_x.is_some());
        assert!(prop_x.unwrap().optional, "Property should be optional");
    } else {
        panic!("Expected object type");
    }
}

// =============================================================================
// Intersection Type Tests - Function Overloading
// =============================================================================

#[test]
fn test_intersection_function_overloads() {
    let interner = TypeInterner::new();

    // Create first function signature: (x: string) => number
    let func1 = interner.function(FunctionShape {
        type_params: vec![],
        params: vec![ParamInfo {
            name: Some(interner.intern_string("x")),
            type_id: TypeId::STRING,
            optional: false,
            rest: false,
        }],
        this_type: None,
        return_type: TypeId::NUMBER,
        type_predicate: None,
        is_constructor: false,
        is_method: false,
    });

    // Create second function signature: (x: number) => string
    let func2 = interner.function(FunctionShape {
        type_params: vec![],
        params: vec![ParamInfo {
            name: Some(interner.intern_string("x")),
            type_id: TypeId::NUMBER,
            optional: false,
            rest: false,
        }],
        this_type: None,
        return_type: TypeId::STRING,
        type_predicate: None,
        is_constructor: false,
        is_method: false,
    });

    // Intersection should create a callable with both signatures
    let result = interner.intersection2(func1, func2);

    if let Some(TypeData::Callable(shape_id)) = interner.lookup(result) {
        let shape = interner.callable_shape(shape_id);
        assert_eq!(
            shape.call_signatures.len(),
            2,
            "Should have both call signatures"
        );
    } else {
        panic!("Expected callable type with overloaded signatures");
    }
}

// =============================================================================
// Union Type Tests - Literal Absorption
// =============================================================================

#[test]
fn test_union_literal_absorbed_into_primitive() {
    let interner = TypeInterner::new();

    let hello = interner.literal_string("hello");
    let world = interner.literal_string("world");

    // "hello" | "world" | string should normalize to just string
    let result = interner.union3(hello, world, TypeId::STRING);

    assert_eq!(
        result,
        TypeId::STRING,
        "Literals should be absorbed into primitive"
    );
}

#[test]
fn test_union_number_literals_absorbed_into_number() {
    let interner = TypeInterner::new();

    let one = interner.literal_number(1.0);
    let two = interner.literal_number(2.0);
    let three = interner.literal_number(3.0);

    // 1 | 2 | 3 | number should normalize to just number
    let result = interner.union(vec![one, two, three, TypeId::NUMBER]);

    assert_eq!(
        result,
        TypeId::NUMBER,
        "Number literals should be absorbed into number"
    );
}

#[test]
fn test_union_boolean_literals_absorbed_into_boolean() {
    let interner = TypeInterner::new();

    // true | false | boolean should normalize to just boolean
    let result = interner.union3(TypeId::BOOLEAN_TRUE, TypeId::BOOLEAN_FALSE, TypeId::BOOLEAN);

    assert_eq!(
        result,
        TypeId::BOOLEAN,
        "Boolean literals should be absorbed into boolean"
    );
}

#[test]
fn test_union_true_false_reduces_to_boolean() {
    let interner = TypeInterner::new();

    // true | false (without explicit boolean) should normalize to boolean
    // This matches TypeScript behavior: `true | false` === `boolean`
    let t = interner.literal_boolean(true);
    let f = interner.literal_boolean(false);
    assert_eq!(
        t,
        TypeId::BOOLEAN_TRUE,
        "literal_boolean(true) should use intrinsic ID"
    );
    assert_eq!(
        f,
        TypeId::BOOLEAN_FALSE,
        "literal_boolean(false) should use intrinsic ID"
    );

    let result = interner.union2(t, f);
    assert_eq!(
        result,
        TypeId::BOOLEAN,
        "true | false should reduce to boolean"
    );
}

#[test]
fn test_union_bigint_literals_absorbed_into_bigint() {
    let interner = TypeInterner::new();

    let bigint1 = interner.literal_bigint("1");
    let bigint2 = interner.literal_bigint("2");

    // 1n | 2n | bigint should normalize to just bigint
    let result = interner.union3(bigint1, bigint2, TypeId::BIGINT);

    assert_eq!(
        result,
        TypeId::BIGINT,
        "Bigint literals should be absorbed into bigint"
    );
}

#[test]
fn test_union_literals_without_primitive_stay_as_union() {
    let interner = TypeInterner::new();

    let hello = interner.literal_string("hello");
    let world = interner.literal_string("world");

    // "hello" | "world" should stay as a union (no primitive present)
    let result = interner.union2(hello, world);

    if let Some(TypeData::Union(list_id)) = interner.lookup(result) {
        let members = interner.type_list(list_id);
        assert_eq!(members.len(), 2, "Should have both literals");
    } else {
        panic!("Expected union type");
    }
}

// =============================================================================
// Union Type Tests - Any/Unknown Handling
// =============================================================================

#[test]
fn test_union_any_dominates() {
    let interner = TypeInterner::new();

    // any | string = any
    let result = interner.union2(TypeId::ANY, TypeId::STRING);
    assert_eq!(result, TypeId::ANY, "any should dominate union");

    // string | any = any
    let result = interner.union2(TypeId::STRING, TypeId::ANY);
    assert_eq!(result, TypeId::ANY, "any should dominate union");
}

#[test]
fn test_union_unknown_dominates() {
    let interner = TypeInterner::new();

    // unknown | string = unknown
    let result = interner.union2(TypeId::UNKNOWN, TypeId::STRING);
    assert_eq!(result, TypeId::UNKNOWN, "unknown should dominate union");
}

#[test]
fn test_union_any_dominates_unknown() {
    let interner = TypeInterner::new();

    // any | unknown = any
    let result = interner.union2(TypeId::ANY, TypeId::UNKNOWN);
    assert_eq!(result, TypeId::ANY, "any should dominate unknown");
}

// =============================================================================
// Union Type Tests - Simplification (Removing Never, Deduplicating, Sorting)
// =============================================================================

#[test]
fn test_union_remove_never() {
    let interner = TypeInterner::new();

    // string | never should normalize to string
    let result = interner.union2(TypeId::STRING, TypeId::NEVER);
    assert_eq!(result, TypeId::STRING, "never should be removed from union");
}

#[test]
fn test_union_multiple_never_removed() {
    let interner = TypeInterner::new();

    // string | never | number | never should normalize to string | number
    let result = interner.union(vec![
        TypeId::STRING,
        TypeId::NEVER,
        TypeId::NUMBER,
        TypeId::NEVER,
    ]);

    if let Some(TypeData::Union(list_id)) = interner.lookup(result) {
        let members = interner.type_list(list_id);
        assert_eq!(
            members.len(),
            2,
            "Should have 2 members after removing never"
        );
    } else {
        panic!("Expected union type");
    }
}

#[test]
fn test_union_only_never_is_never() {
    let interner = TypeInterner::new();

    // never | never = never
    let result = interner.union2(TypeId::NEVER, TypeId::NEVER);
    assert_eq!(result, TypeId::NEVER, "Union of only never should be never");
}

#[test]
fn test_union_deduplicates() {
    let interner = TypeInterner::new();

    // string | string | number should normalize to string | number
    let result = interner.union(vec![TypeId::STRING, TypeId::STRING, TypeId::NUMBER]);

    if let Some(TypeData::Union(list_id)) = interner.lookup(result) {
        let members = interner.type_list(list_id);
        assert_eq!(members.len(), 2, "Should deduplicate string");
    } else {
        panic!("Expected union type");
    }
}

#[test]
fn test_union_sorts_consistently() {
    let interner = TypeInterner::new();

    // Create union in one order
    let result1 = interner.union(vec![TypeId::NUMBER, TypeId::STRING]);

    // Create union in different order
    let result2 = interner.union(vec![TypeId::STRING, TypeId::NUMBER]);

    // Should be the same (sorted for consistent hashing)
    assert_eq!(result1, result2, "Unions should be sorted consistently");
}

// =============================================================================
// Intersection Type Tests - Simplification
// =============================================================================

#[test]
fn test_intersection_remove_unknown() {
    let interner = TypeInterner::new();

    // string & unknown should normalize to string
    let result = interner.intersection2(TypeId::STRING, TypeId::UNKNOWN);
    assert_eq!(
        result,
        TypeId::STRING,
        "unknown should be removed from intersection"
    );
}

#[test]
fn test_intersection_any_is_identity() {
    let interner = TypeInterner::new();

    // string & any = string (any is identity for intersection in practice)
    let result = interner.intersection2(TypeId::STRING, TypeId::ANY);
    assert_eq!(
        result,
        TypeId::ANY,
        "any in intersection should result in any"
    );
}

#[test]
fn test_intersection_flattens_nested() {
    let interner = TypeInterner::new();

    let obj_a = interner.object(vec![PropertyInfo::new(
        interner.intern_string("a"),
        TypeId::STRING,
    )]);

    let obj_b = interner.object(vec![PropertyInfo::new(
        interner.intern_string("b"),
        TypeId::NUMBER,
    )]);

    let inner = interner.intersection2(obj_a, obj_b);
    let outer = interner.intersection2(inner, obj_a);

    // Should flatten and deduplicate
    assert_eq!(inner, outer, "Nested intersections should be flattened");
}

// =============================================================================
// Distributive Conditional Types Over Unions
// =============================================================================

#[test]
fn test_distributive_conditional_over_union() {
    let interner = TypeInterner::new();

    // (string | number) extends string ? true : false
    // Should distribute to: (string extends string ? true : false) | (number extends string ? true : false)
    // = true | false = boolean

    let union = interner.union2(TypeId::STRING, TypeId::NUMBER);

    let conditional = ConditionalType {
        check_type: union,
        extends_type: TypeId::STRING,
        true_type: TypeId::BOOLEAN_TRUE,
        false_type: TypeId::BOOLEAN_FALSE,
        is_distributive: true,
    };

    let result = interner.conditional(conditional);

    // The result should be a conditional type with is_distributive flag set
    // Note: The actual distribution happens during type evaluation in the evaluator
    if let Some(TypeData::Conditional(cond_id)) = interner.lookup(result) {
        let cond = interner.conditional_type(cond_id);
        assert!(cond.is_distributive, "Should be marked as distributive");
        assert_eq!(cond.check_type, union);
        assert_eq!(cond.extends_type, TypeId::STRING);
    } else {
        panic!("Expected conditional type");
    }
}

// =============================================================================
// Edge Cases - Empty and Single Member
// =============================================================================

#[test]
fn test_intersection_empty_is_unknown() {
    let interner = TypeInterner::new();

    // Empty intersection should be unknown (identity element)
    let result = interner.intersection(vec![]);
    assert_eq!(
        result,
        TypeId::UNKNOWN,
        "Empty intersection should be unknown"
    );
}

#[test]
fn test_intersection_single_member_is_itself() {
    let interner = TypeInterner::new();

    // Single-member intersection should be that member
    let result = interner.intersection(vec![TypeId::STRING]);
    assert_eq!(
        result,
        TypeId::STRING,
        "Single-member intersection should be that member"
    );
}

#[test]
fn test_union_empty_is_never() {
    let interner = TypeInterner::new();

    // Empty union should be never (identity element)
    let result = interner.union(vec![]);
    assert_eq!(result, TypeId::NEVER, "Empty union should be never");
}

#[test]
fn test_union_single_member_is_itself() {
    let interner = TypeInterner::new();

    // Single-member union should be that member
    let result = interner.union(vec![TypeId::STRING]);
    assert_eq!(
        result,
        TypeId::STRING,
        "Single-member union should be that member"
    );
}