1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use crate::mangle::MangledName;
use serde::{Deserialize, Serialize};
/// One member of an enum, as the member literal type `E.A` names it.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct EnumMember<V> {
pub name: String,
pub value: V,
/// How many members the enum has, so a union naming them all folds into
/// the enum, as TypeScript reduces `E.A | E.B` to `E`.
pub member_count: usize,
}
impl<V> EnumMember<V> {
pub fn new(name: &str, value: V, member_count: usize) -> Self {
EnumMember {
name: name.to_string(),
value,
member_count,
}
}
}
/// The value an enum member holds.
#[derive(Clone, Debug, PartialEq)]
pub enum EnumValue {
Number(LiteralF64),
String(String),
}
impl EnumValue {
/// The plain literal type of this value: `1` or `"a"`.
pub fn literal_type(&self) -> Type {
match self {
EnumValue::Number(value) => Type::NumberLiteral(*value),
EnumValue::String(value) => Type::StringLiteral(value.clone()),
}
}
}
/// `f64` wrapper for total ordering and bit-pattern equality — bare `f64` lacks `Eq`/`Ord`,
/// which would break the derived impls on [`Type`]. Construction must canonicalize `-0.0 → 0.0`;
/// NaN can't appear from source literals so bit-pattern equality is safe.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct LiteralF64(#[serde(with = "crate::artifact_f64")] pub f64);
impl PartialEq for LiteralF64 {
fn eq(&self, other: &Self) -> bool {
self.0.to_bits() == other.0.to_bits()
}
}
impl Eq for LiteralF64 {}
impl PartialOrd for LiteralF64 {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for LiteralF64 {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.total_cmp(&other.0)
}
}
impl std::hash::Hash for LiteralF64 {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state);
}
}
/// Owning package of a by-name [`Type`] reference (`InterfaceRef`, `AliasRef`, `Alias`,
/// `NumberEnum`, `StringEnum`). Carried so *structural* resolution of an already-typed
/// value can find the symbol by FQN in a global registry, independent of what the current
/// module imported.
///
/// **Excluded from identity:** `Eq`/`Ord`/`Hash` treat every `Package` as equal, so the
/// owning package never drives a by-name type's identity. Identity is the sibling
/// `mangled` field (the declaring symbol's mangled name, which already encodes the
/// package and module); `package` only keeps *structural* registry lookup robust to
/// which construction site stamped it.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Package(pub String);
impl Package {
pub fn prelude() -> Self {
Self(crate::mangle::PRELUDE_PACKAGE.to_string())
}
pub fn user() -> Self {
Self(crate::mangle::USER_PACKAGE.to_string())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl PartialEq for Package {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for Package {}
impl PartialOrd for Package {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Package {
fn cmp(&self, _: &Self) -> std::cmp::Ordering {
std::cmp::Ordering::Equal
}
}
impl std::hash::Hash for Package {
fn hash<H: std::hash::Hasher>(&self, _: &mut H) {}
}
/// `optional: true` means reads widen to `ty | undefined` and construction may omit the field.
/// Distinct from a value-nullable field (`ty: T | null, optional: false`): must be present
/// but can be null.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ObjectField {
pub ty: Type,
pub optional: bool,
/// `readonly` forbids writes through the field; assignability treats a writable
/// target field invariantly (see `assignable.rs`). Inferred object literals and
/// freshly-synthesized shapes are writable (`false`); only an explicit `readonly`
/// modifier on an object-type/interface property sets this.
pub readonly: bool,
/// A method rather than a function-typed property. `tsc` compares a method's
/// parameters bivariantly and a property's contravariantly.
#[serde(default)]
pub method: bool,
}
impl ObjectField {
pub fn required(ty: Type) -> Self {
Self {
ty,
optional: false,
readonly: false,
method: false,
}
}
pub fn optional(ty: Type) -> Self {
Self {
ty,
optional: true,
readonly: false,
method: false,
}
}
/// The type a *read* of this field yields: an optional field widens to
/// `T | undefined`, since an absent property reads as undefined. Every field
/// read — object type, interface property, class field, union member, and
/// codegen's mirror of all four — goes through this, so the widening rule
/// has one definition.
pub fn read_ty(&self) -> Type {
Self::widen_optional(self.optional, self.ty.clone())
}
/// [`read_ty`](Self::read_ty) for callers holding the two facts separately
/// (an interface `PropertySig`, a class `FieldSig`).
pub fn widen_optional(optional: bool, ty: Type) -> Type {
if optional {
Type::union(vec![ty, Type::Undefined])
} else {
ty
}
}
}
/// Values available under arbitrary string property names.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct IndexSignature {
pub value: Box<Type>,
pub readonly: bool,
}
impl IndexSignature {
pub fn map_value(&self, transform: impl FnOnce(&Type) -> Type) -> Self {
Self {
value: Box::new(transform(&self.value)),
readonly: self.readonly,
}
}
/// [`map_value`](Self::map_value) with a transform that can fail.
pub fn try_map_value<E>(
&self,
transform: impl FnOnce(&Type) -> Result<Type, E>,
) -> Result<Self, E> {
Ok(Self {
value: Box::new(transform(&self.value)?),
readonly: self.readonly,
})
}
pub fn read_ty(&self) -> Type {
Type::union(vec![(*self.value).clone(), Type::Undefined])
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TypePredicate {
pub parameter_index: u32,
pub asserted_type: Type,
}
/// Tuple positions and the number of trailing positions that may be omitted.
/// Optional positions include `Undefined` in their element type.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TupleType {
pub elements: Vec<Type>,
pub optional: usize,
}
impl TupleType {
pub fn required_len(&self) -> usize {
self.elements.len().saturating_sub(self.optional)
}
pub fn map(&self, transform: impl FnMut(&Type) -> Type) -> Self {
Self {
elements: self.elements.iter().map(transform).collect(),
optional: self.optional,
}
}
pub fn try_map<E>(&self, transform: impl FnMut(&Type) -> Result<Type, E>) -> Result<Self, E> {
Ok(Self {
elements: self
.elements
.iter()
.map(transform)
.collect::<Result<_, _>>()?,
optional: self.optional,
})
}
}
impl From<Vec<Type>> for TupleType {
fn from(elements: Vec<Type>) -> Self {
Self {
elements,
optional: 0,
}
}
}
impl std::ops::Deref for TupleType {
type Target = [Type];
fn deref(&self) -> &Self::Target {
&self.elements
}
}
impl IntoIterator for TupleType {
type Item = Type;
type IntoIter = std::vec::IntoIter<Type>;
fn into_iter(self) -> Self::IntoIter {
self.elements.into_iter()
}
}
impl<'a> IntoIterator for &'a TupleType {
type Item = &'a Type;
type IntoIter = std::slice::Iter<'a, Type>;
fn into_iter(self) -> Self::IntoIter {
self.elements.iter()
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Type {
Number,
/// No distinct runtime representation — codegen widens to `f64` at every emission site.
NumberLiteral(LiteralF64),
BigInt,
/// A bigint literal type: `123n`, `-1n`. Holds the value in decimal, with a
/// leading `-` when negative, so each value has one spelling. Like the other
/// literal types it lowers exactly as its base, `bigint`.
BigIntLiteral(String),
String,
StringLiteral(String),
Uint8Array,
Boolean,
/// `true` or `false`. Like the other literal types it has no runtime
/// representation of its own: it lowers exactly as `boolean`. `Type::union`
/// folds `true | false` into `boolean`, which is what `boolean` means.
BooleanLiteral(bool),
Null,
/// The single undefined value, distinct from language null and Wasm null.
Undefined,
Void,
/// Unlike TypeScript's `any`, requires explicit narrowing before use.
/// `Unknown | T` collapses to `Unknown`.
Unknown,
Function {
params: Vec<Type>,
/// Number of trailing fixed parameters callers may omit.
optional: usize,
ret: Box<Type>,
/// Boxed to break the `Type → Function → TypePredicate → Type` cycle. Guards are
/// assignable to plain functions but not vice versa.
predicate: Option<Box<TypePredicate>>,
/// When true, the last `params` entry holds the rest array type.
has_rest: bool,
},
/// `BTreeMap` gives structural `==`, deterministic iteration, and canonical field order for codegen.
Object {
fields: BTreeMap<String, ObjectField>,
index: Option<IndexSignature>,
},
Array(Box<Type>),
/// Parser rejects empty tuples. Index access requires an integer literal; out-of-range and
/// non-literal indices are rejected at typecheck time. Lowers to `(ref $Array)` at runtime.
Tuple(TupleType),
/// `readonly T[]` (also spelled `ReadonlyArray<T>`) or `readonly [A, B]`. The inner
/// type is always a [`Type::Array`] or [`Type::Tuple`]: the wrapper only forbids
/// writes, so [`Type::peel`] strips it and every read path sees the plain array.
/// Write paths (index assignment, mutating methods) must ask
/// [`Type::is_readonly_array`] before peeling. `Eq`/`Ord` keep it distinct from the
/// mutable type because a readonly array is not assignable to a mutable one.
Readonly(Box<Type>),
/// Diagnostic already reported; downstream code must not emit cascading errors.
Error,
/// No Wasm representation — never values never reach codegen.
Never,
/// Signature-form generic parameter. Never appears in function bodies — body inference
/// replaces each TypeVar with a fresh [`GenericParam`](Type::GenericParam) at body entry.
TypeVar(String),
/// Body-internal generic placeholder. Identity by `id` — two GPs with different ids are
/// distinct even when they share a name, preventing collisions across nested generic scopes.
GenericParam {
id: u32,
name: String,
},
/// A generic value with a proven runtime shape. Member access and lowering
/// use `ty`; assignability also preserves the original generic identity.
Refined {
original: Box<Type>,
ty: Box<Type>,
},
/// `args` carries already-substituted type arguments; empty for non-generic interfaces.
/// `mangled` is the declaring symbol's mangled name — the **nominal identity** (two
/// modules' same-named interfaces have distinct mangled names). `package`/`name` are
/// kept for diagnostics and import-independent *structural* resolution (see [`Package`]);
/// they do not drive identity. `mangled` is listed first so derived `Ord` keys on it.
InterfaceRef {
mangled: MangledName,
package: Package,
name: String,
args: Vec<Type>,
},
/// Nominal reference to a `class` declaration. Identity is `mangled` (two modules'
/// same-named classes are distinct); `package`/`name` are for diagnostics and
/// import-independent structural resolution, mirroring [`Type::InterfaceRef`].
/// `args` instantiates the class's type parameters; empty for a
/// non-generic class.
ClassRef {
mangled: MangledName,
package: Package,
name: String,
args: Vec<Type>,
},
/// Distinct from `StringEnum` so codegen knows the `i32` representation without consulting the type namespace.
///
/// `member` narrows the enum to one member's literal type, `E.A`, which is
/// what a member read has, as in TypeScript. It shares the enum's runtime
/// representation; [`Type::widen_literal`] drops it back to the enum.
NumberEnum {
mangled: MangledName,
package: Package,
name: String,
member: Option<EnumMember<LiteralF64>>,
},
StringEnum {
mangled: MangledName,
package: Package,
name: String,
member: Option<EnumMember<String>>,
},
/// Canonical union: sorted, deduplicated, no nested unions, no `Error` members, always ≥2
/// members. Build *only* via [`Type::union`].
Union(Vec<Type>),
/// Every pattern-match site must call [`Type::peel`] first; sole exception is
/// [`Display`](fmt::Display). `Eq`/`Ord`/`Hash` are nominal: `Alias { "ID", Number }` ≠
/// `Number` at the raw level. `args` carries already-substituted type arguments.
Alias {
mangled: MangledName,
package: Package,
name: String,
args: Vec<Type>,
ty: Box<Type>,
},
/// Lazy by-name reference to a type alias, used **only at a
/// recursion back-edge** — the inner `Json` in
/// `type Json = number | string | Json[]`, or the `Node` in
/// `type Node = { next: Node | null }`. Unlike [`Type::Alias`] it
/// carries no inline body; the body lives in the type namespace and
/// is resolved by name on demand (mirroring [`Type::InterfaceRef`]).
/// This keeps a recursive alias a *finite* `Type` value — a cyclic
/// inline body would infinitely recurse the derived `Eq`/`Ord` and
/// [`Type::peel`]. `peel` does **not** expand it (it stops here, the
/// same as `InterfaceRef`); the few sites that need the alias's
/// structure resolve it by name with cycle-safety.
AliasRef {
mangled: MangledName,
package: Package,
name: String,
args: Vec<Type>,
},
}
impl Type {
pub fn tuple(elements: Vec<Type>) -> Self {
Self::Tuple(elements.into())
}
/// A receiver whose computed string keys use the object property carrier.
pub fn is_structural_object(&self) -> bool {
match self.peel() {
Self::Object { .. } | Self::InterfaceRef { .. } => true,
Self::Union(members) => members.iter().all(Self::is_structural_object),
_ => false,
}
}
/// Build an [`Type::InterfaceRef`]. `mangled` is the declaring symbol's mangled
/// name (its nominal identity) — pass the symbol's own `mangled_name`, never a
/// value recomputed from `package`/`name`, so two construction sites for the same
/// type always agree.
pub fn interface_ref(
package: Package,
name: impl Into<String>,
mangled: MangledName,
args: Vec<Type>,
) -> Type {
Type::InterfaceRef {
mangled,
package,
name: name.into(),
args,
}
}
/// Build a [`Type::ClassRef`]. `mangled` is the class symbol's nominal identity;
/// pass the symbol's own `mangled_name`, never one recomputed from `package`/`name`.
pub fn class_ref(
package: Package,
name: impl Into<String>,
mangled: MangledName,
args: Vec<Type>,
) -> Type {
Type::ClassRef {
mangled,
package,
name: name.into(),
args,
}
}
pub fn number_enum(package: Package, name: impl Into<String>, mangled: MangledName) -> Type {
Type::NumberEnum {
mangled,
package,
name: name.into(),
member: None,
}
}
pub fn string_enum(package: Package, name: impl Into<String>, mangled: MangledName) -> Type {
Type::StringEnum {
mangled,
package,
name: name.into(),
member: None,
}
}
/// The member literal type `E.A` of the enum type `self`, which has
/// `member_count` members. `self` must be a `NumberEnum` holding a number
/// or a `StringEnum` holding a string. As in TypeScript, the one member of
/// an enum has the enum's own type.
pub fn with_enum_member(
&self,
member_name: &str,
value: EnumValue,
member_count: usize,
) -> Type {
if member_count < 2 {
return self.without_enum_member();
}
match (self.clone(), value) {
(
Type::NumberEnum {
mangled,
package,
name,
..
},
EnumValue::Number(value),
) => Type::NumberEnum {
mangled,
package,
name,
member: Some(EnumMember::new(member_name, value, member_count)),
},
(
Type::StringEnum {
mangled,
package,
name,
..
},
EnumValue::String(value),
) => Type::StringEnum {
mangled,
package,
name,
member: Some(EnumMember::new(member_name, value, member_count)),
},
(ty, _) => ty,
}
}
/// The enum a member literal type `E.A` belongs to; any other type unchanged.
pub fn without_enum_member(&self) -> Type {
match self {
Type::NumberEnum {
mangled,
package,
name,
member: Some(_),
} => Type::number_enum(package.clone(), name.clone(), mangled.clone()),
Type::StringEnum {
mangled,
package,
name,
member: Some(_),
} => Type::string_enum(package.clone(), name.clone(), mangled.clone()),
_ => self.clone(),
}
}
/// Whether this is one literal type, what TypeScript calls a unit type:
/// `1`, `"a"`, `true`, `1n` or an enum member `E.A`.
pub fn is_literal_type(&self) -> bool {
matches!(
self,
Type::NumberLiteral(_)
| Type::StringLiteral(_)
| Type::BooleanLiteral(_)
| Type::BigIntLiteral(_)
) || self.is_enum_member()
}
/// Whether this is an enum member literal type `E.A`.
pub fn is_enum_member(&self) -> bool {
self.enum_member_name().is_some()
}
/// The enum, member name and member count of an enum member literal type `E.A`.
pub fn enum_member_name(&self) -> Option<(&MangledName, &str, usize)> {
match self {
Type::NumberEnum {
mangled,
member: Some(member),
..
} => Some((mangled, &member.name, member.member_count)),
Type::StringEnum {
mangled,
member: Some(member),
..
} => Some((mangled, &member.name, member.member_count)),
_ => None,
}
}
/// The value an enum member literal type `E.A` holds.
pub fn enum_member_value(&self) -> Option<EnumValue> {
match self.peel() {
Type::NumberEnum {
member: Some(member),
..
} => Some(EnumValue::Number(member.value)),
Type::StringEnum {
member: Some(member),
..
} => Some(EnumValue::String(member.value.clone())),
_ => None,
}
}
pub fn alias_ref(
package: Package,
name: impl Into<String>,
mangled: MangledName,
args: Vec<Type>,
) -> Type {
Type::AliasRef {
mangled,
package,
name: name.into(),
args,
}
}
pub fn alias_ty(
package: Package,
name: impl Into<String>,
mangled: MangledName,
args: Vec<Type>,
ty: Box<Type>,
) -> Type {
Type::Alias {
mangled,
package,
name: name.into(),
args,
ty,
}
}
/// Convenience for a non-namespaced prelude interface (`Error`, `Response`, …):
/// the prelude registers these with `mangled_name = prelude(name)`, so this is
/// the matching identity. Namespaced prelude types (`Temporal.*`) must instead
/// use [`Type::interface_ref`] with `extend(prelude("Temporal"), local)`.
pub fn prelude_interface(name: impl Into<String>, args: Vec<Type>) -> Type {
let name = name.into();
let mangled = crate::mangle::prelude(&name);
Type::interface_ref(Package::prelude(), name, mangled, args)
}
/// The built-in `Error` class reference — the type of `throw`/`catch` values
/// and the root of user error subclasses.
pub fn prelude_error_class() -> Type {
Type::class_ref(
Package::prelude(),
"Error",
crate::mangle::prelude("Error"),
Vec::new(),
)
}
/// The built-in `RangeError` class reference — the host-implemented
/// `Error` subclass for out-of-range failures.
pub fn prelude_range_error_class() -> Type {
Type::class_ref(
Package::prelude(),
"RangeError",
crate::mangle::prelude("RangeError"),
Vec::new(),
)
}
/// Remove display aliases while retaining generic guard identity.
pub fn without_aliases(&self) -> &Type {
match self {
Type::Alias { ty, .. } => ty.without_aliases(),
_ => self,
}
}
pub fn peel(&self) -> &Type {
let mut t = self;
while let Type::Alias { ty, .. } | Type::Refined { ty, .. } | Type::Readonly(ty) = t {
t = ty;
}
t
}
/// [`peel`](Self::peel), but stopping at a [`Type::Readonly`] wrapper, for
/// sites that carry a type onward and must not drop its readonly-ness.
pub fn peel_preserving_readonly(&self) -> &Type {
let mut t = self;
while let Type::Alias { ty, .. } | Type::Refined { ty, .. } = t {
t = ty;
}
t
}
/// Whether writes through a value of this type are forbidden because it is a
/// `readonly` array or tuple, looking through aliases and refinements.
pub fn is_readonly_array(&self) -> bool {
matches!(self.peel_preserving_readonly(), Type::Readonly(_))
}
/// The element type of a rest parameter's array: `T` for `T[]` or
/// `readonly T[]`. Not peeled through aliases, since rest lowering matches the
/// parameter type as written.
pub fn rest_element(&self) -> Option<&Type> {
match self {
Type::Array(element) => Some(element),
Type::Readonly(inner) => match inner.as_ref() {
Type::Array(element) => Some(element),
_ => None,
},
_ => None,
}
}
/// A rest parameter's type with any `readonly` removed. Each call packs a
/// fresh array for the rest, so whether the callee may write to it is the
/// callee's own concern: two function types relate on their rest elements,
/// as in tsc.
pub fn rest_array_ignoring_readonly(&self) -> &Type {
match self {
Type::Readonly(inner) if matches!(inner.as_ref(), Type::Array(_)) => inner,
_ => self,
}
}
/// Whether this is a union of only arrays and tuples, which share the `$Array`
/// representation.
pub fn is_array_like_union(&self) -> bool {
match self.peel() {
Type::Union(members) => members
.iter()
.all(|member| matches!(member.peel(), Type::Array(_) | Type::Tuple(_))),
_ => false,
}
}
/// The element of a union of arrays and tuples read as one array: any
/// member's element. `None` for any other type. Only reads may go through
/// it; writing a member's element through the joined type could store
/// another member's element type.
pub fn array_like_union_element(&self) -> Option<Type> {
let Type::Union(members) = self.peel() else {
return None;
};
let elements = members
.iter()
.map(|member| match member.peel() {
Type::Array(element) => Some((**element).clone()),
Type::Tuple(positions) => Some(Type::union(positions.elements.clone())),
_ => None,
})
.collect::<Option<Vec<_>>>()?;
Some(Type::union(elements))
}
/// The arrays and tuples of a union of strings with arrays or tuples, and
/// nothing else, as their own union. Such a union has no shared
/// representation, so each use tests `typeof` and takes the string's or the
/// array's path.
pub fn string_or_array_union_arrays(&self) -> Option<Type> {
let Type::Union(members) = self.peel() else {
return None;
};
let (strings, arrays): (Vec<Type>, Vec<Type>) = members
.iter()
.cloned()
.partition(|member| member.peel().is_string_shaped());
let all_arrays = arrays
.iter()
.all(|member| matches!(member.peel(), Type::Array(_) | Type::Tuple(_)));
(!strings.is_empty() && !arrays.is_empty() && all_arrays).then(|| Type::union(arrays))
}
/// The array a union of arrays and tuples reads as: see
/// [`Self::array_like_union_element`].
pub fn array_like_union_view(&self) -> Option<Type> {
self.array_like_union_element()
.map(|element| Type::Array(Box::new(element)))
}
/// Whether this type is `void`, through any depth of alias.
///
/// `void` is the one type with no value slot at all, so a gate that tests
/// for it decides between "one Wasm result" and "none". Every such gate —
/// in the typechecker *and* in codegen — must answer the same way for
/// `type V = void` as for `void`: a bare `matches!(ty, Type::Void)` hands an
/// aliased `void` a value slot that
/// [`SymbolTable::value_type`](crate::codegen::symbol_table::SymbolTable::value_type)
/// then refuses to lower. A typecheck gate must not start peeling ahead of
/// its codegen counterpart, which turns a clean diagnostic into a panic.
pub fn is_void(&self) -> bool {
matches!(self.peel(), Type::Void)
}
/// Whether a function taking `actual` parameters can stand where one taking
/// `expected` is called. As in TypeScript, it may declare fewer and ignore
/// the rest of the arguments; a closure adapter drops them at runtime. Rest
/// functions keep an exact arity, since their packed array has a slot of its
/// own.
pub fn function_arity_fits(actual: usize, expected: usize, has_rest: bool) -> bool {
actual == expected || (!has_rest && actual < expected)
}
/// Whether a value of this type would need a `void` slot at runtime:
/// `void` itself, or a union that lists it.
///
/// Deliberately one level deep — it does **not** descend into a function's
/// return type, where `void` is legitimate (`() => void`). Every gate that
/// refuses `void` in a value or comparison position wants this, not the
/// bare [`is_void`](Self::is_void). `cond ? f() : 1` and `a ?? f()` are
/// plain `void`, so no expression builds the union form; a gate that asks
/// this still refuses one that did, rather than letting it reach codegen.
pub fn carries_void(&self) -> bool {
match self.peel() {
Type::Void => true,
Type::Union(members) => members.iter().any(|m| matches!(m.peel(), Type::Void)),
_ => false,
}
}
/// Primitive operations shared by enums and homogeneous literal unions,
/// without widening their type identity or changing assignability.
pub fn primitive_behavior(&self) -> &Type {
match self.peel() {
Type::NumberEnum { .. } => &Type::Number,
Type::StringEnum { .. } => &Type::String,
Type::BooleanLiteral(_) => &Type::Boolean,
Type::BigIntLiteral(_) => &Type::BigInt,
Type::Union(members)
if !members.is_empty()
&& members.iter().all(|member| {
matches!(
member.primitive_behavior(),
Type::Number | Type::NumberLiteral(_)
)
}) =>
{
&Type::Number
}
Type::Union(members)
if !members.is_empty()
&& members
.iter()
.all(|member| matches!(member.primitive_behavior(), Type::BigInt)) =>
{
&Type::BigInt
}
Type::Union(members)
if !members.is_empty() && members.iter().all(Type::is_string_shaped) =>
{
&Type::String
}
ty => ty,
}
}
/// Whether every value of this type is a bigint: `bigint`, a bigint literal
/// type, or a union or alias of those.
pub fn is_bigint(&self) -> bool {
matches!(self.primitive_behavior(), Type::BigInt)
}
/// This type with literal types replaced by the primitive they are a literal of.
///
/// A literal type is only sound where the value cannot change, so inference keeps
/// it at a `const` binding and widens here at every position that is mutable or
/// whose type is inferred from its contents — a `let` binding, an array element,
/// an object-literal property, a generic argument. `const a = 1` is `1`, but
/// `let b = a` is `number`, matching TypeScript.
///
/// An enum member literal type `E.A` widens to its enum `E`, not to the
/// enum's primitive: the enum is a nominal type whose identity its members
/// are checked against. Use [`primitive_behavior`](Self::primitive_behavior)
/// for the primitive.
pub fn widen_literal(&self) -> Type {
match self {
Type::NumberLiteral(_) => Type::Number,
Type::StringLiteral(_) => Type::String,
Type::BooleanLiteral(_) => Type::Boolean,
Type::BigIntLiteral(_) => Type::BigInt,
_ if self.is_enum_member() => self.without_enum_member(),
// A union widens memberwise, which also collapses it when the members
// share a base: `1 | 2` is `number`, not `number | number`, because
// `Type::union` deduplicates.
Type::Union(members) => Type::union(members.iter().map(Type::widen_literal).collect()),
_ => self.clone(),
}
}
/// The primitive this literal type, or union of literals of one
/// primitive, is a literal of: `number` for `1 | 2`, `None` for
/// `1 | "a"` or a type that is no literal.
pub fn literal_base(&self) -> Option<Type> {
let widened = self.widen_literal();
(widened != *self && matches!(widened, Type::Number | Type::String | Type::Boolean))
.then_some(widened)
}
/// Whether every part of this type is a string — a `string`, a
/// string-literal type, or a union of those.
///
/// The typechecker, the import collector, and codegen must agree on this
/// exactly: a shape accepted by one and not the others emits a `$string`
/// into an `f64` slot, which fails Wasm validation rather than type
/// checking. Contrast [`contains_string`](Self::contains_string), which
/// asks the `any` question.
pub fn is_string_shaped(&self) -> bool {
match self.peel() {
Type::String | Type::StringLiteral(_) | Type::StringEnum { .. } => true,
Type::Union(members) => members.iter().all(Type::is_string_shaped),
_ => false,
}
}
/// Whether *some* part of this type is a string. Diagnostics-only: it is
/// what decides whether a rejected operand still deserves the "convert
/// first" help, so `string | null` gets it.
pub fn contains_string(&self) -> bool {
match self.peel() {
Type::String | Type::StringLiteral(_) | Type::StringEnum { .. } => true,
Type::Union(members) => members.iter().any(Type::contains_string),
_ => false,
}
}
/// Whether any member, through unions, satisfies `leaf`, which sees peeled
/// types. Syntactic: an alias reference is a leaf, not expanded; the
/// typechecker's `any_resolved_member` follows alias bodies through its
/// resolver.
pub fn any_member(&self, leaf: &dyn Fn(&Type) -> bool) -> bool {
match self.peel() {
Type::Union(members) => members.iter().any(|member| member.any_member(leaf)),
member => leaf(member),
}
}
/// Whether every member, through unions, satisfies `leaf`. Syntactic,
/// like [`Type::any_member`].
pub fn all_members(&self, leaf: &dyn Fn(&Type) -> bool) -> bool {
!self.any_member(&|member| !leaf(member))
}
/// Whether `null` is spelled among the members. Syntactic, unlike the
/// typechecker's `type_admits_null`: `unknown` doesn't count.
pub fn spells_null(&self) -> bool {
self.any_member(&|member| matches!(member, Type::Null))
}
/// Whether `undefined`, or an erased `void` result, is spelled among the
/// members. `unknown` and type parameters don't count.
pub fn spells_undefined(&self) -> bool {
self.any_member(&|member| matches!(member, Type::Undefined | Type::Void))
}
/// Whether a value of the member type `leaf` has no JSON text at the
/// document root, so `JSON.stringify` returns `undefined` for it.
/// Objects and arrays holding such values still produce a document.
pub fn stringifies_to_undefined(leaf: &Type) -> bool {
matches!(
leaf,
Type::Undefined
| Type::Void
| Type::Unknown
| Type::GenericParam { .. }
| Type::TypeVar(_)
| Type::Function { .. }
)
}
/// Normalizes to a flat member list that is unique *by peeled type*.
///
/// Both halves peel because a nominal key is unsound here: an alias whose
/// body is a union is a nested union in disguise, and every downstream
/// per-member probe (`value_type`'s nullability test, narrowing's member
/// walk) reads it as one opaque member. Deduping nominally leaves
/// `N | number` as a two-member union that no operator is defined on.
///
/// The alias label a union displays therefore survives only where it is
/// still a single member: an alias of a union is replaced by its members,
/// and among duplicates the alias-labelled spelling wins regardless of
/// source order, so `N | number` and `number | N` both keep `N`.
///
/// `peel` stops at a *recursive* alias (it is a name, not a body), so a
/// recursive alias never dedups against its own expansion. Both spellings
/// lower the same way, so this costs a redundant member, not correctness.
pub fn union(members: Vec<Type>) -> Type {
if members.iter().any(|m| matches!(m.peel(), Type::Error)) {
return Type::Error;
}
// `unknown | T` → `unknown`; peels aliases so `type Dyn = unknown` still collapses.
if members.iter().any(|m| matches!(m.peel(), Type::Unknown)) {
return Type::Unknown;
}
// `T | never` → `T`. After Error/Unknown checks so cascading-silence wins.
let members: Vec<Type> = members
.into_iter()
.filter(|m| !matches!(m.peel(), Type::Never))
.collect();
let mut flat: Vec<Type> = Vec::new();
for m in members {
match m.without_aliases() {
Type::Union(inner) => flat.extend(inner.iter().cloned()),
_ => flat.push(m),
}
}
// Sorting by the peeled key groups alias-labelled duplicates next to
// their body; aliases rank 0 so they sort first within the group, and
// `dedup_by` keeps the earlier element — the name the user wrote.
let alias_rank = |t: &Type| u8::from(!matches!(t, Type::Alias { .. }));
flat.sort_by(|a, b| {
a.without_aliases()
.cmp(b.without_aliases())
.then_with(|| alias_rank(a).cmp(&alias_rank(b)))
});
flat.dedup_by(|a, b| a.without_aliases() == b.without_aliases());
fold_boolean_literals(&mut flat);
fold_enum_members(&mut flat);
if flat.len() > 1 {
return Type::Union(flat);
}
match flat.into_iter().next() {
Some(member) => member,
None => Type::Never,
}
}
/// For method dispatch. Erased generics route to `Object`. Aliases peel. Returns `None`
/// for function, void, null, and error. The first tuple element is the owning package
/// for diagnostics; the mangled name is the structural lookup key. Built-in
/// interfaces (`Number`, `Array`, `Object`, …) live in the prelude package.
pub fn interface_routing(&self) -> Option<(MangledName, &str, &str, Vec<Type>)> {
let prelude = crate::mangle::PRELUDE_PACKAGE;
match self.primitive_behavior() {
// A literal type routes to its base's interface: `"abc".at(0)` resolves the
// same members a `string` receiver does. The prelude `Number`/`String`
// interfaces expose no mutating members, so routing a literal there cannot
// invalidate it.
Type::Number | Type::NumberLiteral(_) => Some((
crate::mangle::prelude("Number"),
prelude,
"Number",
Vec::new(),
)),
Type::BigInt => Some((
crate::mangle::prelude("BigInt"),
prelude,
"BigInt",
Vec::new(),
)),
Type::Boolean => Some((
crate::mangle::prelude("Boolean"),
prelude,
"Boolean",
Vec::new(),
)),
Type::String | Type::StringLiteral(_) => Some((
crate::mangle::prelude("String"),
prelude,
"String",
Vec::new(),
)),
Type::Uint8Array => Some((
crate::mangle::prelude("Uint8Array"),
prelude,
"Uint8Array",
Vec::new(),
)),
Type::Array(elem) => Some((
crate::mangle::prelude("Array"),
prelude,
"Array",
vec![(**elem).clone()],
)),
// Tuples are arrays at runtime; route to `Array` with the positions'
// union as the element type so reads (`length`, `map`, `at`, …) flow
// through. Mutating methods are rejected separately at the call site.
Type::Tuple(elements) => Some((
crate::mangle::prelude("Array"),
prelude,
"Array",
vec![Type::union(elements.elements.clone())],
)),
Type::Object { .. } | Type::TypeVar(_) | Type::GenericParam { .. } => Some((
crate::mangle::prelude("Object"),
prelude,
"Object",
Vec::new(),
)),
Type::InterfaceRef {
mangled,
package,
name,
args,
..
}
| Type::ClassRef {
mangled,
package,
name,
args,
..
} => Some((
mangled.clone(),
package.as_str(),
name.as_str(),
args.clone(),
)),
// Enum values route to Object (not Number/String) to keep the API surface minimal.
Type::NumberEnum { .. } | Type::StringEnum { .. } => Some((
crate::mangle::prelude("Object"),
prelude,
"Object",
Vec::new(),
)),
// `unknown` routes to Object so vtable methods work.
Type::Unknown => Some((
crate::mangle::prelude("Object"),
prelude,
"Object",
Vec::new(),
)),
_ => None,
}
}
}
/// `ty` as written beside a `?` marker, which already admits `undefined`: without
/// its `undefined` member. A type that is only `undefined` stays as it is.
/// Every renderer of optional parameters shows them through this, except
/// `type_rendering`'s `Frame::Optional`, which applies the same rule to
/// borrowed members.
pub(crate) fn shown_beside_optional_marker(ty: &Type) -> Type {
match ty.peel() {
Type::Union(members) => Type::union(
members
.iter()
.filter(|member| !matches!(member.peel(), Type::Undefined))
.cloned()
.collect(),
),
_ => ty.clone(),
}
}
/// `s` escaped for a double-quoted string the way `tsc` prints a string literal
/// type (`escapeString` in TypeScript's `utilities.ts`): `"G\"HI"`, `"a\nb"`.
pub(crate) fn escape_string_literal(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = crate::literal_units::literal_chars(s).peekable();
while let Some(c) = chars.next() {
let c = match c {
Ok(c) => c,
Err(lone) => {
out.push_str(&format!("\\u{lone:04X}"));
continue;
}
};
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{8}' => out.push_str("\\b"),
'\u{b}' => out.push_str("\\v"),
'\u{c}' => out.push_str("\\f"),
// `\0` before a digit would read as an octal escape.
'\0' if chars
.peek()
.is_some_and(|next| next.is_ok_and(|d| d.is_ascii_digit())) =>
{
out.push_str("\\x00");
}
'\0' => out.push_str("\\0"),
'\u{0}'..='\u{1f}' | '\u{85}' | '\u{2028}' | '\u{2029}' => {
out.push_str(&format!("\\u{:04X}", u32::from(c)));
}
c => out.push(c),
}
}
out
}
/// The [`Type::BigIntLiteral`] of a bigint literal's decimal digits, as the
/// lexer writes them.
pub fn bigint_literal_type(digits: &str) -> Type {
Type::BigIntLiteral(canonical_bigint_digits(digits))
}
/// `digits` negated, in [`Type::BigIntLiteral`]'s spelling: `-0n` is `0n`.
pub fn negate_bigint_digits(digits: &str) -> String {
let canonical = canonical_bigint_digits(digits);
if canonical == "0" {
return canonical;
}
match canonical.strip_prefix('-') {
Some(magnitude) => magnitude.to_string(),
None => format!("-{canonical}"),
}
}
/// `digits` without leading zeros, keeping a sign, and `0` for zero.
fn canonical_bigint_digits(digits: &str) -> String {
let (sign, magnitude) = match digits.strip_prefix('-') {
Some(magnitude) => ("-", magnitude),
None => ("", digits),
};
match magnitude.trim_start_matches('0') {
"" => "0".to_string(),
trimmed => format!("{sign}{trimmed}"),
}
}
/// `boolean` is `true | false`: a union holding both literals, or `boolean`
/// and either literal, holds exactly `boolean`. `members` is sorted and
/// deduplicated, and stays so.
fn fold_boolean_literals(members: &mut Vec<Type>) {
let is_boolean = |m: &Type| matches!(m.without_aliases(), Type::Boolean);
let is_literal = |m: &Type| matches!(m.without_aliases(), Type::BooleanLiteral(_));
let literals = members.iter().filter(|m| is_literal(m)).count();
let has_boolean = members.iter().any(is_boolean);
if literals == 0 || (literals == 1 && !has_boolean) {
return;
}
members.retain(|m| !is_literal(m));
if !has_boolean {
let at = members.partition_point(|m| m.without_aliases() < &Type::Boolean);
members.insert(at, Type::Boolean);
}
}
/// Reduces enum types as TypeScript does: a member beside its enum is absorbed
/// by it, members naming every member of their enum are the enum, and an enum
/// or member beside its primitive (`E | number`) is absorbed by the primitive.
/// Leaves `members` sorted and deduplicated.
fn fold_enum_members(members: &mut Vec<Type>) {
absorb_enums_into_primitives(members);
let complete = complete_enums(members);
if complete.is_empty() {
return;
}
for member in members.iter_mut() {
if let Type::NumberEnum { mangled, .. } | Type::StringEnum { mangled, .. } =
member.without_aliases()
&& complete.contains(mangled)
{
*member = member.without_aliases().without_enum_member();
}
}
members.sort_by(|a, b| a.without_aliases().cmp(b.without_aliases()));
members.dedup_by(|a, b| a.without_aliases() == b.without_aliases());
}
/// Drops every enum type and member beside the primitive it holds.
fn absorb_enums_into_primitives(members: &mut Vec<Type>) {
let has = |base: &Type| members.iter().any(|m| m.without_aliases() == base);
let (has_number, has_string) = (has(&Type::Number), has(&Type::String));
members.retain(|m| match m.without_aliases() {
Type::NumberEnum { .. } => !has_number,
Type::StringEnum { .. } => !has_string,
_ => true,
});
}
/// The enums `members` holds whole: as the enum itself, or by naming every
/// one of its members.
fn complete_enums(members: &[Type]) -> BTreeSet<MangledName> {
struct NamedMembers<'a> {
member_count: usize,
names: BTreeSet<&'a str>,
}
let mut named: BTreeMap<&MangledName, NamedMembers> = BTreeMap::new();
let mut whole: BTreeSet<&MangledName> = BTreeSet::new();
for member in members {
let ty = member.without_aliases();
if let Some((mangled, name, member_count)) = ty.enum_member_name() {
named
.entry(mangled)
.or_insert_with(|| NamedMembers {
member_count,
names: BTreeSet::new(),
})
.names
.insert(name);
} else if let Type::NumberEnum { mangled, .. } | Type::StringEnum { mangled, .. } = ty {
whole.insert(mangled);
}
}
named
.into_iter()
.filter(|(mangled, named)| {
whole.contains(mangled) || named.names.len() >= named.member_count
})
.map(|(mangled, _)| mangled.clone())
.collect()
}
impl Type {
pub fn render_checked(
&self,
limits: crate::rendering::RenderLimits,
) -> Result<crate::rendering::RenderedText, crate::rendering::RenderError> {
crate::type_rendering::render(self, limits)
}
}
/// A union's members in the order they are printed. Members are stored in
/// canonical order, which puts `null` and `undefined` first; they print last,
/// as TypeScript prints them: `string | null | undefined`.
pub fn union_display_order(members: &[Type]) -> Vec<&Type> {
let mut ordered: Vec<&Type> = members.iter().collect();
ordered.sort_by_key(|m| match m {
Type::Null => 1,
Type::Undefined => 2,
_ => 0,
});
ordered
}
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.render_checked(crate::rendering::RenderLimits::default()) {
Ok(rendered) => f.write_str(&rendered.text),
Err(_) => f.write_str("[diagnostic type unavailable]"),
}
}
}
#[cfg(test)]
mod tests {
use super::{Package, Type};
#[test]
fn tuple_mapping_preserves_optional_positions() {
let tuple = super::TupleType {
elements: vec![Type::NumberLiteral(super::LiteralF64(1.0)), Type::Undefined],
optional: 1,
};
let mapped = tuple.map(Type::widen_literal);
assert_eq!(mapped.optional, 1);
assert_eq!(mapped.required_len(), 1);
assert_eq!(mapped.elements, vec![Type::Number, Type::Undefined]);
}
#[test]
fn optional_fields_read_as_undefined() {
let field = super::ObjectField::optional(Type::String);
assert_eq!(
field.read_ty(),
Type::union(vec![Type::String, Type::Undefined])
);
}
#[test]
fn optional_function_and_tuple_display_preserve_omission() {
let ty = Type::Function {
params: vec![Type::union(vec![Type::String, Type::Undefined])],
optional: 1,
ret: Box::new(Type::Void),
predicate: None,
has_rest: false,
};
// An optional parameter admits `undefined` already, as `tsc` prints it.
assert_eq!(ty.to_string(), "(arg0?: string) => void");
let tuple = Type::Tuple(super::TupleType {
elements: vec![
Type::Number,
Type::union(vec![Type::String, Type::Undefined]),
],
optional: 1,
});
assert_eq!(tuple.to_string(), "[number, (string | undefined)?]");
}
#[test]
fn atomic_display() {
assert_eq!(Type::Number.to_string(), "number");
assert_eq!(Type::String.to_string(), "string");
assert_eq!(Type::Boolean.to_string(), "boolean");
assert_eq!(Type::Null.to_string(), "null");
assert_eq!(Type::Void.to_string(), "void");
assert_eq!(Type::Error.to_string(), "<error>");
}
#[test]
fn readonly_display_matches_typescript() {
let numbers = Type::Array(Box::new(Type::Number));
let readonly = Type::Readonly(Box::new(numbers.clone()));
assert_eq!(readonly.to_string(), "readonly number[]");
assert_eq!(
Type::Array(Box::new(readonly.clone())).to_string(),
"(readonly number[])[]"
);
assert_eq!(
Type::Readonly(Box::new(Type::Array(Box::new(numbers)))).to_string(),
"readonly number[][]"
);
assert_eq!(
Type::Readonly(Box::new(Type::Tuple(
vec![Type::Number, Type::String].into()
)))
.to_string(),
"readonly [number, string]"
);
assert!(readonly.is_readonly_array());
assert_eq!(readonly.peel(), &Type::Array(Box::new(Type::Number)));
}
#[test]
fn string_literal_display_escapes_like_typescript() {
// Each expectation is what `tsc` 5.9 prints for the same literal type.
let cases = [
("G\"HI\\", r#""G\"HI\\""#),
("a\nb\r\t", r#""a\nb\r\t""#),
("\u{8}\u{b}\u{c}", r#""\b\v\f""#),
("\0x", r#""\0x""#),
("\u{0}1", r#""\x001""#),
("\u{7}\u{1b}", r#""\u0007\u001B""#),
("\u{85}\u{2028}\u{2029}", r#""\u0085\u2028\u2029""#),
("\u{7f}é", "\"\u{7f}é\""),
];
for (value, printed) in cases {
assert_eq!(Type::StringLiteral(value.into()).to_string(), printed);
}
}
#[test]
fn structural_equality() {
assert_eq!(Type::Number, Type::Number);
assert_ne!(Type::Number, Type::String);
let a = Type::Function {
params: vec![Type::Number, Type::String],
ret: Box::new(Type::Boolean),
predicate: None,
has_rest: false,
optional: 0,
};
let b = Type::Function {
params: vec![Type::Number, Type::String],
ret: Box::new(Type::Boolean),
predicate: None,
has_rest: false,
optional: 0,
};
let c = Type::Function {
params: vec![Type::Number],
ret: Box::new(Type::Boolean),
predicate: None,
has_rest: false,
optional: 0,
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn function_display_no_params() {
let t = Type::Function {
params: vec![],
ret: Box::new(Type::Number),
predicate: None,
has_rest: false,
optional: 0,
};
assert_eq!(t.to_string(), "() => number");
}
#[test]
fn function_display_one_param() {
let t = Type::Function {
params: vec![Type::Number],
ret: Box::new(Type::Boolean),
predicate: None,
has_rest: false,
optional: 0,
};
assert_eq!(t.to_string(), "(arg0: number) => boolean");
}
#[test]
fn function_display_multi_param() {
let t = Type::Function {
params: vec![Type::Number, Type::String],
ret: Box::new(Type::Void),
predicate: None,
has_rest: false,
optional: 0,
};
assert_eq!(t.to_string(), "(arg0: number, arg1: string) => void");
}
#[test]
fn function_display_nested() {
let inner = Type::Function {
params: vec![],
ret: Box::new(Type::Number),
predicate: None,
has_rest: false,
optional: 0,
};
let outer = Type::Function {
params: vec![],
ret: Box::new(inner),
predicate: None,
has_rest: false,
optional: 0,
};
assert_eq!(outer.to_string(), "() => () => number");
}
#[test]
fn clone_roundtrip() {
let t = Type::Function {
params: vec![Type::Number, Type::String],
ret: Box::new(Type::Boolean),
predicate: None,
has_rest: false,
optional: 0,
};
assert_eq!(t.clone(), t);
}
fn point_type() -> Type {
let mut fields = std::collections::BTreeMap::new();
fields.insert("x".to_string(), crate::ObjectField::required(Type::Number));
fields.insert("y".to_string(), crate::ObjectField::required(Type::Number));
Type::Object {
index: None,
fields,
}
}
#[test]
fn object_structural_equality_ignores_field_insertion_order() {
let mut a = std::collections::BTreeMap::new();
a.insert("y".to_string(), crate::ObjectField::required(Type::Number));
a.insert("x".to_string(), crate::ObjectField::required(Type::Number));
let mut b = std::collections::BTreeMap::new();
b.insert("x".to_string(), crate::ObjectField::required(Type::Number));
b.insert("y".to_string(), crate::ObjectField::required(Type::Number));
assert_eq!(
Type::Object {
index: None,
fields: a
},
Type::Object {
index: None,
fields: b
}
);
}
#[test]
fn object_inequality_on_different_field_set() {
let mut a = std::collections::BTreeMap::new();
a.insert("x".to_string(), crate::ObjectField::required(Type::Number));
let mut b = std::collections::BTreeMap::new();
b.insert("y".to_string(), crate::ObjectField::required(Type::Number));
assert_ne!(
Type::Object {
index: None,
fields: a
},
Type::Object {
index: None,
fields: b
}
);
}
#[test]
fn object_display() {
assert_eq!(point_type().to_string(), "{ x: number; y: number }");
let empty = Type::Object {
index: None,
fields: std::collections::BTreeMap::new(),
};
assert_eq!(empty.to_string(), "{}");
}
#[test]
fn object_display_with_optional_field() {
let mut fields = std::collections::BTreeMap::new();
fields.insert("x".to_string(), crate::ObjectField::required(Type::Number));
fields.insert("y".to_string(), crate::ObjectField::optional(Type::String));
let t = Type::Object {
index: None,
fields,
};
assert_eq!(t.to_string(), "{ x: number; y?: string }");
}
#[test]
fn object_inequality_required_vs_optional() {
let mut a = std::collections::BTreeMap::new();
a.insert("x".to_string(), crate::ObjectField::required(Type::Number));
let mut b = std::collections::BTreeMap::new();
b.insert("x".to_string(), crate::ObjectField::optional(Type::Number));
assert_ne!(
Type::Object {
index: None,
fields: a
},
Type::Object {
index: None,
fields: b
}
);
}
#[test]
fn array_equality() {
assert_eq!(
Type::Array(Box::new(Type::Number)),
Type::Array(Box::new(Type::Number))
);
assert_ne!(
Type::Array(Box::new(Type::Number)),
Type::Array(Box::new(Type::String))
);
}
#[test]
fn array_display() {
assert_eq!(Type::Array(Box::new(Type::Number)).to_string(), "number[]");
assert_eq!(
Type::Array(Box::new(Type::Array(Box::new(Type::Number)))).to_string(),
"number[][]"
);
}
#[test]
fn nested_object_in_array_display() {
let arr = Type::Array(Box::new(point_type()));
assert_eq!(arr.to_string(), "{ x: number; y: number }[]");
}
#[test]
fn type_var_display_uses_source_name() {
assert_eq!(Type::TypeVar("T".to_string()).to_string(), "T");
assert_eq!(Type::TypeVar("Key".to_string()).to_string(), "Key");
}
#[test]
fn type_var_structural_equality_by_name() {
let t = Type::TypeVar("T".to_string());
let t2 = Type::TypeVar("T".to_string());
let u = Type::TypeVar("U".to_string());
assert_eq!(t, t2);
assert_ne!(t, u);
assert_ne!(t, Type::Number);
}
#[test]
fn type_var_inside_array_and_function_displays_through() {
let arr = Type::Array(Box::new(Type::TypeVar("T".to_string())));
assert_eq!(arr.to_string(), "T[]");
let func = Type::Function {
params: vec![Type::TypeVar("T".to_string())],
ret: Box::new(Type::TypeVar("U".to_string())),
predicate: None,
has_rest: false,
optional: 0,
};
assert_eq!(func.to_string(), "(arg0: T) => U");
}
#[test]
fn generic_param_display_uses_name_not_id() {
let gp = Type::GenericParam {
id: 42,
name: "T".to_string(),
};
assert_eq!(gp.to_string(), "T");
}
#[test]
fn generic_param_equality_by_id() {
let a = Type::GenericParam {
id: 5,
name: "T".to_string(),
};
let b = Type::GenericParam {
id: 5,
name: "T".to_string(),
};
assert_eq!(a, b);
let c = Type::GenericParam {
id: 6,
name: "T".to_string(),
};
assert_ne!(a, c);
}
#[test]
fn union_canonical_dedup() {
let t = Type::union(vec![Type::Number, Type::Null, Type::Number]);
let Type::Union(members) = t else {
panic!("expected Union, got {t:?}");
};
assert_eq!(members, vec![Type::Number, Type::Null]);
}
#[test]
fn union_canonical_order_independent() {
let a = Type::union(vec![Type::Number, Type::Null]);
let b = Type::union(vec![Type::Null, Type::Number]);
assert_eq!(a, b);
}
#[test]
fn union_collapses_to_single_member() {
let t = Type::union(vec![Type::Number, Type::Number]);
assert_eq!(t, Type::Number);
}
#[test]
fn union_flattens_nested() {
let inner = Type::union(vec![Type::String, Type::Null]);
let outer = Type::union(vec![Type::Number, inner]);
let expected = Type::union(vec![Type::Number, Type::String, Type::Null]);
assert_eq!(outer, expected);
}
#[test]
fn union_error_member_collapses_to_error() {
let t = Type::union(vec![Type::Number, Type::Error]);
assert_eq!(t, Type::Error);
}
#[test]
fn union_display_basic() {
let t = Type::union(vec![Type::Number, Type::String]);
assert_eq!(t.to_string(), "number | string");
}
#[test]
fn union_display_with_null() {
let t = Type::union(vec![Type::Number, Type::Null]);
assert_eq!(t.to_string(), "number | null");
let t2 = Type::union(vec![Type::Null, Type::Number]);
assert_eq!(t2.to_string(), "number | null");
}
#[test]
fn union_display_wraps_function_member() {
let fn_ty = Type::Function {
params: vec![],
ret: Box::new(Type::String),
predicate: None,
has_rest: false,
optional: 0,
};
let t = Type::union(vec![fn_ty, Type::Boolean]);
assert_eq!(t.to_string(), "boolean | (() => string)");
}
use super::LiteralF64;
#[test]
fn string_literal_display_is_quoted() {
let t = Type::StringLiteral("north".to_string());
assert_eq!(t.to_string(), "\"north\"");
}
#[test]
fn number_literal_display_is_unquoted_with_whole_number_shape() {
let whole = Type::NumberLiteral(LiteralF64(42.0));
assert_eq!(whole.to_string(), "42");
let frac = Type::NumberLiteral(LiteralF64(4.5));
assert_eq!(frac.to_string(), "4.5");
}
#[test]
fn string_literal_equality_by_value() {
let a = Type::StringLiteral("hi".to_string());
let b = Type::StringLiteral("hi".to_string());
let c = Type::StringLiteral("bye".to_string());
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn number_literal_equality_by_value() {
let a = Type::NumberLiteral(LiteralF64(42.0));
let b = Type::NumberLiteral(LiteralF64(42.0));
let c = Type::NumberLiteral(LiteralF64(43.0));
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn union_sorts_literals_next_to_base_types() {
// NumberLiteral sorts after Number, StringLiteral after String per variant order.
let t = Type::union(vec![
Type::String,
Type::StringLiteral("hi".to_string()),
Type::Number,
Type::NumberLiteral(LiteralF64(42.0)),
]);
assert_eq!(t.to_string(), "number | 42 | string | \"hi\"");
}
#[test]
fn widen_literal_replaces_a_literal_with_its_base() {
assert_eq!(
Type::NumberLiteral(LiteralF64(1.0)).widen_literal(),
Type::Number
);
assert_eq!(
Type::StringLiteral("hi".to_string()).widen_literal(),
Type::String
);
}
/// A union widens memberwise, and `Type::union` then deduplicates — so a union of
/// literals over one base collapses to that base rather than repeating it.
#[test]
fn widen_literal_collapses_a_union_of_literals() {
let t = Type::union(vec![
Type::NumberLiteral(LiteralF64(1.0)),
Type::NumberLiteral(LiteralF64(2.0)),
]);
assert_eq!(t.widen_literal(), Type::Number);
}
/// Enums are nominal, not literal: widening one would discard the identity its
/// members are checked against. `primitive_behavior` is the enum-aware accessor.
#[test]
fn widen_literal_leaves_everything_else_alone() {
assert_eq!(Type::Number.widen_literal(), Type::Number);
assert_eq!(Type::Boolean.widen_literal(), Type::Boolean);
let arr = Type::Array(Box::new(Type::NumberLiteral(LiteralF64(1.0))));
assert_eq!(arr.widen_literal(), arr);
}
#[test]
fn union_of_two_string_literals_sorts_by_value() {
let t = Type::union(vec![
Type::StringLiteral("south".to_string()),
Type::StringLiteral("north".to_string()),
]);
assert_eq!(t.to_string(), "\"north\" | \"south\"");
}
#[test]
fn literal_f64_equality_distinguishes_negative_zero_at_bit_level() {
// Bit-pattern equality distinguishes -0.0 and +0.0; parser canonicalizes -0.0→0.0 so
// this case won't appear in practice.
let pos = LiteralF64(0.0);
let neg = LiteralF64(-0.0);
assert_ne!(pos, neg);
}
#[test]
fn type_var_and_generic_param_are_distinct_types() {
// TypeVar is signature form; GenericParam is body form.
// Even with the same name they're different variants.
let tv = Type::TypeVar("T".to_string());
let gp = Type::GenericParam {
id: 0,
name: "T".to_string(),
};
assert_ne!(tv, gp);
}
#[test]
fn alias_display_renders_name_not_body() {
let ty = user_alias("Circle", point_type());
assert_eq!(ty.to_string(), "Circle");
}
#[test]
fn peel_walks_through_alias_to_underlying() {
let inner = Type::Number;
let aliased = user_alias("ID", inner.clone());
assert_eq!(aliased.peel(), &inner);
}
#[test]
fn peel_is_idempotent_through_nested_aliases() {
let nested = user_alias("A", user_alias("B", Type::Number));
assert_eq!(nested.peel(), &Type::Number);
assert_eq!(nested.peel().peel(), &Type::Number);
}
#[test]
fn alias_is_not_structurally_equal_to_underlying() {
let aliased = user_alias("ID", Type::Number);
assert_ne!(aliased, Type::Number);
assert_eq!(aliased.peel(), &Type::Number);
}
#[test]
fn alias_routes_to_underlying_interface() {
let aliased = user_alias("ID", Type::Number);
let (_mangled, _pkg, iface, _args) = aliased.interface_routing().expect("number routes");
assert_eq!(iface, "Number");
}
#[test]
fn union_of_error_alias_collapses_to_error() {
let alias_err = user_alias("Bad", Type::Error);
let t = Type::union(vec![Type::Number, alias_err]);
assert_eq!(t, Type::Error);
}
#[test]
fn union_preserves_distinct_alias_members_for_display() {
let circle = user_alias("Circle", point_type());
let rect = user_alias("Rectangle", Type::Number);
let t = Type::union(vec![circle, rect]);
// Ordered by the peeled bodies, which puts `Number` before the object
// shape — not by the order the members were written.
assert_eq!(t.to_string(), "Rectangle | Circle");
}
#[test]
fn union_dedups_an_alias_against_its_own_body_keeping_the_label() {
let n = user_alias("N", Type::Number);
assert_eq!(Type::union(vec![n.clone(), Type::Number]), n);
assert_eq!(Type::union(vec![Type::Number, n.clone()]), n);
}
#[test]
fn union_dedups_aliases_that_share_one_body() {
let circle = user_alias("Circle", point_type());
let rect = user_alias("Rectangle", point_type());
assert_eq!(Type::union(vec![circle.clone(), rect]), circle);
}
#[test]
fn union_flattens_an_alias_whose_body_is_a_union() {
let nullable = user_alias("MN", Type::union(vec![Type::Number, Type::Null]));
assert_eq!(
Type::union(vec![nullable, Type::Number]),
Type::union(vec![Type::Number, Type::Null])
);
}
#[test]
fn generic_alias_display_includes_args() {
let ty = user_alias_args("Box", vec![Type::Number], Type::Number);
assert_eq!(ty.to_string(), "Box<number>");
}
fn iface(package: &str, name: &str) -> Type {
Type::interface_ref(
Package(package.to_string()),
name,
crate::mangle::package_symbol(package, name),
Vec::new(),
)
}
fn user_alias(name: &str, ty: Type) -> Type {
user_alias_args(name, Vec::new(), ty)
}
fn user_alias_args(name: &str, args: Vec<Type>, ty: Type) -> Type {
Type::alias_ty(
Package::user(),
name,
crate::mangle::package_symbol(crate::mangle::USER_PACKAGE, name),
args,
Box::new(ty),
)
}
#[test]
fn mangled_name_keys_type_identity() {
// Identity is the mangled name. Same `(package, name)` ⇒ same mangled ⇒ equal;
// a different owning package ⇒ different mangled ⇒ distinct (the multi-file
// property: two same-named interfaces in different packages/modules are not
// conflated).
assert_eq!(iface("main", "Response"), iface("main", "Response"));
let http = iface("submilli:http", "Response");
let main = iface("main", "Response");
assert_ne!(
http, main,
"different package ⇒ different mangled ⇒ distinct"
);
assert_ne!(
http.cmp(&main),
std::cmp::Ordering::Equal,
"Ord must distinguish distinct mangled names"
);
assert_ne!(
iface("main", "Response"),
iface("main", "Other"),
"different names stay distinct"
);
}
#[test]
fn same_name_different_module_not_equal_nor_assignable() {
// The core multi-file guarantee: a sibling module's `Logger`
// (`mod:main#util#Logger`) is a distinct type from the root's `Logger`
// (`main#Logger`), even though the bare name matches.
let root = iface("main", "Logger");
let sibling = Type::InterfaceRef {
mangled: crate::mangle::package_module_symbol("main", "util", "Logger"),
package: Package::user(),
name: "Logger".to_string(),
args: Vec::new(),
};
assert_ne!(root, sibling);
// Same mangled ⇒ equal.
let root2 = iface("main", "Logger");
assert_eq!(root, root2);
}
#[test]
fn union_dedups_interface_refs_by_mangled() {
// Same mangled collapses to one member; different mangled stays a 2-member union.
let same = Type::union(vec![iface("main", "Response"), iface("main", "Response")]);
assert!(
!matches!(same, Type::Union(_)),
"identical refs collapse to one member, got {same:?}"
);
let distinct = Type::union(vec![
iface("submilli:http", "Response"),
iface("main", "Response"),
]);
assert!(
matches!(distinct, Type::Union(ref ms) if ms.len() == 2),
"distinct-package refs stay a 2-member union, got {distinct:?}"
);
}
#[test]
fn generic_alias_display_multiple_args() {
let ty = user_alias_args("Pair", vec![Type::String, Type::Number], Type::Number);
assert_eq!(ty.to_string(), "Pair<string, number>");
}
}