submilli-engine 0.3.0

Compiles Submilli programs, a TypeScript subset, to WebAssembly and runs them under capability policy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
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
//! Type-level assignability rule + small literal-bridging helpers used
//! by the predicate-environment extractor.

use std::collections::BTreeMap;
use std::ops::ControlFlow;

use crate::{MangledName, MethodSig, ObjectField, Type, TypeKind};

use super::generic::substitute_or_record;
use super::narrowing;
use super::type_namespace::TypeNamespace;
use super::type_registry::TypeRegistry;
use super::variance::Variance;

/// The pair of tables structural resolution needs: the import-scoped namespace
/// plus the import-independent FQN registry. Carried (by `Copy`) wherever
/// assignability recurses so a recursion back-edge into a *library* alias still
/// resolves by its own package, not just what the current module imported.
#[derive(Clone, Copy)]
pub(crate) struct TypeResolver<'a> {
    pub(super) types: &'a TypeNamespace<'a>,
    pub(super) registry: &'a TypeRegistry<'a>,
    /// Records an oversized type met while resolving, for the inferer's next
    /// checkpoint; the resolver itself answers as if the type were `Error`.
    pub(crate) limits: &'a crate::type_size::TypeLimits,
}

/// A single way a class fails to satisfy an interface it declares it `implements`.
pub(super) enum ImplementsFailure {
    /// The interface requires `member`, but the class has no public member by
    /// that name (private members don't count toward the contract).
    Missing(String),
    /// `member` exists on the class but its type is not assignable to the
    /// interface's — wrong type or wrong arity. Signatures are pre-rendered
    /// (`Display`) for the diagnostic.
    Incompatible {
        member: String,
        expected: String,
        actual: String,
    },
    /// `member` has the right type but cannot be written (`readonly` field, or a
    /// getter with no setter) while the interface declares it settable. Reported
    /// apart from [`Incompatible`] because both sides render the same type there,
    /// naming no fix.
    NotWritable {
        member: String,
        ty: String,
    },
    NotReadable {
        member: String,
        ty: String,
    },
    /// `member` is optional on the class where the interface requires it. Same
    /// identical-types problem as [`NotWritable`].
    OptionalityMismatch {
        member: String,
        ty: String,
    },
}

impl<'a> TypeResolver<'a> {
    pub(super) fn lookup(
        &self,
        mangled: &MangledName,
        name: &str,
    ) -> Option<&'a crate::TypeSymbol> {
        self.registry
            .lookup(mangled)
            .or_else(|| self.types.lookup(name))
    }

    /// Full structural member form of an interface — methods (as `Function`
    /// types, method-level generics skipped) plus data properties, generic
    /// args substituted. Backs structural interface assignability.
    pub(super) fn interface_full_form(
        &self,
        mangled: &MangledName,
        name: &str,
        args: &[Type],
    ) -> Option<BTreeMap<String, ObjectField>> {
        let TypeKind::Interface {
            generics,
            methods,
            properties,
            ..
        } = &self.lookup(mangled, name)?.kind
        else {
            return None;
        };
        let bindings: BTreeMap<String, Type> =
            generics.iter().cloned().zip(args.iter().cloned()).collect();
        let mut out: BTreeMap<String, ObjectField> = BTreeMap::new();
        for (member, sig) in methods {
            if !sig.generics.is_empty() {
                continue;
            }
            out.insert(
                member.clone(),
                ObjectField {
                    ty: self.method_type(sig, &bindings),
                    optional: sig.optional,
                    readonly: true,
                    method: true,
                },
            );
        }
        for (member, sig) in properties {
            out.insert(
                member.clone(),
                ObjectField {
                    ty: substitute_or_record(&sig.ty, &bindings, self.limits),
                    optional: sig.optional,
                    readonly: sig.readonly,
                    method: false,
                },
            );
        }
        Some(out)
    }

    pub(super) fn sym_by_mangled(&self, mangled: &MangledName) -> Option<&'a crate::TypeSymbol> {
        self.registry
            .lookup(mangled)
            .or_else(|| self.types.lookup_by_mangled(mangled))
    }

    /// True when `actual` is `expected` or a subclass of it (nominal, via the
    /// `extends` chain). Cycle-guarded.
    pub(super) fn is_subclass(&self, actual: &MangledName, expected: &MangledName) -> bool {
        let mut cur = Some(actual.clone());
        let mut seen: Vec<MangledName> = Vec::new();
        while let Some(m) = cur {
            if &m == expected {
                return true;
            }
            if seen.contains(&m) {
                break;
            }
            seen.push(m.clone());
            cur = match self.sym_by_mangled(&m).map(|s| &s.kind) {
                Some(TypeKind::Class { extends, .. }) => extends.as_ref().map(|e| e.parent.clone()),
                _ => None,
            };
        }
        false
    }

    /// The type args at which `actual` (instantiated at `actual_args`) reaches
    /// ancestor `expected` through its `extends` chain — each hop substitutes
    /// the clause's args with the child's bindings. `None` when `expected`
    /// isn't an ancestor. Powers subclass→generic-parent assignability
    /// (`NumBox` extends `Box<number>` reaches `Box` at `[number]`, so
    /// `NumBox` is not a `Box<string>`).
    pub(super) fn class_args_at_ancestor(
        &self,
        actual: &MangledName,
        actual_args: &[Type],
        expected: &MangledName,
    ) -> Option<Vec<Type>> {
        super::classes::walk_class_chain_with(
            |m| self.sym_by_mangled(m).cloned(),
            self.limits,
            actual,
            actual_args,
            |sym, bindings| {
                if &sym.mangled_name != expected {
                    return ControlFlow::Continue(());
                }
                // The bindings at `expected` are its own generics zipped with
                // the args this chain reached it at.
                let TypeKind::Class { generics, .. } = &sym.kind else {
                    return ControlFlow::Break(None);
                };
                ControlFlow::Break(Some(
                    generics
                        .iter()
                        .map(|g| bindings.get(g).cloned().unwrap_or(Type::Unknown))
                        .collect(),
                ))
            },
        )
    }

    /// Public structural member form of a class — public methods (as `Function`
    /// types) and public fields, including inherited members (child wins on
    /// name). Backs `implements` conformance and class→interface assignability.
    /// Private members are excluded: they are not part of the external contract.
    /// `args` substitutes the class's own generics; leaving them raw would make
    /// members leak `TypeVar`s, which `assignable_rec` treats as wildcards.
    pub(super) fn class_full_form(
        &self,
        mangled: &MangledName,
        args: &[Type],
    ) -> Option<BTreeMap<String, ObjectField>> {
        let mut out: BTreeMap<String, ObjectField> = BTreeMap::new();
        super::classes::for_each_class_in_chain(
            |m| self.sym_by_mangled(m).cloned(),
            self.limits,
            mangled,
            args,
            |sym, bindings| {
                let TypeKind::Class {
                    fields,
                    methods,
                    method_visibility,
                    ..
                } = &sym.kind
                else {
                    return;
                };
                for (name, sig) in methods {
                    if !sig.generics.is_empty()
                        || method_visibility.get(name).copied() == Some(crate::Visibility::Private)
                    {
                        continue;
                    }
                    out.entry(name.clone()).or_insert(ObjectField {
                        ty: self.method_type(sig, bindings),
                        optional: sig.optional,
                        readonly: true,
                        method: true,
                    });
                }
                for (name, f) in fields {
                    if f.visibility == crate::Visibility::Private {
                        continue;
                    }
                    out.entry(name.clone()).or_insert(ObjectField {
                        ty: substitute_or_record(&f.ty, bindings, self.limits),
                        optional: f.optional,
                        readonly: f.readonly,
                        method: false,
                    });
                }
            },
        )?;
        Some(out)
    }

    /// A method's signature as a function type, with the class's arguments
    /// substituted.
    fn method_type(&self, sig: &MethodSig, bindings: &BTreeMap<String, Type>) -> Type {
        Type::Function {
            params: sig
                .params
                .iter()
                .map(|p| {
                    crate::ObjectField::widen_optional(
                        p.is_omittable(),
                        substitute_or_record(&p.ty, bindings, self.limits),
                    )
                })
                .collect(),
            ret: Box::new(substitute_or_record(&sig.ret, bindings, self.limits)),
            predicate: None,
            has_rest: sig.params.last().is_some_and(|p| p.rest),
            optional: crate::package_declaration::optional_parameter_count(&sig.params),
        }
    }

    /// The private fields and methods of the class and its ancestors, the
    /// members [`class_full_form`](Self::class_full_form) leaves out, with the
    /// class's arguments substituted. Each is keyed by the class that declares
    /// it and its name. `None` means the `extends` chain broke.
    pub(super) fn class_private_members(
        &self,
        mangled: &MangledName,
        args: &[Type],
    ) -> Option<PrivateMembers> {
        let mut private = BTreeMap::new();
        super::classes::for_each_class_in_chain(
            |m| self.sym_by_mangled(m).cloned(),
            self.limits,
            mangled,
            args,
            |sym, bindings| {
                let TypeKind::Class {
                    fields,
                    methods,
                    method_visibility,
                    ..
                } = &sym.kind
                else {
                    return;
                };
                let mut insert = |name: &String, ty: Type| {
                    private.insert((sym.mangled_name.clone(), name.clone()), ty);
                };
                for (name, field) in fields {
                    if field.visibility == crate::Visibility::Private {
                        insert(name, substitute_or_record(&field.ty, bindings, self.limits));
                    }
                }
                for (name, sig) in methods {
                    if method_visibility.get(name).copied() == Some(crate::Visibility::Private) {
                        insert(name, self.method_type(sig, bindings));
                    }
                }
            },
        )?;
        Some(private)
    }

    /// Per-member conformance of a class against one interface it declares it
    /// `implements`. An empty result means the class satisfies the interface.
    /// This mirrors the class→interface arm of [`assignable_rec`] but reports
    /// *which* members fail (powering member-level diagnostics) instead of
    /// collapsing to a single boolean.
    /// `class_args` instantiates a generic class's own parameters. They must be
    /// opaque (`GenericParam`), not bare `TypeVar`s: `assignable_rec` treats a
    /// bare `TypeVar` as a wildcard, which would make every member of every
    /// generic class satisfy every interface silently.
    pub(super) fn implements_failures(
        &self,
        class_mangled: &MangledName,
        class_args: &[Type],
        iface_mangled: &MangledName,
        iface_name: &str,
        iface_args: &[Type],
    ) -> Vec<ImplementsFailure> {
        let (Some(class_form), Some(iface_form)) = (
            self.class_full_form(class_mangled, class_args),
            self.interface_full_form(iface_mangled, iface_name, iface_args),
        ) else {
            return Vec::new();
        };
        let mut failures = Vec::new();
        for (member, exp) in &iface_form {
            match class_form.get(member) {
                Some(act) => {
                    let mut seen = Vec::new();
                    // A setter's parameter is not a readable value. Check for a
                    // getter and required presence before comparing read types:
                    // optional reads add undefined even when declared types match.
                    //
                    // `readonly` is shallow, so the type check stays covariant. But a
                    // writable interface member requires writable class storage,
                    // excluding readonly fields and getter-only accessors. Real
                    // methods have callable payloads that a structural interface
                    // can replace, even though their structural form is readonly.
                    if self.class_property_is_write_only(class_mangled, class_args, member) {
                        failures.push(ImplementsFailure::NotReadable {
                            member: member.clone(),
                            ty: exp.ty.to_string(),
                        });
                    } else if !exp.optional && act.optional {
                        failures.push(ImplementsFailure::OptionalityMismatch {
                            member: member.clone(),
                            ty: exp.ty.to_string(),
                        });
                    } else if !self.class_member_assignable(
                        class_mangled,
                        class_args,
                        member,
                        &act.read_ty(),
                        &exp.read_ty(),
                        &mut seen,
                    ) {
                        failures.push(ImplementsFailure::Incompatible {
                            member: member.clone(),
                            expected: exp.ty.to_string(),
                            actual: act.ty.to_string(),
                        });
                    } else if !exp.readonly
                        && act.readonly
                        && !self.class_member_is_method(class_mangled, class_args, member)
                    {
                        failures.push(ImplementsFailure::NotWritable {
                            member: member.clone(),
                            ty: exp.ty.to_string(),
                        });
                    }
                }
                None if !exp.optional => failures.push(ImplementsFailure::Missing(member.clone())),
                None => {}
            }
        }
        failures
    }

    /// Structural calls resolve a class method dynamically, retaining its default
    /// metadata even when the target signature has fewer parameters.
    fn class_member_assignable(
        self,
        class: &MangledName,
        args: &[Type],
        member: &str,
        actual: &Type,
        expected: &Type,
        seen: &mut Vec<(Type, Type)>,
    ) -> bool {
        if assignable_rec(actual, expected, self, seen) {
            return true;
        }
        if let Type::Union(members) = expected.peel() {
            return members.iter().any(|expected| {
                self.class_member_assignable(class, args, member, actual, expected, seen)
            });
        }
        let (
            Type::Function {
                params,
                ret,
                predicate,
                optional: _,
                has_rest: false,
            },
            Type::Function {
                params: expected_params,
                has_rest: false,
                ..
            },
        ) = (actual.peel(), expected.peel())
        else {
            return false;
        };
        if expected_params.len() >= params.len() {
            return false;
        }
        let omittable = super::classes::walk_class_chain_with(
            |m| self.sym_by_mangled(m).cloned(),
            self.limits,
            class,
            args,
            |sym, _| {
                let TypeKind::Class {
                    methods, fields, ..
                } = &sym.kind
                else {
                    return ControlFlow::Continue(());
                };
                if fields.contains_key(member) {
                    return ControlFlow::Break(Some(false));
                }
                let Some(method) = methods.get(member) else {
                    return ControlFlow::Continue(());
                };
                ControlFlow::Break(Some(
                    method
                        .params
                        .iter()
                        .skip(expected_params.len())
                        .all(|param| param.default.is_some()),
                ))
            },
        )
        .unwrap_or(false);
        omittable
            && assignable_rec(
                &Type::Function {
                    params: params.iter().take(expected_params.len()).cloned().collect(),
                    ret: ret.clone(),
                    predicate: predicate.clone(),
                    has_rest: false,
                    optional: 0,
                },
                expected,
                self,
                seen,
            )
    }

    fn class_member_is_method(&self, mangled: &MangledName, args: &[Type], member: &str) -> bool {
        super::classes::walk_class_chain_with(
            |name| self.sym_by_mangled(name).cloned(),
            self.limits,
            mangled,
            args,
            |symbol, _| {
                let TypeKind::Class {
                    methods, fields, ..
                } = &symbol.kind
                else {
                    return ControlFlow::Continue(());
                };
                if fields.contains_key(member) {
                    return ControlFlow::Break(Some(false));
                }
                if methods.contains_key(member) {
                    return ControlFlow::Break(Some(true));
                }
                ControlFlow::Continue(())
            },
        )
        .unwrap_or(false)
    }

    fn class_property_is_write_only(
        &self,
        mangled: &MangledName,
        args: &[Type],
        member: &str,
    ) -> bool {
        let mut has_setter = false;
        let mut has_getter = false;
        super::classes::for_each_class_in_chain(
            |m| self.sym_by_mangled(m).cloned(),
            self.limits,
            mangled,
            args,
            |sym, _| {
                if let TypeKind::Class { accessors, .. } = &sym.kind {
                    for accessor in accessors.iter().filter(|a| a.name() == member) {
                        match accessor {
                            crate::AccessorSig::Getter { .. } => has_getter = true,
                            crate::AccessorSig::Setter { .. } => has_setter = true,
                        }
                    }
                }
            },
        );
        has_setter && !has_getter
    }

    /// Structural object shape of a **data-only** interface's properties, with
    /// generic args substituted. `None` if the name doesn't resolve to an
    /// interface, or if the interface declares methods — a method-bearing
    /// interface (`Map`, `Iterator`, …) is nominal: a plain object has no
    /// vtable, so neither structural assignability nor a runtime structural
    /// check can treat it as data. The single source of truth for
    /// object↔interface expansion shared by the assignability arms, the
    /// `as`-cast reducer
    /// ([`Inferer::interface_data_shape`](super::Inferer::interface_data_shape)
    /// delegates here), and JSON.parse target validation.
    pub(super) fn interface_data_shape(
        &self,
        mangled: &MangledName,
        name: &str,
        args: &[Type],
    ) -> Option<BTreeMap<String, ObjectField>> {
        let TypeKind::Interface {
            generics,
            properties,
            methods,
            ..
        } = &self.lookup(mangled, name)?.kind
        else {
            return None;
        };
        if !methods.is_empty() {
            return None;
        }
        let bindings: BTreeMap<String, Type> =
            generics.iter().cloned().zip(args.iter().cloned()).collect();
        Some(
            properties
                .iter()
                .map(|(field, sig)| {
                    (
                        field.clone(),
                        ObjectField {
                            ty: substitute_or_record(&sig.ty, &bindings, self.limits),
                            optional: sig.optional,
                            readonly: sig.readonly,
                            method: false,
                        },
                    )
                })
                .collect(),
        )
    }

    /// The names of an interface's methods.
    pub(super) fn interface_method_names(&self, mangled: &MangledName, name: &str) -> Vec<String> {
        match self.lookup(mangled, name).map(|symbol| &symbol.kind) {
            Some(TypeKind::Interface { methods, .. }) => methods.keys().cloned().collect(),
            _ => Vec::new(),
        }
    }

    /// The names of a class's methods, its ancestors' included.
    pub(super) fn class_method_names(&self, mangled: &MangledName, args: &[Type]) -> Vec<String> {
        let mut names = Vec::new();
        super::classes::for_each_class_in_chain(
            |m| self.sym_by_mangled(m).cloned(),
            self.limits,
            mangled,
            args,
            |sym, _| {
                if let TypeKind::Class { methods, .. } = &sym.kind {
                    names.extend(methods.keys().cloned());
                }
            },
        );
        names
    }

    /// True when `name` resolves to an interface that declares methods — the
    /// nominal-only interfaces `interface_data_shape` refuses to expand.
    pub(super) fn interface_has_methods(&self, mangled: &MangledName, name: &str) -> bool {
        match self.lookup(mangled, name).map(|symbol| &symbol.kind) {
            Some(TypeKind::Interface { methods, .. }) => !methods.is_empty(),
            _ => false,
        }
    }
}

/// Whether a function with a rest parameter, `actual`, accepts every argument
/// list of a fixed-arity function, `expected`, as in tsc: each argument at a
/// fixed position fits that parameter (`accepts(expected, actual)`), and each
/// past them fits the rest parameter's element type.
///
/// Unlike tsc, the two must differ in parameter count: a rest function's
/// closure has the same Wasm arity as a fixed function with as many
/// parameters, so a cast from an erased slot could not tell it needs its
/// arguments packed.
pub(crate) fn rest_function_accepts(
    actual: &[Type],
    expected: &[Type],
    mut accepts: impl FnMut(&Type, &Type) -> bool,
) -> bool {
    let Some((rest, fixed)) = actual.split_last() else {
        return false;
    };
    let Type::Array(element) = rest.peel() else {
        return false;
    };
    let Some(past_fixed) = expected.get(fixed.len()..) else {
        return false;
    };
    actual.len() != expected.len()
        && fixed
            .iter()
            .zip(expected)
            .all(|(declared, passed)| accepts(passed, declared))
        && past_fixed.iter().all(|passed| accepts(passed, element))
}

/// Whether a value of an enum, or of its member `actual`, is one of `expected`:
/// the whole enum, or that same member.
fn enum_member_fits<V>(
    actual: Option<&crate::types::EnumMember<V>>,
    expected: Option<&crate::types::EnumMember<V>>,
) -> bool {
    match (actual, expected) {
        (_, None) => true,
        (Some(actual), Some(expected)) => actual.name == expected.name,
        (None, Some(_)) => false,
    }
}

/// The members of the enum `actual` as member literal types, when the union
/// `expected` names one of them: only then can it need them all.
fn enum_as_member_union(
    actual: &Type,
    expected: &[Type],
    types: TypeResolver,
) -> Option<Vec<Type>> {
    let (Type::NumberEnum {
        mangled: enum_mangled,
        member: None,
        ..
    }
    | Type::StringEnum {
        mangled: enum_mangled,
        member: None,
        ..
    }) = actual.peel()
    else {
        return None;
    };
    let names_member = expected.iter().any(|m| match m.peel() {
        Type::NumberEnum {
            mangled,
            member: Some(_),
            ..
        }
        | Type::StringEnum {
            mangled,
            member: Some(_),
            ..
        } => mangled == enum_mangled,
        _ => false,
    });
    if !names_member {
        return None;
    }
    super::comparable::enum_member_types(actual.peel(), types)
}

pub(crate) fn assignable(actual: &Type, expected: &Type, types: TypeResolver) -> bool {
    // Coinductive assumption set for recursive-alias (`AliasRef`)
    // expansion: a pair re-encountered mid-proof is assumed to hold, so
    // comparing recursive types terminates.
    let mut seen: Vec<(Type, Type)> = Vec::new();
    assignable_rec(actual, expected, types, &mut seen)
}

fn assignable_rec(
    actual: &Type,
    expected: &Type,
    types: TypeResolver,
    seen: &mut Vec<(Type, Type)>,
) -> bool {
    // Structures that each fit the type limits can still take exponentially
    // many comparisons, so each one draws on the phase's work allowance. Once a
    // limit is recorded the answer no longer matters: compilation fails.
    if !types.limits.spend_work(1) {
        return false;
    }
    if let Type::Refined { original, ty } = expected.without_aliases() {
        return assignable_rec(actual, original, types, seen)
            && assignable_rec(actual, ty, types, seen);
    }
    if let Type::Refined { original, ty } = actual.without_aliases() {
        return assignable_rec(original, expected, types, seen)
            || assignable_rec(ty, expected, types, seen);
    }
    if same_alias_instance(actual, expected) {
        return true;
    }
    // Keep named pairs on the active proof path: expanding a back-edge can
    // change its inline spelling without changing the alias instantiation.
    if seen
        .iter()
        .any(|(a, e)| same_alias_instance(actual, a) && same_alias_instance(expected, e))
    {
        return true;
    }
    // Distribute unions, including named unions, before expanding back-edges.
    // Non-union members retain their names and can reuse the active comparison.
    if let Type::Union(ms) = actual.peel() {
        return ms.iter().all(|m| assignable_rec(m, expected, types, seen));
    }
    if let Type::Union(ms) = expected.peel() {
        // An enum is the union of its members, so `E` fits `E.A | E.B` when
        // that names every member.
        if let Some(members) = enum_as_member_union(actual, ms, types) {
            return members
                .iter()
                .all(|member| ms.iter().any(|m| assignable_rec(member, m, types, seen)));
        }
        return ms.iter().any(|m| assignable_rec(actual, m, types, seen));
    }
    if drops_readonly(actual, expected) {
        return false;
    }
    if matches!(actual, Type::Alias { .. }) || matches!(expected, Type::Alias { .. }) {
        let pair = (actual.clone(), expected.clone());
        seen.push(pair);
        let result = assignable_rec(actual.peel(), expected.peel(), types, seen);
        seen.pop();
        return result;
    }
    let actual = actual.peel();
    let expected = expected.peel();
    if matches!(actual, Type::Error) || matches!(expected, Type::Error) {
        return true;
    }
    if matches!(actual, Type::Never) {
        return true;
    }
    if matches!(
        (actual, expected),
        (Type::Undefined | Type::Void, Type::Void)
    ) {
        return true;
    }
    if matches!(expected, Type::TypeVar(_)) || matches!(actual, Type::TypeVar(_)) {
        return true;
    }
    // Placed after TypeVar so generic fns can receive `unknown`; the wildcard binds T→Unknown, post-substitution sees identity.
    if matches!(expected, Type::Unknown) {
        return true;
    }
    if matches!(actual, Type::Unknown) {
        return false;
    }
    // A recursion back-edge on either side is expanded by name and
    // compared structurally; the `seen` set breaks the cycle. Two
    // back-edges to the same alias with assignable args short-circuit.
    if matches!(actual, Type::AliasRef { .. }) || matches!(expected, Type::AliasRef { .. }) {
        if let (
            Type::AliasRef {
                mangled: ma,
                args: aa,
                ..
            },
            Type::AliasRef {
                mangled: me,
                args: ae,
                ..
            },
        ) = (actual, expected)
            && ma == me
            && aa.len() == ae.len()
            && aa
                .iter()
                .zip(ae.iter())
                .all(|(a, e)| assignable_rec(a, e, types, seen))
        {
            return true;
        }
        let key = (actual.clone(), expected.clone());
        if seen.iter().any(|(a, e)| a == &key.0 && e == &key.1) {
            return true;
        }
        // Different instantiations of a type-growing alias may never repeat
        // a pair. Bound that proof rather than overflowing the compiler stack.
        let recursive_expansions = seen
            .iter()
            .filter(|(actual, expected)| {
                matches!(actual, Type::AliasRef { .. }) || matches!(expected, Type::AliasRef { .. })
            })
            .count();
        if recursive_expansions >= 32 {
            return false;
        }
        seen.push(key);
        let a = expand_alias_ref(actual, types);
        let e = expand_alias_ref(expected, types);
        let result = assignable_rec(&a, &e, types, seen);
        seen.pop();
        return result;
    }
    match (actual, expected) {
        (Type::GenericParam { id: a, .. }, Type::GenericParam { id: b, .. }) => a == b,
        (Type::GenericParam { .. }, _) | (_, Type::GenericParam { .. }) => false,
        // Explicit before the `==` fallback, which would reject `StringLiteral("foo") <: String`.
        (Type::StringLiteral(a), Type::StringLiteral(b)) => a == b,
        (Type::StringLiteral(_) | Type::StringEnum { .. }, Type::String) => true,
        (Type::String, Type::StringLiteral(_)) => false,
        (Type::NumberLiteral(a), Type::NumberLiteral(b)) => a == b,
        (Type::NumberLiteral(_) | Type::NumberEnum { .. }, Type::Number) => true,
        (Type::Number, Type::NumberLiteral(_)) => false,
        (Type::BigIntLiteral(a), Type::BigIntLiteral(b)) => a == b,
        (Type::BigIntLiteral(_), Type::BigInt) => true,
        (Type::BigInt, Type::BigIntLiteral(_)) => false,
        (Type::BooleanLiteral(a), Type::BooleanLiteral(b)) => a == b,
        (Type::BooleanLiteral(_), Type::Boolean) => true,
        (Type::Boolean, Type::BooleanLiteral(_)) => false,
        // An enum's identity is its declaration: an aliased import
        // (`import { E as G }`) names the same enum under another `name`. An
        // enum member literal type `E.A` is its enum's and its value's.
        (
            Type::NumberEnum {
                mangled: ma,
                member: am,
                ..
            },
            Type::NumberEnum {
                mangled: me,
                member: em,
                ..
            },
        ) => ma == me && enum_member_fits(am.as_ref(), em.as_ref()),
        (
            Type::StringEnum {
                mangled: ma,
                member: am,
                ..
            },
            Type::StringEnum {
                mangled: me,
                member: em,
                ..
            },
        ) => ma == me && enum_member_fits(am.as_ref(), em.as_ref()),
        (
            Type::NumberEnum {
                member: Some(member),
                ..
            },
            Type::NumberLiteral(value),
        ) => member.value == *value,
        (
            Type::StringEnum {
                member: Some(member),
                ..
            },
            Type::StringLiteral(value),
        ) => member.value == *value,
        // TypeScript lets a number literal stand for the numeric member that
        // holds its value, but no string literal for a string member.
        (
            Type::NumberLiteral(value),
            Type::NumberEnum {
                member: Some(member),
                ..
            },
        ) => member.value == *value,
        (Type::Array(ae), Type::Array(ee)) => assignable_rec(ae, ee, types, seen),
        (Type::Tuple(aa), Type::Tuple(ae)) => {
            aa.required_len() >= ae.required_len()
                && aa.len() <= ae.len()
                && aa
                    .iter()
                    .zip(ae.iter())
                    .all(|(a, e)| assignable_rec(a, e, types, seen))
        }
        (Type::Tuple(aa), Type::Array(ee)) => aa.iter().all(|a| assignable_rec(a, ee, types, seen)),
        (
            Type::InterfaceRef {
                mangled: ma,
                args: aa,
                name: na,
                ..
            },
            Type::InterfaceRef {
                mangled: me,
                args: ae,
                ..
            },
        ) => {
            // Measured variances decide first, as in tsc: comparing the members
            // of a recursive interface instead would expand ever larger
            // instantiations (`I0<I1<T, U>, T>`). Arguments that fail only
            // where the members may still accept them fall back to plain
            // covariance, then to the members.
            if ma == me {
                match args_relate_at_variances(ma, na, aa, ae, types, seen) {
                    Some(ArgsRelation::Related) => return true,
                    Some(ArgsRelation::Unrelated) => return false,
                    Some(ArgsRelation::MembersDecide) | None => {}
                }
                if args_relate_covariantly(aa, ae, types, seen) {
                    return true;
                }
            }
            satisfies_structurally(actual, expected, types, seen)
        }
        // Classes are nominal: assignable only up the `extends` chain. Generic
        // classes additionally compare args pairwise, at each type parameter's
        // variance (mutable fields count as covariant, as in TypeScript).
        (
            Type::ClassRef {
                mangled: ma,
                args: aa,
                ..
            },
            Type::ClassRef {
                mangled: me,
                name: ne,
                args: ae,
                ..
            },
        ) => {
            // A subclass relates through the args its extends chain applies to
            // the ancestor: `NumBox extends Box<number>` reaches `Box` at
            // `[number]`, so it satisfies `Box<number>` but not `Box<string>`.
            let actual_at_expected = if ma == me {
                Some(aa.clone())
            } else {
                types.class_args_at_ancestor(ma, aa, me)
            };
            match actual_at_expected {
                // Classes are nominal and have no member fallback, so arguments
                // the members might accept still leave them unrelated.
                Some(at) => match args_relate_at_variances(me, ne, &at, ae, types, seen) {
                    Some(relation) => relation == ArgsRelation::Related,
                    None => args_relate_covariantly(&at, ae, types, seen),
                },
                None => false,
            }
        }
        // A class instance satisfies an interface structurally (its `implements`
        // contract and ordinary duck typing) through its public member shape.
        (
            Type::ClassRef {
                mangled: ma,
                args: aa,
                ..
            },
            Type::InterfaceRef {
                mangled: me,
                name: ne,
                args: ae,
                ..
            },
        ) => {
            let (Some(class_form), Some(iface_form)) = (
                types.class_full_form(ma, aa),
                types.interface_full_form(me, ne, ae),
            ) else {
                return false;
            };
            if weak_type_rejects(&class_form, &iface_form) {
                return false;
            }
            iface_form
                .iter()
                .all(|(member, exp)| match class_form.get(member) {
                    Some(act) => {
                        !types.class_property_is_write_only(ma, aa, member)
                            && (exp.optional || !act.optional)
                            && types.class_member_assignable(
                                ma,
                                aa,
                                member,
                                &act.read_ty(),
                                &exp.read_ty(),
                                seen,
                            )
                    }
                    None => exp.optional,
                })
        }
        (Type::ClassRef { mangled, args, .. }, Type::Object { fields, index }) => {
            let Some(class_form) = types.class_full_form(mangled, args) else {
                return false;
            };
            if index.as_ref().is_some_and(|i| {
                class_form
                    .values()
                    .any(|f| !assignable_rec(&f.ty, &i.value, types, seen))
            }) {
                return false;
            }
            if weak_type_rejects(&class_form, fields) {
                return false;
            }
            fields
                .iter()
                .all(|(member, expected)| match class_form.get(member) {
                    Some(actual) => {
                        !types.class_property_is_write_only(mangled, args, member)
                            && (expected.optional || !actual.optional)
                            && types.class_member_assignable(
                                mangled,
                                args,
                                member,
                                &actual.read_ty(),
                                &expected.read_ty(),
                                seen,
                            )
                    }
                    None => expected.optional,
                })
        }
        // An interface value is not nominally a class.
        (Type::InterfaceRef { .. }, Type::ClassRef { .. }) => false,
        // Non-interface values (strings, arrays, …) satisfy an interface
        // through their own interface form — `string` is `Iterable<string>`
        // because `String` declares `iterator()`.
        (_, Type::InterfaceRef { .. }) if satisfies_structurally(actual, expected, types, seen) => {
            true
        }
        (
            Type::Function {
                params: pa,
                ret: ra,
                predicate: predicate_a,
                has_rest: rest_a,
                optional: optional_a,
            },
            Type::Function {
                params: pe,
                ret: re,
                predicate: predicate_e,
                has_rest: rest_e,
                optional: _,
            },
        ) => {
            // A rest function can't stand for one whose own rest arguments
            // it would have to unpack.
            if *rest_e && !rest_a {
                return false;
            }
            // Predicate→non-predicate: ok (info dropped). Non-predicate→predicate: rejected (can't manufacture narrowing metadata).
            let predicate_ok = match (predicate_a, predicate_e) {
                (Some(a), Some(e)) => {
                    a.parameter_index == e.parameter_index
                        && assignable_rec(&a.asserted_type, &e.asserted_type, types, seen)
                }
                (Some(_), None) => true,
                (None, Some(_)) => false,
                (None, None) => true,
            };
            let params_ok = if *rest_a && !rest_e {
                rest_function_accepts(pa, pe, |e, a| assignable_rec(e, a, types, seen))
            } else {
                // Trailing optional parameters may go unpassed by the caller.
                let required = if *rest_a {
                    pa.len()
                } else {
                    pa.len().saturating_sub(*optional_a)
                };
                Type::function_arity_fits(required, pe.len(), *rest_a)
                    && pa.iter().zip(pe.iter()).enumerate().all(|(i, (a, e))| {
                        let both_rest = *rest_a && i + 1 == pa.len() && i + 1 == pe.len();
                        if both_rest {
                            assignable_rec(
                                e.rest_array_ignoring_readonly(),
                                a.rest_array_ignoring_readonly(),
                                types,
                                seen,
                            )
                        } else {
                            assignable_rec(e, a, types, seen)
                        }
                    })
            };
            predicate_ok
                && params_ok
                && (re.is_void()
                    || (ra.is_void() && matches!(re.peel(), Type::TypeVar(_)))
                    || assignable_rec(ra, re, types, seen))
        }
        // `readonly` is shallow (TS-faithful): it gates direct writes, not
        // assignability. Object width subtyping stays covariant per field.
        (
            Type::Object {
                fields: a_fields,
                index: a_index,
            },
            Type::Object {
                fields: e_fields,
                index: e_index,
            },
        ) => {
            if let Some(expected_index) = e_index {
                if !a_fields
                    .values()
                    .all(|f| assignable_rec(&f.ty, &expected_index.value, types, seen))
                {
                    return false;
                }
                if let Some(actual_index) = a_index
                    && !assignable_rec(&actual_index.value, &expected_index.value, types, seen)
                {
                    return false;
                }
            }
            if e_index.is_none() && weak_type_rejects(a_fields, e_fields) {
                return false;
            }
            // `{a: T|null}` into `{a?: T}` is still rejected — `assignable(T|null, T)` fails.
            e_fields.iter().all(|(k, e_field)| match a_fields.get(k) {
                Some(a_field) => {
                    if a_field.optional && !e_field.optional {
                        return false;
                    }
                    assignable_rec(&a_field.read_ty(), &e_field.read_ty(), types, seen)
                }
                None => e_field.optional,
            })
        }
        // Structural compatibility for *data-only* interfaces, both directions:
        // expand the interface to its property shape and reuse the `(Object,
        // Object)` width rule. Method-bearing interfaces expand to `None` and
        // fall through to rejection — a plain object has no vtable, so a later
        // method call would trap. The `seen` guard breaks recursive interfaces
        // coinductively (mirrors the `AliasRef` arm above).
        (Type::Object { .. }, Type::InterfaceRef { .. })
        | (Type::InterfaceRef { .. }, Type::Object { .. }) => {
            let expanded_pair = if matches!(expected, Type::InterfaceRef { .. }) {
                expand_interface_data_shape(expected, types).map(|o| (actual.clone(), o))
            } else {
                expand_interface_data_shape(actual, types).map(|o| (o, expected.clone()))
            };
            let Some((a, e)) = expanded_pair else {
                return false;
            };
            let key = (actual.clone(), expected.clone());
            if seen.iter().any(|(sa, se)| sa == &key.0 && se == &key.1) {
                return true;
            }
            seen.push(key);
            let result = assignable_rec(&a, &e, types, seen);
            seen.pop();
            result
        }
        _ => actual == expected,
    }
}

/// How one instantiation's type arguments relate to another's at the measured
/// variances.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ArgsRelation {
    Related,
    Unrelated,
    /// Every failing argument may still fit through the members: a `void`
    /// at a covariant parameter (tsc's `hasCovariantVoidArgument`, so a
    /// `Task<number>` serves as a `Task<void>`), or a type parameter still
    /// being inferred (`Sink<T>` for a `Sink<void>`).
    MembersDecide,
}

/// How one instantiation's type arguments relate to another's, for the generic
/// class or interface `mangled`, at each parameter's variance. `None` when the
/// variances couldn't be measured in full.
fn args_relate_at_variances(
    mangled: &MangledName,
    name: &str,
    actual_args: &[Type],
    expected_args: &[Type],
    types: TypeResolver,
    seen: &mut Vec<(Type, Type)>,
) -> Option<ArgsRelation> {
    if actual_args.len() != expected_args.len() {
        return Some(ArgsRelation::Unrelated);
    }
    if actual_args == expected_args {
        return Some(ArgsRelation::Related);
    }
    let variances = types.settled_variances(mangled, name, actual_args.len())?;
    let mut relation = ArgsRelation::Related;
    for ((actual, expected), variance) in actual_args.iter().zip(expected_args).zip(variances) {
        if variance.relates(actual, expected, |a, e| assignable_rec(a, e, types, seen)) {
            continue;
        }
        let members_may_accept = (variance == Variance::Covariant
            && matches!(expected, Type::Void))
            || super::expr::type_contains_type_var(expected);
        if !members_may_accept {
            return Some(ArgsRelation::Unrelated);
        }
        relation = ArgsRelation::MembersDecide;
    }
    Some(relation)
}

/// Whether each type argument is assignable to the one at its position.
fn args_relate_covariantly(
    actual_args: &[Type],
    expected_args: &[Type],
    types: TypeResolver,
    seen: &mut Vec<(Type, Type)>,
) -> bool {
    actual_args.len() == expected_args.len()
        && actual_args
            .iter()
            .zip(expected_args)
            .all(|(actual, expected)| assignable_rec(actual, expected, types, seen))
}

/// Whether `actual` is a `readonly` array or tuple and `expected` a mutable one.
/// The element types still decide assignability everywhere else: `readonly` is
/// shallow and otherwise covariant, like the array it wraps.
pub(crate) fn drops_readonly(actual: &Type, expected: &Type) -> bool {
    actual.is_readonly_array()
        && !expected.is_readonly_array()
        && matches!(expected.peel(), Type::Array(_) | Type::Tuple(_))
}

fn same_alias_instance(left: &Type, right: &Type) -> bool {
    if left == right {
        return true;
    }
    let (Some((left_name, left_args)), Some((right_name, right_args))) =
        (alias_identity(left), alias_identity(right))
    else {
        return false;
    };
    left_name == right_name
        && left_args.len() == right_args.len()
        && left_args
            .iter()
            .zip(right_args)
            .all(|(left, right)| same_alias_instance(left, right))
}

pub(super) fn alias_identity(ty: &Type) -> Option<(&MangledName, &[Type])> {
    match ty {
        Type::Alias { mangled, args, .. } | Type::AliasRef { mangled, args, .. } => {
            Some((mangled, args))
        }
        _ => None,
    }
}

/// A class's private members, keyed by the class that declares each and its
/// name, as [`TypeResolver::class_private_members`] returns them.
pub(super) type PrivateMembers = BTreeMap<(MangledName, String), Type>;

/// Expand a recursion back-edge to the alias's underlying body (args
/// substituted), by name. Returns the input unchanged for non-`AliasRef`
/// or an unresolvable name.
pub(crate) fn expand_alias_ref(ty: &Type, types: TypeResolver) -> Type {
    let Type::AliasRef {
        mangled,
        name,
        args,
        ..
    } = ty
    else {
        return ty.clone();
    };
    let Some(sym) = types.lookup(mangled, name) else {
        return ty.clone();
    };
    let TypeKind::Alias {
        generics, ty: body, ..
    } = &sym.kind
    else {
        return ty.clone();
    };
    if generics.is_empty() {
        body.clone()
    } else {
        let sub = crate::typechecker::type_param_substitution::TypeParamSubstitution::from_pairs(
            generics, args,
        );
        sub.apply_or_record(body, types.limits)
    }
}

/// TS-style structural interface satisfaction: every member the expected
/// interface declares exists on the actual type's interface form (via
/// [`Type::interface_routing`]) with an assignable type. The nominal fast
/// path stays first; this is the fallback that makes interfaces structural.
fn satisfies_structurally(
    actual: &Type,
    expected: &Type,
    types: TypeResolver,
    seen: &mut Vec<(Type, Type)>,
) -> bool {
    let key = (actual.clone(), expected.clone());
    if seen.contains(&key) {
        // Coinductive: an in-progress pair counts as satisfied.
        return true;
    }
    if expanding_interface_pair(actual, expected, seen) {
        return true;
    }
    let Some((me, _pe, ne, ae)) = expected.interface_routing() else {
        return false;
    };
    let Some((ma, _pa, na, aa)) = actual.interface_routing() else {
        return false;
    };
    let Some(expected_form) = types.interface_full_form(&me, ne, &ae) else {
        return false;
    };
    let Some(actual_form) = types.interface_full_form(&ma, na, &aa) else {
        return false;
    };
    if weak_type_rejects(&actual_form, &expected_form) {
        return false;
    }
    if let Some(index) = types.index_signature(expected) {
        if !matches!(
            actual.peel(),
            Type::Object { .. } | Type::ClassRef { .. } | Type::InterfaceRef { .. }
        ) {
            return false;
        }
        seen.push(key.clone());
        let compatible = actual_form
            .values()
            .all(|field| assignable_rec(&field.ty, &index.value, types, seen))
            && types
                .index_signature(actual)
                .is_none_or(|actual| assignable_rec(&actual.value, &index.value, types, seen));
        seen.pop();
        if !compatible {
            return false;
        }
    }
    seen.push(key);
    let ok = expected_form
        .iter()
        .all(|(member, exp)| match actual_form.get(member) {
            Some(act) => {
                (exp.optional || !act.optional)
                    && assignable_rec(&act.read_ty(), &exp.read_ty(), types, seen)
            }
            None => exp.optional,
        });
    seen.pop();
    ok
}

/// Expansive recursion produces fresh instantiations forever, so exact-pair
/// coinduction cannot terminate it. Require growth on at least one side of the same
/// named comparison; explicitly nested, shrinking arguments still get checked.
fn expanding_interface_pair(actual: &Type, expected: &Type, seen: &[(Type, Type)]) -> bool {
    let (
        Type::InterfaceRef {
            mangled: actual_name,
            args: actual_args,
            ..
        },
        Type::InterfaceRef {
            mangled: expected_name,
            args: expected_args,
            ..
        },
    ) = (actual, expected)
    else {
        return false;
    };
    let mut previous = (
        type_argument_depth(actual_args),
        type_argument_depth(expected_args),
    );
    let mut expansions = 0;
    for (actual, expected) in seen.iter().rev() {
        let (
            Type::InterfaceRef {
                mangled: ancestor_actual_name,
                args: ancestor_actual_args,
                ..
            },
            Type::InterfaceRef {
                mangled: ancestor_expected_name,
                args: ancestor_expected_args,
                ..
            },
        ) = (actual, expected)
        else {
            continue;
        };
        if ancestor_actual_name != actual_name || ancestor_expected_name != expected_name {
            continue;
        }
        let depth = (
            type_argument_depth(ancestor_actual_args),
            type_argument_depth(ancestor_expected_args),
        );
        if depth.0 > previous.0 || depth.1 > previous.1 || depth == previous {
            continue;
        }
        expansions += 1;
        if expansions == 3 {
            return true;
        }
        previous = depth;
    }
    false
}

fn type_argument_depth(args: &[Type]) -> usize {
    args.iter().map(type_nesting_depth).max().unwrap_or(0)
}

fn type_nesting_depth(ty: &Type) -> usize {
    1 + match ty {
        Type::Array(element) | Type::Readonly(element) => type_nesting_depth(element),
        Type::InterfaceRef { args, .. }
        | Type::ClassRef { args, .. }
        | Type::AliasRef { args, .. }
        | Type::Alias { args, .. } => type_argument_depth(args),
        Type::Tuple(elements) => type_argument_depth(elements),
        Type::Union(elements) => type_argument_depth(elements),
        Type::Function { params, ret, .. } => {
            type_argument_depth(params).max(type_nesting_depth(ret))
        }
        Type::Refined { original, ty } => type_nesting_depth(original).max(type_nesting_depth(ty)),
        Type::Object { fields, index } => fields
            .values()
            .map(|field| type_nesting_depth(&field.ty))
            .chain(index.iter().map(|i| type_nesting_depth(&i.value)))
            .max()
            .unwrap_or(0),
        _ => 0,
    }
}

/// TS weak-type rule: an all-optional target is vacuously satisfied by
/// member-by-member checks, which would let `number` satisfy `{ years?: number }`
/// through its `Number` interface form (and codegen would then put an f64 in
/// a ref slot — invalid Wasm), or let `{ p: number }` stand for `{ q?: string }`
/// while it holds a `q` of another type. Require at least one member in common.
/// An empty actual form stays assignable, mirroring TS's `{}`-source exemption.
pub(super) fn weak_type_rejects(
    actual_form: &BTreeMap<String, ObjectField>,
    expected_form: &BTreeMap<String, ObjectField>,
) -> bool {
    !expected_form.is_empty()
        && expected_form.values().all(|f| f.optional)
        && !actual_form.is_empty()
        && !expected_form.keys().any(|k| actual_form.contains_key(k))
}

/// Expand a **data-only** (method-free) `InterfaceRef` to the structural
/// `Type::Object` of its properties. Returns `None` for non-interfaces,
/// method-bearing interfaces, or unresolvable names — callers treat `None` as
/// "not structurally assignable".
pub(crate) fn expand_interface_data_shape(ty: &Type, types: TypeResolver) -> Option<Type> {
    let Type::InterfaceRef {
        mangled,
        name,
        args,
        ..
    } = ty
    else {
        return None;
    };
    Some(Type::Object {
        index: types.index_signature(ty),
        fields: types.interface_data_shape(mangled, name, args)?,
    })
}

/// `null` and `undefined` are excluded: they narrow through `predicate_envs_eq_nullish`.
pub(super) fn literal_value_of(kind: &crate::TypedExprKind) -> Option<narrowing::LiteralValue> {
    use crate::TypedExprKind;
    match kind {
        TypedExprKind::Number(n) => Some(narrowing::LiteralValue::Number(
            crate::types::LiteralF64(*n),
        )),
        TypedExprKind::String(s) => Some(narrowing::LiteralValue::String(s.clone())),
        TypedExprKind::Boolean(b) => Some(narrowing::LiteralValue::Boolean(*b)),
        TypedExprKind::BigInt(digits) => match crate::types::bigint_literal_type(digits) {
            Type::BigIntLiteral(canonical) => Some(narrowing::LiteralValue::BigInt(canonical)),
            _ => None,
        },
        _ => None,
    }
}

pub(super) fn literal_to_type(lit: &narrowing::LiteralValue) -> Type {
    match lit {
        narrowing::LiteralValue::Number(n) => Type::NumberLiteral(*n),
        narrowing::LiteralValue::String(s) => Type::StringLiteral(s.clone()),
        narrowing::LiteralValue::Boolean(b) => Type::BooleanLiteral(*b),
        narrowing::LiteralValue::BigInt(digits) => Type::BigIntLiteral(digits.clone()),
        narrowing::LiteralValue::Null => Type::Null,
        narrowing::LiteralValue::Undefined => Type::Undefined,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// 2-arg shim so the existing tests read unchanged. None exercise
    /// recursive aliases, so empty tables are sufficient; it shadows the
    /// glob-imported 3-arg `assignable` for unqualified calls in this module.
    fn assignable(actual: &Type, expected: &Type) -> bool {
        let types = TypeNamespace::new();
        let registry = TypeRegistry::new();
        let limits = crate::type_size::TypeLimits::default();
        super::assignable(
            actual,
            expected,
            TypeResolver {
                types: &types,
                registry: &registry,
                limits: &limits,
            },
        )
    }

    fn fn_ty(params: Vec<Type>, ret: Type) -> Type {
        Type::Function {
            params,
            ret: Box::new(ret),
            predicate: None,
            has_rest: false,
            optional: 0,
        }
    }

    #[test]
    fn undefined_is_distinct_from_null_and_assignable_to_void() {
        assert!(assignable(&Type::Undefined, &Type::Void));
        assert!(assignable(&Type::Void, &Type::Unknown));
        assert!(!assignable(&Type::Void, &Type::Undefined));
        assert!(!assignable(&Type::Null, &Type::Undefined));
        assert!(!assignable(&Type::Undefined, &Type::Null));
    }

    #[test]
    fn optional_tuple_accepts_omission_but_cannot_satisfy_required_position() {
        let optional = Type::Tuple(crate::types::TupleType {
            elements: vec![
                Type::Number,
                Type::union(vec![Type::String, Type::Undefined]),
            ],
            optional: 1,
        });
        let short = Type::Tuple(vec![Type::Number].into());
        let full = Type::Tuple(vec![Type::Number, Type::String].into());
        assert!(assignable(&short, &optional));
        assert!(assignable(&full, &optional));
        assert!(!assignable(&optional, &short));
        assert!(!assignable(&optional, &full));
    }

    #[test]
    fn optional_function_parameter_can_be_omitted_by_target_callers() {
        let optional = Type::Function {
            params: vec![Type::union(vec![Type::String, Type::Undefined])],
            ret: Box::new(Type::Void),
            predicate: None,
            has_rest: false,
            optional: 1,
        };
        let no_args = fn_ty(vec![], Type::Void);
        let required = fn_ty(vec![Type::String], Type::Void);
        assert!(assignable(&optional, &no_args));
        assert!(assignable(&optional, &required));
        assert!(!assignable(&required, &optional));
        let required_union = fn_ty(
            vec![Type::union(vec![Type::String, Type::Undefined])],
            Type::Void,
        );
        assert!(assignable(&required_union, &optional));
        assert!(!assignable(&required_union, &no_args));
    }

    #[test]
    fn optional_object_field_accepts_explicit_undefined() {
        let object = |field| Type::Object {
            fields: [("value".to_string(), field)].into_iter().collect(),
            index: None,
        };
        let optional = object(ObjectField::optional(Type::String));
        assert!(assignable(
            &object(ObjectField::required(Type::Undefined)),
            &optional
        ));
        assert!(!assignable(
            &object(ObjectField::required(Type::Null)),
            &optional
        ));
    }

    #[test]
    fn assignable_function_exact_match() {
        let a = fn_ty(vec![Type::Number], Type::String);
        let b = fn_ty(vec![Type::Number], Type::String);
        assert!(assignable(&a, &b));
        assert!(assignable(&b, &a));
    }

    #[test]
    fn assignable_function_may_take_fewer_params_but_not_more() {
        let one = fn_ty(vec![Type::Number], Type::Void);
        let two = fn_ty(vec![Type::Number, Type::Number], Type::Void);
        assert!(assignable(&one, &two));
        assert!(!assignable(&two, &one));
    }

    #[test]
    fn assignable_function_return_mismatch() {
        let a = fn_ty(vec![Type::Number], Type::Number);
        let b = fn_ty(vec![Type::Number], Type::String);
        assert!(!assignable(&a, &b));
        assert!(!assignable(&b, &a));
    }

    #[test]
    fn assignable_function_param_mismatch() {
        let a = fn_ty(vec![Type::Number], Type::Void);
        let b = fn_ty(vec![Type::String], Type::Void);
        assert!(!assignable(&a, &b));
        assert!(!assignable(&b, &a));
    }

    #[test]
    fn assignable_function_error_param_is_bidirectional() {
        // Cascading diagnostics don't pile up when a param failed to resolve.
        let a = fn_ty(vec![Type::Error], Type::Void);
        let b = fn_ty(vec![Type::Number], Type::Void);
        assert!(assignable(&a, &b));
        assert!(assignable(&b, &a));
    }

    #[test]
    fn assignable_function_error_return_is_bidirectional() {
        let a = fn_ty(vec![Type::Number], Type::Error);
        let b = fn_ty(vec![Type::Number], Type::String);
        assert!(assignable(&a, &b));
        assert!(assignable(&b, &a));
    }

    #[test]
    fn assignable_function_param_contravariance_uses_assignable() {
        let actual = fn_ty(vec![Type::Number], Type::Void);
        let expected = fn_ty(vec![Type::Error], Type::Void);
        assert!(assignable(&actual, &expected));
        assert!(assignable(&expected, &actual));
    }

    #[test]
    fn assignable_function_return_covariance_uses_assignable() {
        let actual = fn_ty(vec![Type::Number], Type::Error);
        let expected = fn_ty(vec![Type::Number], Type::String);
        assert!(assignable(&actual, &expected));
        assert!(assignable(&expected, &actual));
    }

    #[test]
    fn assignable_nested_function_recurses() {
        let inner = fn_ty(vec![Type::Number], Type::Number);
        let outer = fn_ty(vec![Type::Number], inner.clone());
        assert!(assignable(&outer, &outer));
        let inner_bad = fn_ty(vec![Type::Number], Type::String);
        let outer_bad = fn_ty(vec![Type::Number], inner_bad);
        assert!(!assignable(&outer, &outer_bad));
        assert!(!assignable(&outer_bad, &outer));
    }

    #[test]
    fn assignable_zero_arity_function() {
        let a = fn_ty(vec![], Type::Number);
        let b = fn_ty(vec![], Type::Number);
        assert!(assignable(&a, &b));
    }

    #[test]
    fn assignable_function_vs_non_function_rejected() {
        let a = fn_ty(vec![Type::Number], Type::Void);
        let b = Type::Number;
        assert!(!assignable(&a, &b));
        assert!(!assignable(&b, &a));
    }

    #[test]
    fn assignable_non_function_still_structural_eq() {
        assert!(assignable(&Type::Number, &Type::Number));
        assert!(!assignable(&Type::Number, &Type::String));
        assert!(assignable(&Type::Error, &Type::String));
        assert!(assignable(&Type::String, &Type::Error));
    }

    #[test]
    fn assignable_member_to_union() {
        let u = Type::union(vec![Type::Number, Type::String]);
        assert!(assignable(&Type::Number, &u));
        assert!(assignable(&Type::String, &u));
    }

    #[test]
    fn assignable_non_member_to_union_fails() {
        let u = Type::union(vec![Type::Number, Type::String]);
        assert!(!assignable(&Type::Boolean, &u));
    }

    #[test]
    fn assignable_union_to_superset_union() {
        let actual = Type::union(vec![Type::Number, Type::String]);
        let expected = Type::union(vec![Type::Number, Type::String, Type::Boolean]);
        assert!(assignable(&actual, &expected));
    }

    #[test]
    fn assignable_union_to_subset_union_fails() {
        let actual = Type::union(vec![Type::Number, Type::String]);
        let expected = Type::union(vec![Type::Number, Type::Boolean]);
        assert!(!assignable(&actual, &expected));
    }

    #[test]
    fn assignable_union_to_member_fails() {
        let actual = Type::union(vec![Type::Number, Type::String]);
        assert!(!assignable(&actual, &Type::Number));
    }

    #[test]
    fn assignable_union_with_error_member_is_bidirectional() {
        let with_error = Type::union(vec![Type::Number, Type::Error]);
        assert_eq!(with_error, Type::Error);
        assert!(assignable(&with_error, &Type::Boolean));
        assert!(assignable(&Type::Boolean, &with_error));
    }

    #[test]
    fn assignable_array_of_union_recurses() {
        let union_elem = Type::union(vec![Type::Number, Type::String]);
        let union_arr = Type::Array(Box::new(union_elem));
        assert!(assignable(&union_arr, &union_arr));
        let narrow_arr = Type::Array(Box::new(Type::Number));
        assert!(assignable(&narrow_arr, &union_arr));
        assert!(!assignable(&union_arr, &narrow_arr));
    }

    #[test]
    fn readonly_accepts_mutable_but_not_the_reverse() {
        let array = |elem: Type| Type::Array(Box::new(elem));
        let readonly = |ty: Type| Type::Readonly(Box::new(ty));
        let numbers = array(Type::Number);
        let either = array(Type::union(vec![Type::Number, Type::String]));
        assert!(assignable(&numbers, &readonly(numbers.clone())));
        assert!(!assignable(&readonly(numbers.clone()), &numbers));
        // Covariant in the element, like the array it wraps.
        assert!(assignable(
            &readonly(numbers.clone()),
            &readonly(either.clone())
        ));
        assert!(!assignable(&readonly(either), &readonly(numbers.clone())));
        let pair = Type::Tuple(vec![Type::Number, Type::Number].into());
        assert!(assignable(&pair, &readonly(pair.clone())));
        assert!(!assignable(&readonly(pair.clone()), &pair));
        assert!(assignable(
            &readonly(pair.clone()),
            &readonly(numbers.clone())
        ));
        assert!(!assignable(&readonly(pair), &numbers));
        assert!(assignable(&readonly(numbers), &Type::Unknown));
    }

    #[test]
    fn assignable_anything_to_unknown() {
        for t in [
            Type::Number,
            Type::String,
            Type::Boolean,
            Type::Null,
            Type::Array(Box::new(Type::Number)),
            Type::Object {
                index: None,
                fields: std::collections::BTreeMap::new(),
            },
            Type::union(vec![Type::Number, Type::String]),
        ] {
            assert!(
                assignable(&t, &Type::Unknown),
                "{t} should be assignable to unknown",
            );
        }
    }

    #[test]
    fn assignable_unknown_to_concrete_fails() {
        for t in [
            Type::Number,
            Type::String,
            Type::Boolean,
            Type::Null,
            Type::Array(Box::new(Type::Number)),
        ] {
            assert!(
                !assignable(&Type::Unknown, &t),
                "unknown should NOT flow into {t}",
            );
        }
    }

    #[test]
    fn assignable_unknown_to_unknown_identity() {
        assert!(assignable(&Type::Unknown, &Type::Unknown));
    }

    #[test]
    fn union_with_unknown_collapses() {
        assert_eq!(
            Type::union(vec![Type::Number, Type::Unknown]),
            Type::Unknown,
        );
        assert_eq!(
            Type::union(vec![Type::Unknown, Type::String, Type::Null]),
            Type::Unknown,
        );
    }

    fn obj(fields: Vec<(&str, Type, bool)>) -> Type {
        Type::Object {
            index: None,
            fields: fields
                .into_iter()
                .map(|(k, ty, optional)| {
                    (
                        k.to_string(),
                        crate::ObjectField {
                            ty,
                            optional,
                            readonly: false,
                            method: false,
                        },
                    )
                })
                .collect(),
        }
    }

    fn iref(name: &str) -> Type {
        Type::interface_ref(
            crate::types::Package::user(),
            name,
            crate::mangle::package_symbol(crate::mangle::USER_PACKAGE, name),
            Vec::new(),
        )
    }

    /// A namespace holding a single interface named `name` with the given
    /// properties; `has_method` adds a method so the interface is no longer
    /// data-only.
    fn ns_with_interface(
        name: &'static str,
        properties: Vec<(&'static str, Type, bool)>,
        has_method: bool,
    ) -> TypeNamespace<'static> {
        use crate::package_declaration::{Dispatch, MethodSig, PropertySig};
        use std::collections::BTreeMap;
        let properties: BTreeMap<String, PropertySig> = properties
            .into_iter()
            .map(|(field, ty, optional)| {
                (
                    field.to_string(),
                    PropertySig {
                        ty,
                        readonly: false,
                        intrinsic: false,
                        optional,
                        doc: None,
                    },
                )
            })
            .collect();
        let mut methods = BTreeMap::new();
        if has_method {
            methods.insert(
                "m".to_string(),
                MethodSig {
                    optional: false,
                    generics: Vec::new(),
                    params: Vec::new(),
                    ret: Type::Void,
                    predicate: None,
                    doc: None,
                },
            );
        }
        let mut ns = TypeNamespace::new();
        ns.insert(
            name.to_string(),
            crate::mangle::USER_PACKAGE.to_string(),
            crate::TypeSymbol {
                name: name.to_string(),
                mangled_name: crate::mangle::package_symbol(crate::mangle::USER_PACKAGE, name),
                declaration_span: crate::Span::at(crate::FileId(0)),
                kind: TypeKind::Interface {
                    index: None,
                    generics: Vec::new(),
                    methods,
                    properties,
                    dispatch: Dispatch::VTable,
                    doc: None,
                },
            },
        );
        ns
    }

    fn assignable_with(actual: &Type, expected: &Type, ns: &TypeNamespace) -> bool {
        let registry = TypeRegistry::new();
        let limits = crate::type_size::TypeLimits::default();
        super::assignable(
            actual,
            expected,
            TypeResolver {
                types: ns,
                registry: &registry,
                limits: &limits,
            },
        )
    }

    #[test]
    fn object_value_assignable_to_data_only_interface_both_ways() {
        let ns = ns_with_interface("Issue", vec![("id", Type::String, false)], false);
        let object = obj(vec![("id", Type::String, false)]);
        let iface = iref("Issue");
        assert!(assignable_with(&object, &iface, &ns), "object -> interface");
        assert!(assignable_with(&iface, &object, &ns), "interface -> object");
    }

    #[test]
    fn object_width_subtyping_into_interface() {
        // Extra fields on the object are fine when assigning into the interface.
        let ns = ns_with_interface("Issue", vec![("id", Type::String, false)], false);
        let wider = obj(vec![
            ("id", Type::String, false),
            ("extra", Type::Number, false),
        ]);
        assert!(assignable_with(&wider, &iref("Issue"), &ns));
    }

    #[test]
    fn object_missing_required_interface_field_rejected() {
        let ns = ns_with_interface(
            "Issue",
            vec![("id", Type::String, false), ("title", Type::String, false)],
            false,
        );
        let only_id = obj(vec![("id", Type::String, false)]);
        assert!(!assignable_with(&only_id, &iref("Issue"), &ns));
    }

    #[test]
    fn method_bearing_interface_not_structurally_assignable() {
        let ns = ns_with_interface("Logger", vec![("id", Type::String, false)], true);
        let object = obj(vec![("id", Type::String, false)]);
        assert!(
            !assignable_with(&object, &iref("Logger"), &ns),
            "object -> method iface"
        );
        assert!(
            !assignable_with(&iref("Logger"), &object, &ns),
            "method iface -> object"
        );
    }
}