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
//! Diagnostic-emitting helpers and the wrappers around the
//! `.d.ts`-style definition / signature lifts used by B1 / B2.
//!
//! Also hosts the "did you mean" closest-match callers (B3) — they
//! delegate to [`crate::did_you_mean`] but need access to `self.types`
//! and `self.scopes`, so the helper sits here on the `Inferer`.

use crate::{Diagnostic, ExprId, MethodSig, Severity, Span, Type, TypeKind, ValueKind};

use super::format_signature::SignatureKind;
use super::lookup::FieldWrite;
use crate::did_you_mean;
use crate::typechecker::type_param_substitution::TypeParamSubstitution;

use super::{Inferer, format_definition, format_signature, narrowing};

/// Add-on payload for a diagnostic: free-form `help:` lines plus
/// span-anchored notes. Used by the narrowing-invalidation hint
/// (plan 75.17a) to attach both a fix-shape help and a "this killed
/// you" pointer to a primary diagnostic.
type DiagnosticAddon = (Vec<String>, Vec<(Span, String)>);

/// The message every plain type mismatch reports. Callers that drop a
/// duplicate mismatch match against it, so the wording lives only here.
pub(super) fn mismatch_message(
    expected: &impl std::fmt::Display,
    got: &impl std::fmt::Display,
) -> String {
    format!("expected `{expected}`, got `{got}`")
}

/// Whether a type *spells* `null` or `undefined` — the signal that a failing
/// read is about a missing narrowing rather than an unrelated mismatch.
/// Deliberately narrower than `infer::expr`'s `type_admits_nullish`, which
/// answers the semantic question: `unknown` admits both too, but its callers
/// gate on assignability and `unknown` is assignable to nothing, so it would
/// never reach a hint here.
fn spells_nullish(ty: &Type) -> bool {
    ty.spells_null() || ty.spells_undefined()
}

/// The absent values a type spells, so a receiver diagnostic names and guards
/// against exactly those: `null | A` needs only `!== null`.
#[derive(Clone, Copy, Default)]
struct Absence {
    null: bool,
    undefined: bool,
}

impl Absence {
    fn of(ty: &Type) -> Self {
        Self {
            null: ty.spells_null(),
            undefined: ty.spells_undefined(),
        }
    }

    fn describe(self) -> &'static str {
        match (self.null, self.undefined) {
            (true, false) => "`null`",
            (false, true) => "`undefined`",
            _ => "nullish",
        }
    }

    fn guard(self, recv: &str) -> String {
        match (self.null, self.undefined) {
            (true, false) => format!("{recv} !== null"),
            (false, true) => format!("{recv} !== undefined"),
            _ => format!("{recv} !== null && {recv} !== undefined"),
        }
    }
}

/// Which side of the assignment a member access sits on. A write carries the
/// operator, because the rewrite it names has to be the edit the reader makes —
/// `x!.f = …` is a different operation from `x.f++`.
#[derive(Clone, Copy)]
enum MemberSide {
    Read,
    Write(Option<RwOp>),
}

/// How a write to `target` is spelled, for a rewrite the reader can paste.
/// `None` is a plain assignment.
fn write_form(target: &str, op: Option<RwOp>) -> String {
    match op {
        None => format!("{target} = …"),
        Some(rw @ RwOp::Postfix(_)) => format!("{target}{}", rw.text()),
        Some(rw) => format!("{target} {} …", rw.text()),
    }
}

/// What a member name resolves to on a receiver with `null` removed. A method
/// has to be *called*, so its rewrites carry the call; a bare `x?.m` is a method
/// reference, which is not a value in this language.
#[derive(Clone, Copy)]
enum NonNullAccess {
    Field,
    /// The arity is carried rather than assumed: `a!.map()` is a fix that does
    /// not compile, and it drops whatever the reader already passed.
    Method {
        takes_args: bool,
    },
}

impl NonNullAccess {
    fn call_suffix(self) -> &'static str {
        match self {
            NonNullAccess::Field => "",
            NonNullAccess::Method { takes_args: false } => "()",
            NonNullAccess::Method { takes_args: true } => "(…)",
        }
    }
}

/// A read-modify-write operator: `x.f += v` or `x.f++`. Holds the operator
/// itself rather than its renderings, so a diagnostic cannot name one operator
/// while applying another's accept rule.
#[derive(Clone, Copy)]
pub(super) enum RwOp {
    Compound(crate::BinOp),
    /// Only `Inc` / `Dec` reach here — `infer_postfix` sends `NonNullAssert`
    /// down its own path before any target is resolved.
    Postfix(crate::PostfixOp),
}

impl RwOp {
    /// How the source spells the operator.
    pub(super) fn text(self) -> String {
        match self {
            RwOp::Compound(binary) => format!("{}=", super::stmt::binary_op_text(binary)),
            RwOp::Postfix(crate::PostfixOp::Dec) => "--".to_string(),
            RwOp::Postfix(_) => "++".to_string(),
        }
    }

    /// The binary operator a written-out rewrite applies.
    pub(super) fn sign(self) -> &'static str {
        match self {
            RwOp::Compound(binary) => super::stmt::binary_op_text(binary),
            RwOp::Postfix(crate::PostfixOp::Dec) => "-",
            RwOp::Postfix(_) => "+",
        }
    }

    /// Whether the operator is defined for `ty` at all. A field it rejects
    /// regardless of `null` is not a nullability problem, and saying otherwise
    /// sends the reader after a guard that changes nothing.
    fn accepts(self, ty: &Type) -> bool {
        // Arithmetic widens literals; the result cannot be stored back into
        // a literal-only field, even after a null guard.
        let is_literal =
            |ty: &Type| matches!(ty.peel(), Type::NumberLiteral(_) | Type::StringLiteral(_));
        if is_literal(ty)
            || matches!(ty.peel(), Type::Union(members) if members.iter().all(is_literal))
        {
            return false;
        }
        match self {
            RwOp::Compound(binary) => super::stmt::compound_arith_result(binary, ty, ty).is_some(),
            // `++` / `--` write `x.f ± 1` back, so they need what that binary
            // form needs, including a compatible write-back type.
            RwOp::Postfix(_) => {
                super::stmt::compound_arith_result(crate::BinOp::Add, ty, &Type::Number).is_some()
                    || super::stmt::compound_arith_result(crate::BinOp::Add, ty, &Type::BigInt)
                        .is_some()
            }
        }
    }
}

impl<'a> Inferer<'a> {
    pub(super) fn error(&mut self, span: Span, message: String) {
        self.error_with_help_and_notes(span, message, vec![], vec![]);
    }

    /// Like [`Self::error`] but attaches one or more `help:` blocks
    /// (free-form, no span anchor). Span-anchored secondaries belong
    /// in [`Diagnostic::notes`] — this is for lifted type/signature
    /// definitions and similar fix-shape text the LLM needs but that
    /// doesn't point anywhere in the source.
    pub(super) fn error_with_help(&mut self, span: Span, message: String, help: Vec<String>) {
        self.error_with_help_and_notes(span, message, help, vec![]);
    }

    /// How many *errors* have been reported so far.
    ///
    /// Callers that suppress a follow-on diagnostic must count errors, not all
    /// diagnostics: an error aborts before codegen, so a warning is the only
    /// thing that can both raise the count and let compilation continue —
    /// which would silence the follow-on and let its subject reach codegen.
    pub(super) fn error_count(&self) -> usize {
        self.diagnostics
            .iter()
            .filter(|d| d.severity == crate::Severity::Error)
            .count()
    }

    /// Bare `void` and `never` cannot be tested for truthiness.
    pub(super) fn error_non_condition_type(&mut self, span: Span, ty: &Type) {
        let help = vec![
            "conditions need a value to test for truthiness; this expression \
             produces none. Call something that returns a value, or restructure \
             the condition."
                .to_string(),
        ];
        self.error_with_help(
            span,
            format!("expected a value in this condition, got `{ty}`"),
            help,
        );
    }

    /// Report a write to a block-scoped binding that cannot be reassigned: a
    /// `const`, or a nested function, which is immutable as in TypeScript.
    pub(super) fn report_const_local_write(
        &mut self,
        target: &crate::Ident,
        entry: &super::scopes::ScopeEntry,
    ) {
        let (message, help, note) = if entry.nested_function.is_some() {
            (
                format!("cannot assign to function `{}`", target.name),
                "functions are immutable; declare a `let f = …` binding to reassign".to_string(),
                "declared as a function here",
            )
        } else {
            (
                format!("cannot assign to const binding `{}`", target.name),
                format!(
                    "declare with `let` if reassignment is required: `let {} = …;`",
                    target.name
                ),
                "declared as `const` here",
            )
        };
        self.error_with_help_and_notes(
            target.span,
            message,
            vec![help],
            vec![(entry.decl_span, note.to_string())],
        );
    }

    /// Like [`Self::error_with_help`] but also attaches span-anchored
    /// secondary notes. Used by diagnostic sites that lift both a
    /// fix-shape help block and a "this is what killed you" pointer
    /// at another location — currently the property-path narrowing
    /// tombstone surfaces (plan 75.17a).
    ///
    /// Error reports are dropped while a type limit is recorded: until the next
    /// checkpoint fails compilation with it, they may describe the `Type::Error`
    /// stand-in rather than the source. Errors that do not depend on types,
    /// such as a duplicate `case` label or an assignment to a `const`, are
    /// pushed directly and still reported.
    pub(super) fn error_with_help_and_notes(
        &mut self,
        span: Span,
        message: String,
        help: Vec<String>,
        notes: Vec<(Span, String)>,
    ) {
        if self.type_limits.limit_reached() {
            return;
        }
        self.diagnostics.push(Diagnostic {
            severity: Severity::Error,
            span,
            message,
            help,
            notes,
        });
    }

    /// Plan 75.17a: build the `(help, notes)` add-on for a failing
    /// field / method / index access whose receiver lost a narrowing.
    /// Returns `None` when there's nothing relevant to surface — the
    /// caller then emits the bare diagnostic.
    ///
    /// Strategy: derive the receiver's [`narrowing::ReferencePath`]
    /// and look it up first in the tombstone stack (a narrowing was
    /// installed and then killed), then in the closure-mutator set
    /// (the narrowing was refused outright under stability rule 5).
    /// The two sources are mutually exclusive in practice — a path
    /// can't have both a live tombstone and a captured-mutator root
    /// at the same time without something else having gone wrong.
    pub(super) fn narrowing_invalidation_hint(
        &self,
        receiver: ExprId,
    ) -> Result<Option<DiagnosticAddon>, crate::compiler_error::CompilerFailure> {
        let receiver_expr = self
            .typed_ast
            .try_expr(receiver)
            .map_err(crate::typechecker::arena_failure)?;
        if let Some(hint) = self.getter_narrowing_hint(&receiver_expr.kind)? {
            return Ok(Some(hint));
        }
        let Some(path) = self.expr_to_reference_path(receiver_expr)? else {
            return Ok(None);
        };
        Ok(self.narrowing_hint_for_path(&path))
    }

    /// The operand whose `null` is what breaks this site: it admits `null`, and
    /// `accepts` says dropping `null` would make the site legal. Callers must supply
    /// that second half — advice that still fails when followed verbatim is worse
    /// than no advice, and a nullable operand sitting beside an unrelated mismatch
    /// is the common case, not the rare one.
    pub(super) fn nullish_culprit(
        &self,
        operands: &[(ExprId, &Type)],
        accepts: impl Fn(&Type) -> bool,
    ) -> Option<ExprId> {
        operands.iter().find_map(|(expr, ty)| {
            if !spells_nullish(ty) {
                return None;
            }
            let non_null = super::narrow_scopes::non_null_form((*ty).clone())?;
            accepts(&non_null).then_some(*expr)
        })
    }

    /// [`error_with_help`](Self::error_with_help) plus the narrowing hint for
    /// `culprit` — the operand a caller has already established is nullable *and*
    /// the reason this site fails (see [`nullish_culprit`](Self::nullish_culprit)).
    /// `None` emits the bare diagnostic.
    pub(super) fn error_with_narrowing_hint(
        &mut self,
        span: Span,
        message: String,
        mut help: Vec<String>,
        culprit: Option<ExprId>,
    ) -> Result<(), crate::compiler_error::CompilerFailure> {
        let mut notes = Vec::new();
        if let Some((extra_help, extra_notes)) = culprit
            .map(|e| self.narrowing_invalidation_hint(e))
            .transpose()?
            .flatten()
        {
            help.extend(extra_help);
            notes.extend(extra_notes);
        }
        self.error_with_help_and_notes(span, message, help, notes);
        Ok(())
    }

    /// The culprit for a binary operator, given the operator's own rule for which
    /// operand pairs it accepts. `accepts` must be the *same* rule the arm used to
    /// decide it had an error — "the two sides now agree" is not enough, since
    /// `number[] + number[]` agrees and is still rejected.
    pub(super) fn nullable_binary_culprit(
        &self,
        lhs: (ExprId, &Type),
        rhs: (ExprId, &Type),
        accepts: impl Fn(&Type, &Type) -> bool,
    ) -> Option<ExprId> {
        self.nullish_culprit(&[lhs], |non_null| accepts(non_null, rhs.1))
            .or_else(|| self.nullish_culprit(&[rhs], |non_null| accepts(lhs.1, non_null)))
            .or_else(|| {
                // Both sides nullable: neither one-sided probe can match, yet a
                // single guard may still cover both (`s + s`, or two variables
                // guarded together). Try dropping `null` from both.
                let rhs_non_null = super::narrow_scopes::non_null_form(rhs.1.clone())?;
                self.nullish_culprit(&[lhs], |non_null| accepts(non_null, &rhs_non_null))
            })
    }

    /// Why a path isn't narrowed here, most specific cause first. A killed
    /// narrowing, a closure boundary and a refused shape are different stories;
    /// whichever applies must win consistently, or the same program point gets
    /// contradictory advice depending on which diagnostic site fired.
    pub(super) fn narrowing_hint_for_path(
        &self,
        path: &narrowing::ReferencePath,
    ) -> Option<DiagnosticAddon> {
        // Guards that ruled out every value hold here: no write or boundary
        // dropped them, though a write elsewhere may have left a tombstone.
        if self
            .narrowed_read(path.clone())
            .is_some_and(|(_, ty)| matches!(ty, Type::Never))
        {
            return None;
        }
        if let Some(reason) = self.lookup_tombstone(path) {
            return Some(self.invalidation_reason_hint(path, &reason));
        }
        if self.path_root_is_captured_mutator(path) {
            return Some(self.captured_mutator_hint(path));
        }
        if self.narrowed_in_suspended_frame(path) {
            return Some(self.closure_boundary_hint(path));
        }
        None
    }

    /// Explains a nullable read on a path whose guard the engine cannot carry
    /// to this point, for diagnostic sites that fire while inferring the
    /// expression rather than on a later read of it.
    ///
    /// Fires only when dropping `null` would actually satisfy `want` — that is
    /// what separates "you need a guard here" from an unrelated mismatch that
    /// merely happens to involve a nullable value.
    pub(super) fn narrowing_refusal_hint(
        &self,
        kind: &crate::TypedExprKind,
        got: &Type,
        want: &Type,
    ) -> Result<Option<DiagnosticAddon>, crate::compiler_error::CompilerFailure> {
        if !spells_nullish(got) {
            return Ok(None);
        }
        let Some(non_null) = super::narrow_scopes::non_null_form(got.clone()) else {
            return Ok(None);
        };
        if !super::assignable::assignable(&non_null, want, self.resolver()) {
            return Ok(None);
        }
        if let Some(hint) = self.getter_narrowing_hint(kind)? {
            return Ok(Some(hint));
        }
        let Some(path) = self.kind_to_reference_path(kind)? else {
            return Ok(None);
        };
        Ok(self.narrowing_hint_for_path(&path))
    }

    fn getter_narrowing_hint(
        &self,
        kind: &crate::TypedExprKind,
    ) -> Result<Option<DiagnosticAddon>, crate::compiler_error::CompilerFailure> {
        let Some(state) = self.kind_to_reference_path_state(kind)? else {
            return Ok(None);
        };
        if !state.contains_getter {
            return Ok(None);
        }
        let rendered = state.path.render();
        let tmp = self.fresh_hint_binding();
        Ok(Some((
            vec![format!(
                "`{rendered}` is getter-backed, so each read may return a different value and its guard cannot narrow later reads. Bind one read to a local `const` first: `const {tmp} = {rendered};` then guard `{tmp}`."
            )],
            Vec::new(),
        )))
    }

    /// A binding name the suggested rewrite can introduce without colliding
    /// with something already in scope — `const v = v` is not advice.
    fn fresh_hint_binding(&self) -> String {
        (0..)
            .map(|n| {
                if n == 0 {
                    "v".to_string()
                } else {
                    format!("v{n}")
                }
            })
            .find(|name| self.scopes.get(name).is_none())
            .unwrap_or_else(|| "v".to_string())
    }

    /// What a local binding's declared type can be instead of a value; a deeper
    /// path or another root falls back to guarding against both.
    fn path_absence(&self, path: &narrowing::ReferencePath) -> Absence {
        match (&path.root, path.chain.is_empty()) {
            (narrowing::BindingId::Local { name, .. }, true) => self
                .scopes
                .get(name)
                .map(|binding| Absence::of(&binding.ty))
                .filter(|absence| absence.null || absence.undefined)
                .unwrap_or(Absence {
                    null: true,
                    undefined: true,
                }),
            _ => Absence {
                null: true,
                undefined: true,
            },
        }
    }

    /// The path is narrowed outside the closure we are currently inferring, but
    /// isn't one of the stable depth-0 narrowings that cross the
    /// boundary (stability rule 9).
    fn closure_boundary_hint(&self, path: &narrowing::ReferencePath) -> DiagnosticAddon {
        let rendered = path.render();
        let tmp = self.fresh_hint_binding();
        // Always the hoist form: a `let` could also just be declared `const`,
        // but a parameter can't, and both are `BindingId::Local` here.
        (
            vec![format!(
                "narrowing on `{rendered}` does not cross a closure boundary — \
                 only a directly narrowed binding with no later or nested-function \
                 writes keeps its narrowing inside a closure body. Bind it to a `const` \
                 first: `const {tmp} = {rendered}; if ({}) {{ … }}` — or \
                 re-narrow inside the closure.",
                self.path_absence(path).guard(&tmp),
            )],
            Vec::new(),
        )
    }

    fn invalidation_reason_hint(
        &self,
        path: &narrowing::ReferencePath,
        reason: &narrowing::InvalidationReason,
    ) -> DiagnosticAddon {
        let rendered = path.render();
        // Neither help offers an `if (x !== null)` example: the dropped narrowing
        // may be a discriminant or `typeof` one, where that edit does nothing. The
        // primary diagnostic already names the form this type needs.
        let (help, note_text) = match reason {
            narrowing::InvalidationReason::ShapeUnrebuildable { .. } => (
                format!(
                    "cannot preserve this guard on `{rendered}` because its source cannot be \
                     rebuilt here. Bind the value to a local `const` and guard that instead."
                ),
                String::new(),
            ),
            narrowing::InvalidationReason::Write { .. } => (
                format!(
                    "narrowing on `{rendered}` was dropped by the write — \
                     re-narrow it after the write to read it again."
                ),
                // Names no path: the write may be to a *prefix* of `rendered`
                // (`o = …` drops `o.a`), and the span already points at it.
                format!("this write invalidates the narrowing on `{rendered}`"),
            ),
            narrowing::InvalidationReason::Reassignment { .. } => (
                format!(
                    "narrowing on `{rendered}` was dropped by the reassignment — \
                     re-narrow it after the reassignment to read it again."
                ),
                format!("this reassignment invalidates the narrowing on `{rendered}`"),
            ),
            narrowing::InvalidationReason::CapturedMutator { .. } => {
                // Should not be reachable via lookup_tombstone — the
                // captured-mutator case is detected via
                // `path_root_is_captured_mutator` below. Fall back to
                // a generic message just in case.
                (
                    format!("narrowing on `{rendered}` was refused (stability rule 5)."),
                    "narrowing refused here".to_string(),
                )
            }
        };
        let mut notes = Vec::new();
        if let Some(span) = reason.span() {
            notes.push((span, note_text));
        }
        (vec![help], notes)
    }

    /// Leads with the read-into-`const`-and-write-back rewrite rather than
    /// "drop the reassignment", because the reassignment is often the very
    /// statement being diagnosed — `v += 1` or `v = v + 1` inside the closure.
    /// There, dropping it and declaring `v` as `const` are both refusals to write
    /// the program. The hoist form compiles either way.
    fn captured_mutator_hint(&self, path: &narrowing::ReferencePath) -> DiagnosticAddon {
        let root_name = match &path.root {
            narrowing::BindingId::Local { name, .. } => name.clone(),
            narrowing::BindingId::Global(_) | narrowing::BindingId::This => path.render(),
        };
        let tmp = self.fresh_hint_binding();
        (
            vec![format!(
                "narrowing on `{root_name}` was refused because a closure body \
                 reassigns `{root_name}` — stability rule 5. Read it into a \
                 `const` and write back: `const {tmp} = {root_name}; \
                 if ({}) {{ {root_name} = {tmp}…; }}` — or, if \
                 `{root_name}` never needs to change, declare it `const`.",
                self.path_absence(path).guard(&tmp),
            )],
            Vec::new(),
        )
    }

    /// Wrapper around [`format_definition::format_definition`] that threads the
    /// FQN registry (with `self.types` as fallback) so a library-typed value's
    /// shape is lifted into help even when the interface name was never imported.
    pub(super) fn format_definition(&self, ty: &Type) -> String {
        self.render_help(format_definition::format_definition(
            ty,
            &self.types,
            &self.type_registry,
        ))
    }

    /// Infallible diagnostic builders retain the original diagnostic while the
    /// phase checkpoint propagates rendering failure and discards compilation.
    /// Rendering has its own budgets and never clears a pending semantic limit.
    pub(super) fn render_help(
        &self,
        rendered: Result<String, crate::rendering::RenderError>,
    ) -> String {
        match rendered {
            Ok(text) => text,
            Err(crate::rendering::RenderError::Truncated) => crate::rendering::TRUNCATED.into(),
            Err(error) => {
                let previous = self.diagnostic_failure.take();
                self.diagnostic_failure.set(Some(previous.unwrap_or(error)));
                "[diagnostic help unavailable]".into()
            }
        }
    }

    pub(super) fn render_help_list(
        &self,
        rendered: Result<Vec<String>, crate::rendering::RenderError>,
    ) -> Vec<String> {
        match rendered {
            Ok(help) => help,
            Err(error) => vec![self.render_help(Err(error))],
        }
    }

    pub(super) fn render_optional_help(
        &self,
        rendered: Result<Option<String>, crate::rendering::RenderError>,
    ) -> Option<String> {
        match rendered {
            Ok(help) => help,
            Err(error) => Some(self.render_help(Err(error))),
        }
    }

    /// The type's definition lifted as a `help:` block, empty when the lift is
    /// only the type's own `Display`. Every caller already prints the type in the
    /// message line, so a union (and the other arms with no members to list)
    /// would otherwise echo it back as advice.
    pub(super) fn definition_help(&self, ty: &Type) -> Vec<String> {
        let lifted = self.format_definition(ty);
        if lifted == ty.peel().to_string() {
            return Vec::new();
        }
        vec![lifted]
    }

    /// Look up the doc comment for a top-level function by name.
    /// Returns `None` for non-functions or unknown names. Used by B2
    /// signature lifts to thread the function's JSDoc into the help
    /// block..
    pub(super) fn lookup_function_doc(&self, name: &str) -> Option<crate::DocComment> {
        self.top_symbols
            .get(name)
            .and_then(|entry| match &entry.kind {
                ValueKind::Function { doc, .. } => doc.clone(),
                _ => None,
            })
    }

    /// Builds the substitution a method lift renders with — empty for every
    /// other kind — and hands it to the formatter.
    ///
    /// Used by the B2 diagnostic sites (method / generic-call arity, type-arg,
    /// argument-type mismatches) that need to lift a callable's signature into a
    /// one-line `help:` block. A method lift substitutes at the args the member
    /// was actually looked up with — see
    /// checked definition lookup.
    pub(super) fn format_signature(&self, kind: format_signature::SignatureKind<'_>) -> String {
        if let SignatureKind::Function {
            name,
            generics,
            params,
            ret,
            doc,
            ..
        } = kind
        {
            let predicate = self
                .lookup_top_function(name)
                .and_then(|entry| match &entry.kind {
                    ValueKind::Function { type_predicate, .. } => type_predicate.as_ref(),
                    _ => None,
                });
            return self.render_help(format_signature::format_signature(
                SignatureKind::Function {
                    name,
                    generics,
                    params,
                    ret,
                    doc,
                    predicate,
                },
                &TypeParamSubstitution::new(),
            ));
        }
        let substitution = match &kind {
            SignatureKind::Method {
                receiver_ty, name, ..
            } => match format_definition::method_bindings(
                &self.types,
                &self.type_registry,
                receiver_ty,
                name,
            ) {
                Ok(bindings) => bindings,
                Err(error) => return self.render_help(Err(error)),
            },
            _ => TypeParamSubstitution::new(),
        };
        self.render_help(format_signature::format_signature(kind, &substitution))
    }

    /// Suggest the closest identifier (across local scopes + top
    /// symbols) to `query`. Used by B3's "unresolved identifier"
    /// diagnostics to attach a "did you mean `X`?" help block.
    pub(super) fn closest_local_or_global(&self, query: &str) -> Option<String> {
        let locals: Vec<&str> = self.scopes.all_names().collect();
        let globals = self.top_symbols.keys().map(String::as_str);
        // A later global bound early is in `top_symbols` though hidden here;
        // suggesting the name itself would not help.
        let candidates = locals
            .into_iter()
            .chain(globals)
            .filter(|name| *name != query);
        did_you_mean::closest_match(query, candidates).map(String::from)
    }

    /// Report `name` as unresolved. A `let`/`const` declared in another clause
    /// of an enclosing `switch` gets its own message: JavaScript scopes the
    /// clauses together, but the declaration only runs when its own clause does.
    pub(super) fn report_unresolved_identifier(&mut self, name: &str, span: Span) {
        if let Some(declaration) = self.declaration_in_another_case_clause(name) {
            // A read above the declaration already has its use-before-declaration error.
            let reported = self
                .diagnostics
                .iter()
                .any(|d| d.severity == crate::Severity::Error && d.span == span);
            if reported {
                return;
            }
            self.error_with_help_and_notes(
                span,
                format!("`{name}` is declared in another `case` clause"),
                vec![format!(
                    "declare `{name}` before the `switch` to use it in more than one clause"
                )],
                vec![(declaration, format!("`{name}` is declared here"))],
            );
            return;
        }
        let help: Vec<String> = self
            .closest_local_or_global(name)
            .map(|s| vec![format!("did you mean `{}`?", s)])
            .unwrap_or_default();
        self.error_with_help(span, format!("unresolved identifier `{name}`"), help);
    }

    /// Suggest the closest type name to `query` from the four
    /// primitive keywords + every name in `self.types`. Used by B3's
    /// "unknown type" diagnostic.
    pub(super) fn closest_type_name(&self, query: &str) -> Option<String> {
        const BUILTINS: [&str; 5] = ["number", "string", "boolean", "void", "never"];
        let user_types: Vec<&str> = self.types.iter_names().collect();
        did_you_mean::closest_match(query, BUILTINS.into_iter().chain(user_types)).map(String::from)
    }

    /// Report a field that does not exist on `receiver_ty` — the single place
    /// that decides whether such a miss is reportable at all. A class whose
    /// `extends` clause never resolved could have inherited the field from the
    /// parent we failed to find, so the miss there is unknowable rather than
    /// wrong, and the clause's own diagnostic stands alone.
    pub(super) fn report_missing_field(&mut self, span: Span, receiver_ty: &Type, name: &str) {
        if self.receiver_inherits_unresolved_parent(receiver_ty) {
            return;
        }
        let help = self.interface_member_miss_help(receiver_ty, name);
        self.error_with_help(
            span,
            format!("field `{name}` does not exist on `{receiver_ty}`"),
            help,
        );
    }

    /// Reports a failing member *read* that is really a method named without
    /// its call, answering whether it did. `false` means the name is not a
    /// method and the caller still owes a diagnostic — same shape as
    /// [`report_static_on_instance`](Self::report_static_on_instance).
    ///
    /// Read positions only. In a write the fix is not "call it", so assignment
    /// goes straight to [`report_missing_field`](Self::report_missing_field).
    pub(super) fn try_report_method_reference(
        &mut self,
        span: Span,
        receiver_ty: &Type,
        name: &str,
    ) -> bool {
        let Some((sig, ..)) = self.find_method(receiver_ty, name) else {
            return false;
        };
        self.report_method_reference(span, receiver_ty, name, &sig);
        true
    }

    /// A method named where a value is expected. A bare instance-method
    /// reference is not a value in this language, on any receiver, so the fix is
    /// always to call it and the signature lift shows what to pass.
    pub(super) fn report_method_reference(
        &mut self,
        span: Span,
        receiver_ty: &Type,
        name: &str,
        sig: &MethodSig,
    ) {
        // Rendered with the receiver's generic bindings applied, so the
        // parameters shown are the ones the caller actually has to pass.
        let help = self.format_signature(SignatureKind::Method {
            receiver_ty,
            name,
            sig,
        });
        self.error_with_help(
            span,
            format!("method `{name}` must be called — a method reference is not a value"),
            vec![
                help,
                "to pass it as a value, wrap the call in an arrow".to_string(),
            ],
        );
    }

    /// Reports a failing member *write* that is really an assignment to a method,
    /// answering whether it did. `false` means the name is not a method and the
    /// caller still owes a diagnostic — the write-position twin of
    /// [`try_report_method_reference`](Self::try_report_method_reference).
    ///
    /// Without it a class receiver reports the name as missing and then suggests
    /// that same name back, and an interface receiver calls the method a readonly
    /// property; both leave the reader to guess that methods are not assignable
    /// at all.
    pub(super) fn try_report_method_assignment(
        &mut self,
        span: Span,
        receiver_ty: &Type,
        name: &str,
    ) -> bool {
        let Some((sig, ..)) = self.find_method(receiver_ty, name) else {
            return false;
        };
        let help = self.format_signature(SignatureKind::Method {
            receiver_ty,
            name,
            sig: &sig,
        });
        self.error_with_help(
            span,
            format!("cannot assign to method `{name}` on `{receiver_ty}`"),
            vec![
                help,
                "methods are fixed at their declaration; only a field of function type \
                 can be reassigned"
                    .to_string(),
            ],
        );
        true
    }

    /// Rejects a nullable or optional field as a read-modify-write target
    /// (`x.f += v`, `x.f++`), answering whether it did.
    ///
    /// Only when dropping `null` would actually make the operator legal — the
    /// same rule [`nullish_culprit`](Self::nullish_culprit) enforces for the
    /// operator diagnostics. A `boolean`, array, or literal-union field admits
    /// no `+=` whether or not it is nullable, and blaming the null there sends
    /// the reader after a guard that changes nothing; those fall through to the
    /// operator's own message, which names the real problem.
    ///
    /// The rewrite it names is the written-out assignment rather than a guard,
    /// because narrowing does not reach a read-modify-write target: an `if`
    /// around the statement leaves the target's own read un-narrowed, so the
    /// advice that works everywhere else is wrong here.
    pub(super) fn try_report_nullable_rw_target(
        &mut self,
        receiver_span: Span,
        receiver_ty: &Type,
        name: &crate::Ident,
        field_ty: &Type,
        optional: bool,
        op: RwOp,
    ) -> bool {
        // Compare against the *peeled* type: `strip_nullish` peels, so an alias
        // of a non-nullish type would otherwise differ from its own declaration
        // and read as nullish.
        let non_null = narrowing::strip_nullish(field_ty);
        if !optional && non_null == *field_ty.peel() {
            return false;
        }
        if !op.accepts(&non_null) {
            return false;
        }
        // `++` / `--` mean exactly ±1, so the rewrite names the whole statement.
        // A compound assignment's right-hand side is whatever the caller wrote,
        // and guessing it would hand back code computing the wrong thing.
        let operand = match op {
            RwOp::Postfix(_) if non_null.is_bigint() => "1n",
            RwOp::Postfix(_) => "1",
            RwOp::Compound(_) => "…",
        };
        let rewrite = format!("{} {operand}", op.sign());
        let shape = if optional { "optional" } else { "nullable" };
        let target = format!("{}.{}", self.rewritable_snippet(receiver_span), name.name);
        let mut absence = Absence::of(field_ty);
        absence.undefined |= optional;
        let op_text = op.text();
        self.error_with_help(
            name.span,
            format!(
                "`{}` on `{receiver_ty}` is {shape}; `{op_text}` requires a field that is never {}",
                name.name,
                absence.describe(),
            ),
            vec![format!(
                "narrowing does not reach the target of `{op_text}`; write the assignment out: \
                 `if ({}) {{ {target} = {target} {rewrite}; }}`",
                absence.guard(&target),
            )],
        );
        true
    }

    /// A field read that misses on an object literal's own shape. Deliberately
    /// not [`report_missing_field`](Self::report_missing_field): that one's help
    /// routes a structural receiver to the prelude `Object` interface and would
    /// list *its* members. What the reader needs here is the shape they wrote.
    pub(super) fn report_missing_object_field(
        &mut self,
        span: Span,
        receiver_ty: &Type,
        name: &str,
    ) {
        let help = vec![self.format_definition(receiver_ty)];
        self.error_with_help(
            span,
            format!("field `{name}` does not exist on `{receiver_ty}`"),
            help,
        );
    }

    /// A field read on a receiver that carries no fields at all. Attaches the
    /// type's definition plus, when the receiver lost a narrowing, the hint
    /// naming what killed it. A nullable receiver gets the guard rewrite *instead
    /// of* the definition dump — the definition is not what is wrong with it.
    pub(super) fn report_non_object_field_read(
        &mut self,
        span: Span,
        receiver: ExprId,
        receiver_ty: &Type,
        name: &str,
    ) -> Result<(), crate::compiler_error::CompilerFailure> {
        let recv_span = self
            .typed_ast
            .try_expr(receiver)
            .map_err(crate::typechecker::arena_failure)?
            .span;
        let recv_path = self.expr_to_reference_path(
            self.typed_ast
                .try_expr(receiver)
                .map_err(crate::typechecker::arena_failure)?,
        )?;
        let nullable = self.nullable_receiver_fix(
            recv_span,
            recv_path.as_ref(),
            receiver_ty,
            name,
            MemberSide::Read,
        );
        let (message, mut help) = match nullable {
            Some(fix) => (
                format!(
                    "cannot read field `{name}` on `{receiver_ty}`: the receiver can be {}",
                    Absence::of(receiver_ty).describe(),
                ),
                vec![fix],
            ),
            None if receiver_ty.interface_routing().is_some()
                && !matches!(
                    receiver_ty.peel(),
                    Type::Number | Type::Boolean | Type::BooleanLiteral(_)
                ) =>
            {
                (
                    format!("field `{name}` does not exist on `{receiver_ty}`"),
                    self.interface_member_miss_help(receiver_ty, name),
                )
            }
            None => (
                format!("cannot read field `{name}` on non-object type `{receiver_ty}`"),
                self.definition_help(receiver_ty),
            ),
        };
        let mut notes: Vec<(Span, String)> = Vec::new();
        if let Some((extra_help, extra_notes)) = self.narrowing_invalidation_hint(receiver)? {
            help.extend(extra_help);
            notes.extend(extra_notes);
        }
        self.error_with_help_and_notes(span, message, help, notes);
        Ok(())
    }

    /// A field read on a union whose members otherwise carry fields, where one
    /// member can't back it. Which member and *why* are both load-bearing: told
    /// "does not exist" about a member that visibly declares the name, a reader
    /// goes looking for the wrong fix.
    pub(super) fn report_union_field_miss(
        &mut self,
        span: Span,
        receiver_path: Option<&narrowing::ReferencePath>,
        receiver_ty: &Type,
        missing: &Type,
        name: &str,
        miss: super::lookup::MemberFieldMiss,
    ) {
        use super::lookup::MemberFieldMiss;
        let message = match miss {
            MemberFieldMiss::Absent => format!(
                "field `{name}` does not exist on all members of `{receiver_ty}` \
                 (missing on `{missing}`)"
            ),
            MemberFieldMiss::Method => {
                format!(
                    "`{name}` is a method on `{missing}`, and a union receiver reads only fields"
                )
            }
            MemberFieldMiss::HostDispatched => format!(
                "`{name}` on `{missing}` is a built-in property, which a union receiver cannot reach"
            ),
        };
        let mut help = vec![
            self.format_definition(missing),
            union_narrow_help(receiver_ty),
        ];
        let mut notes: Vec<(Span, String)> = Vec::new();
        if let Some((extra_help, extra_notes)) =
            receiver_path.and_then(|p| self.narrowing_hint_for_path(p))
        {
            help.extend(extra_help);
            notes.extend(extra_notes);
        }
        self.error_with_help_and_notes(span, message, help, notes);
    }

    /// A member *write* whose receiver carries no assignable field map — the
    /// dead end `=`, `+=`, and `++` all fall to when
    /// [`assignment_target_fields`](Self::assignment_target_fields) returns
    /// `None`.
    ///
    /// A union is the one receiver here with a fix to name. `assignment_target_fields`
    /// answers `None` for *every* union, whether or not its members agree about
    /// the field, so per-member classification here is the only thing that can
    /// say which reason applies.
    ///
    /// The value the write was given is not typed here — callers that need the
    /// shape to check it against ask [`write_target_ty`](Self::write_target_ty).
    pub(super) fn report_unassignable_field_target(
        &mut self,
        recv_span: Span,
        name: &crate::Ident,
        receiver_ty: &Type,
        recv_path: Option<&narrowing::ReferencePath>,
        rw_op: Option<RwOp>,
    ) {
        use super::lookup::MemberFieldMiss;
        // The same gate the read side applies before it treats a receiver as a
        // union of shapes. A union carrying `null` or a primitive fails for a
        // different reason — that member has no fields at all — and the
        // narrow-to-one-member advice below would name `instanceof` at a
        // receiver whose fix is a null check.
        let members = match receiver_ty.peel() {
            Type::Union(members) if members.iter().all(Self::is_field_bearing) => members,
            _ => {
                return self.report_non_union_field_write(
                    recv_span,
                    name,
                    receiver_ty,
                    recv_path,
                    rw_op,
                );
            }
        };
        let field = &name.name;
        let miss = members.iter().find_map(|m| {
            self.union_member_field_read_ty(m, field)
                .err()
                .map(|reason| (m.clone(), reason))
        });
        let (message, missing) = match miss {
            Some((missing, MemberFieldMiss::Absent)) => (
                format!(
                    "field `{field}` does not exist on all members of `{receiver_ty}` \
                     (missing on `{missing}`)"
                ),
                Some(missing),
            ),
            Some((missing, MemberFieldMiss::Method)) => (
                format!(
                    "`{field}` is a method on `{missing}`; methods are fixed at their declaration"
                ),
                Some(missing),
            ),
            Some((missing, MemberFieldMiss::HostDispatched)) => (
                format!(
                    "`{field}` on `{missing}` is a built-in property, which a union receiver \
                     cannot assign through"
                ),
                Some(missing),
            ),
            // Every member backs the field, so it is the write itself that has
            // nowhere to go: the members may lay the field out at different
            // slots and there is no union-receiver field write to scan them.
            None => (
                format!(
                    "cannot assign to `{field}` through `{receiver_ty}`: a union receiver has \
                     no single field layout to write"
                ),
                None,
            ),
        };
        let mut help = Vec::new();
        match missing {
            Some(m) => {
                help.push(self.format_definition(&m));
                help.push(union_narrow_help(receiver_ty));
            }
            // Every member carries the field, so the shared narrow-first advice
            // is wrong here: `"f" in x` discriminates nothing.
            None => help.push(self.union_write_fix_help(
                recv_span,
                field,
                receiver_ty,
                members,
                recv_path,
                rw_op,
            )),
        }
        self.error_with_help(name.span, message, help);
    }

    /// The shape a write to `field` on this receiver is typed against, whatever
    /// rejected the write — including where no edit could make it legal, since a
    /// `readonly` field still says what a value written to it would have to be.
    /// `None` only when no member names a shape.
    ///
    /// `null` comes off first: adding `| null` to a receiver must not change what
    /// its value is checked against. Stripping is identity on a null-free type,
    /// so both reporters can share this.
    pub(super) fn write_target_ty(&self, receiver_ty: &Type, field: &str) -> Option<Type> {
        match narrowing::strip_nullish(receiver_ty) {
            Type::Union(members) => self.members_agree_on_write_ty(&members, field),
            single => self.union_member_field_write(&single, field).map(|w| w.ty),
        }
    }

    /// Every write receiver that is not a union of field-bearing members — a
    /// primitive, a nullable, or a union one of whose members carries no fields.
    /// None of them is helped by the `instanceof` advice
    /// [`report_unassignable_field_target`](Self::report_unassignable_field_target)
    /// gives a union.
    ///
    /// `null` is the one with a fix of its own, so it is answered here and
    /// anchored at the field, as the union messages are.
    fn report_non_union_field_write(
        &mut self,
        recv_span: Span,
        name: &crate::Ident,
        receiver_ty: &Type,
        recv_path: Option<&narrowing::ReferencePath>,
        rw_op: Option<RwOp>,
    ) {
        match self.nullable_receiver_fix(
            recv_span,
            recv_path,
            receiver_ty,
            &name.name,
            MemberSide::Write(rw_op),
        ) {
            Some(fix) => self.error_with_help(
                name.span,
                format!(
                    "cannot assign to field `{}` of `{receiver_ty}`: the receiver can be {}",
                    name.name,
                    Absence::of(receiver_ty).describe(),
                ),
                vec![fix],
            ),
            // Nothing to narrow and no member to name, so this keeps the
            // receiver anchor; the union messages name the field and anchor at
            // it, as the read side does.
            None => self.error(
                recv_span,
                format!("cannot assign to field of `{receiver_ty}`"),
            ),
        }
    }

    /// How to reach a non-null receiver, for a member access on either side of
    /// the assignment. `None` when the null is not what blocks the access.
    ///
    /// Claimed only when removing `null` makes *this* access legal — see
    /// [`access_after_nullish`](Self::access_after_nullish). Advice that lands on a
    /// second rejection is worse than the generic message it replaces, and it
    /// also costs the reader the type dump that message carries.
    fn nullable_receiver_fix(
        &self,
        recv_span: Span,
        recv_path: Option<&narrowing::ReferencePath>,
        receiver_ty: &Type,
        field: &str,
        side: MemberSide,
    ) -> Option<String> {
        if !spells_nullish(receiver_ty) {
            return None;
        }
        let access =
            self.access_after_nullish(&narrowing::strip_nullish(receiver_ty), field, side)?;
        let recv = self.rewritable_snippet(recv_span);
        let member = format!("{field}{}", access.call_suffix());
        let (nonnull_rewrite, guard_body) = match side {
            MemberSide::Read => (
                format!(
                    "read it as `{recv}?.{member}`, or assert non-null with `{recv}!.{member}`"
                ),
                format!("{{ … {recv}.{member} … }}"),
            ),
            MemberSide::Write(op) => (
                format!(
                    "assert non-null with `{}`",
                    write_form(&format!("{recv}!.{member}"), op),
                ),
                format!("{{ {} }}", write_form(&format!("{recv}.{member}"), op),),
            ),
        };
        // `!` and `?.` rewrite the access itself, so they hold whatever the
        // receiver is. A guard is different: it installs a narrowing, and only a
        // place can hold one — the same rule `union_write_fix_help` follows, and
        // the reason it asks for a `const` binding rather than printing a test
        // that compiles and then narrows nothing.
        let bind_first = format!(
            "bind {} to a `const` first and guard that, or {nonnull_rewrite}",
            match self.rewritable_text(recv_span) {
                Some(place) => format!("`{place}`"),
                None => "the receiver".to_string(),
            },
        );
        Some(match self.receiver_place(recv_path) {
            ReceiverPlace::Narrowable => {
                format!(
                    "guard first — `if ({}) {guard_body}` — or {nonnull_rewrite}",
                    Absence::of(receiver_ty).guard(&recv),
                )
            }
            ReceiverPlace::BindFirst(reason) => format!("{reason} — {bind_first}"),
            // Some pathless receivers narrow fine and some cannot, so the advice
            // true of both is to bind first.
            ReceiverPlace::Unmodeled => bind_first,
        })
    }

    /// What `field` resolves to on the receiver once `null` is removed, or
    /// `None` when the non-null half rejects the access for its own reason.
    ///
    /// Field-*bearing* is not a strong enough test: a guard is only the fix if
    /// the access succeeds on the other side of it, and several shapes are
    /// field-bearing and fail anyway.
    fn access_after_nullish(
        &self,
        stripped: &Type,
        field: &str,
        side: MemberSide,
    ) -> Option<NonNullAccess> {
        let backs_field =
            |receiver: &Type| self.union_member_field_read_ty(receiver, field).is_ok();
        match (side, stripped) {
            (MemberSide::Read, Type::Union(members)) => members
                .iter()
                .all(backs_field)
                .then_some(NonNullAccess::Field),
            (MemberSide::Read, single) => {
                if let Some((sig, ..)) = self.find_method(single, field) {
                    return Some(NonNullAccess::Method {
                        // An optional or rest parameter need not be passed, so a
                        // rewrite showing `(…)` for one would ask the reader to
                        // invent an argument list they do not owe.
                        takes_args: sig.params.iter().any(|p| !p.is_omittable() && !p.rest),
                    });
                }
                // `lookup_interface_property` rather than `find_property`: the
                // latter declines a VTable-dispatched interface, and this asks
                // only whether the read resolves, not how it lowers. Without it
                // the three commonest nullable receivers in generated code —
                // `T[] | null`, `string | null`, `Map<K, V> | null` — miss the
                // gate on `.length` / `.size`, which are properties rather than
                // fields.
                (backs_field(single) || self.lookup_interface_property(single, field).is_some())
                    .then_some(NonNullAccess::Field)
            }
            (MemberSide::Write(_), Type::Union(_)) => None,
            // Permission, not shape.
            (MemberSide::Write(_), single) => self
                .union_member_field_writable(single, field)
                .then_some(NonNullAccess::Field),
        }
    }

    /// How to reach a writable single-member view of a union whose members all
    /// declare the field.
    ///
    /// Every branch names a form that actually compiles *in this module*; each
    /// constraint on that lives with the helper that checks it.
    fn union_write_fix_help(
        &self,
        recv_span: Span,
        field: &str,
        receiver_ty: &Type,
        members: &[Type],
        recv_path: Option<&narrowing::ReferencePath>,
        rw_op: Option<RwOp>,
    ) -> String {
        if !members
            .iter()
            .any(|m| self.union_member_field_writable(m, field))
        {
            return format!(
                "`{field}` is readonly on every member; no narrowing makes it writable"
            );
        }
        let recv = self.rewritable_snippet(recv_span);
        // Writable *and* spellable here: the two together are what make a named
        // member usable in the `as` or `instanceof` the help is about to print.
        let nameable: Vec<&Type> = members
            .iter()
            .filter(|m| self.union_member_field_writable(m, field) && self.name_resolves_here(m))
            .collect();
        let cast = self
            .members_agree_on_write_ty(members, field)
            .and_then(|_| {
                nameable
                    .iter()
                    .find(|m| self.is_legal_cast_target(receiver_ty, m))
            })
            .map(|m| {
                format!(
                    "write through a checked cast — `{}`",
                    write_form(&format!("({recv} as {m}).{field}"), rw_op),
                )
            });
        let guard = self.narrowing_guard(&recv, members, field, &nameable);
        let narrow_only = format!("narrow `{recv}` to one member first");
        let primary = match self.receiver_place(recv_path) {
            ReceiverPlace::BindFirst(reason) => {
                format!("{reason} — bind `{recv}` to a `const` first, then narrow that")
            }
            // Some pathless receivers narrow fine (`x!`) and some cannot (a call
            // result), so binding first is named only when a guard exists to
            // follow it — the one advice true of both.
            ReceiverPlace::Unmodeled if guard.is_some() => {
                format!("bind `{recv}` to a `const` first, then narrow that")
            }
            ReceiverPlace::Unmodeled => narrow_only,
            ReceiverPlace::Narrowable => match guard {
                Some(guard) => format!(
                    "narrow to one member first — `{guard} {{ {} }}`",
                    write_form(&format!("{recv}.{field}"), rw_op),
                ),
                None => narrow_only,
            },
        };
        or_cast(primary, cast.as_deref())
    }

    /// Syntax alone does not answer this: a plain identifier the narrowing
    /// engine refuses to install a view for — one a closure reassigns — reads as
    /// a place and narrows like an element, so naming a guard for it hands back
    /// the line that just failed.
    fn receiver_place(&self, path: Option<&narrowing::ReferencePath>) -> ReceiverPlace {
        let Some(path) = path else {
            return ReceiverPlace::Unmodeled;
        };
        if matches!(path.chain.last(), Some(narrowing::PathElem::Index(_))) {
            return ReceiverPlace::BindFirst("an element is not a place a guard can narrow");
        }
        if self.path_root_is_captured_mutator(path) {
            return ReceiverPlace::BindFirst(
                "a variable a closure reassigns cannot hold a narrowing",
            );
        }
        ReceiverPlace::Narrowable
    }

    /// The shape every member gives a write to `field`, or `None` where they
    /// disagree or no member carries the field.
    ///
    /// Gates the cast advice — a cast names one member, so offering one where the
    /// members disagree hands back a form that compiles and then rejects the
    /// value. It is also the type a rejected write checks its right-hand side
    /// against.
    ///
    /// Agreement is over the members a write could actually go through: a
    /// `readonly` member can never be the cast's target, so letting it veto the
    /// others costs the cast *and* the shape. Where no member is writable there
    /// is nothing to prefer, and every member's shape counts — the write is
    /// doomed either way, and the value still has to be typed against something.
    fn members_agree_on_write_ty(&self, members: &[Type], field: &str) -> Option<Type> {
        let writes: Vec<FieldWrite> = members
            .iter()
            .filter_map(|m| self.union_member_field_write(m, field))
            .collect();
        let mut considered: Vec<&FieldWrite> = writes.iter().filter(|w| w.writable).collect();
        if considered.is_empty() {
            considered = writes.iter().collect();
        }
        let first = considered.first()?;
        considered
            .iter()
            .all(|w| w.ty == first.ty)
            .then(|| first.ty.clone())
    }

    /// The `if (…)` a reader can write to reach one member of this union, or
    /// `None` when no test distinguishes them and only a cast will do.
    ///
    /// A discriminant is read from *every* member — the test compares a field
    /// they all carry, so a member this module cannot name is no obstacle.
    /// `instanceof` has to name a class, so it draws from `nameable` only. It is
    /// preferred over the cast wherever such a class exists, including in a union
    /// that also holds interfaces, where it still narrows: a guard that picks the
    /// wrong member merely fails its test, while a cast that picks the wrong
    /// member traps.
    fn narrowing_guard(
        &self,
        recv: &str,
        members: &[Type],
        field: &str,
        nameable: &[&Type],
    ) -> Option<String> {
        if let Some((discriminant, variants)) = self.union_discriminant_with_nominals(members) {
            // Name a literal whose own member is writable — a bare `…` lets a
            // reader pick the branch where the field is `readonly`, which narrows
            // correctly and then rejects the write. Spellability is deliberately
            // not required: the literal is what the test compares, and it needs
            // no type name. A literal that names several members (`undefined`
            // with optional discriminants) doesn't narrow to one, so it's skipped.
            let value = variants.iter().find_map(|(literal, _)| {
                let only = variants.get(literal)?;
                let member = members.get(only.0 as usize)?;
                self.union_member_field_writable(member, field)
                    .then(|| render_literal(literal))
            });
            let value = value.unwrap_or_else(|| "…".to_string());
            return Some(format!("if ({recv}.{discriminant} === {value})"));
        }
        // `instanceof` tests the class itself — type arguments are erased, and
        // `instanceof A<string>` is rejected — so name the bare class.
        nameable.iter().find_map(|m| match m.peel() {
            Type::ClassRef { name, .. } => Some(format!("if ({recv} instanceof {name})")),
            _ => None,
        })
    }

    pub(super) fn interface_member_miss_help(&self, receiver_ty: &Type, name: &str) -> Vec<String> {
        let mut help = Vec::new();
        if let Some((mangled, _, iface_name, _)) = receiver_ty.interface_routing()
            && let Some(sym) = self.lookup_structural_type(&mangled, iface_name)
        {
            let candidates: Vec<&str> = match &sym.kind {
                TypeKind::Interface {
                    methods,
                    properties,
                    ..
                } => methods
                    .keys()
                    .chain(properties.keys())
                    .map(String::as_str)
                    .collect(),
                // Suggest only public members at miss sites; private members of
                // a class from another module are invisible (docs/classes.md §3).
                TypeKind::Class {
                    methods,
                    method_visibility,
                    fields,
                    ..
                } => methods
                    .keys()
                    .filter(|m| {
                        method_visibility.get(*m).copied() != Some(crate::Visibility::Private)
                    })
                    .chain(
                        fields
                            .iter()
                            .filter(|(_, f)| f.visibility != crate::Visibility::Private)
                            .map(|(n, _)| n),
                    )
                    .map(String::as_str)
                    .collect(),
                _ => Vec::new(),
            };
            if let Some(suggestion) = did_you_mean::closest_match(name, candidates) {
                help.push(format!("did you mean `{suggestion}`?"));
            }
        }
        help.push(self.format_definition(receiver_ty));
        help
    }

    /// Build the fix trio for a nullable value in a string context —
    /// the runtime-checked `!` assert, a `??` fallback, and narrowing —
    /// each rewritten against the offending expression's source text so
    /// the model can apply one verbatim.
    pub(super) fn nullish_string_fix_help(&self, expr_span: Span, ty: &Type) -> Vec<String> {
        let expr = self.rewritable_snippet(expr_span);
        vec![format!(
            "use a non-null value:\n\
             \x20 `{expr}!.toString()` — assert non-null (throws `TypeError` at runtime if it is not)\n\
             \x20 `({expr} ?? \"fallback\").toString()` — provide a fallback\n\
             \x20 `String({expr})` — convert it, `null` included\n\
             \x20 or narrow first: `if ({}) {{ … }}`",
            Absence::of(ty).guard(&expr),
        )]
    }

    /// Remove the generic "expected `T`, got `U`" an expression reported under
    /// its contextual type, when the caller reports the same mismatch better.
    pub(super) fn drop_contextual_mismatch(&mut self, span: Span, expected: &Type, got: &Type) {
        let message = mismatch_message(&expected, &got);
        if let Some(index) = self
            .diagnostics
            .iter()
            .rposition(|diagnostic| diagnostic.span == span && diagnostic.message == message)
        {
            self.diagnostics.remove(index);
        }
    }

    /// Source text of `span`, ready to take a postfix `!` or a trailing
    /// `?? …`: simple reference paths pass through verbatim, other
    /// single-line expressions are parenthesized to stay
    /// precedence-correct, and anything unrenderable falls back to `x`.
    pub(super) fn rewritable_snippet(&self, span: Span) -> String {
        self.rewritable_text(span)
            .unwrap_or_else(|| "x".to_string())
    }

    /// Source text of `span` if it can be rendered at all, `None` otherwise.
    ///
    /// [`rewritable_snippet`](Self::rewritable_snippet) substitutes `x` for the
    /// `None`, which reads correctly inside a code sample (`x?.f`) and wrongly
    /// in prose that points at a binding — "bind `x` to a `const`" names a
    /// variable the reader does not have. Advice of the second kind asks here.
    fn rewritable_text(&self, span: Span) -> Option<String> {
        let text = self.source.get(span.start as usize..span.end as usize)?;
        if text.is_empty() || text.len() > 60 || text.contains('\n') {
            return None;
        }
        let is_path_char =
            |c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '$' | '.' | '[' | ']');
        if text.chars().all(is_path_char) {
            Some(text.to_string())
        } else {
            Some(format!("({text})"))
        }
    }

    /// Validate a condition expression's type, preferring
    /// the "narrow first" diagnostic when the type is `unknown`
    /// (forcing the LLM toward `typeof` / `x === null` /
    /// `Array.isArray(x)` rather than puzzling over a generic
    /// "expected boolean" mismatch). Otherwise defers to
    /// [`condition_compatible`](super::narrowing::condition_compatible).
    pub(super) fn check_condition_ty(&mut self, ty: &Type, span: Span) {
        if matches!(ty.peel(), Type::Unknown) {
            self.error_with_help(
                span,
                "cannot use `unknown` as a condition".to_string(),
                vec![
                    "narrow first with `typeof x === \"…\"`, `x === null`, \
                     or `Array.isArray(x)` before using as a condition"
                        .to_string(),
                ],
            );
        } else if !super::narrowing::condition_compatible(ty) {
            self.error_non_condition_type(span, ty);
        }
    }
}

/// The narrow-first advice every union member-access diagnostic ends on. One
/// definition so the read and write sides cannot name different fixes for the
/// same receiver.
fn union_narrow_help(receiver_ty: &Type) -> String {
    format!(
        "narrow `{receiver_ty}` to one member first — `instanceof`, a discriminant \
         field, or `\"<field>\" in x`"
    )
}

/// How a receiver relates to the guards that could narrow it.
enum ReceiverPlace {
    /// A place the narrowing engine will refuse a view for, carrying the reason
    /// so the help can say which refusal this is. Binding to a `const` escapes
    /// every one of them.
    BindFirst(&'static str),
    /// No path form at all. Some of these narrow fine (`x!`) and some cannot
    /// (a call result); the path model does not say which, so nothing about the
    /// receiver may be asserted.
    Unmodeled,
    /// A path a guard can bind a shadow for — an identifier or a field path.
    Narrowable,
}

/// Appends the cast as an alternative to whatever fix was named first. One
/// definition so the two sites that offer it cannot punctuate it differently.
fn or_cast(primary: String, cast: Option<&str>) -> String {
    match cast {
        Some(cast) => format!("{primary}, or {cast}"),
        None => primary,
    }
}

/// A discriminant's literal value, spelled as source.
fn render_literal(literal: &narrowing::LiteralValue) -> String {
    match literal {
        narrowing::LiteralValue::String(s) => format!("{s:?}"),
        narrowing::LiteralValue::Number(n) => crate::runtime::number::format_number_js(n.0),
        narrowing::LiteralValue::Boolean(b) => b.to_string(),
        narrowing::LiteralValue::BigInt(digits) => format!("{digits}n"),
        narrowing::LiteralValue::Null => "null".to_string(),
        narrowing::LiteralValue::Undefined => "undefined".to_string(),
    }
}

#[cfg(test)]
mod dropped_guard_tests {
    use super::super::test_support::run;

    // A guard through a key whose declared type can't index, which the
    // narrowing source can't rebuild from declared types.
    const TYPES: &str = "class Leaf { z: number | null = 3; }\n\
        const key: string | null = \"k\";\n\
        class Holder { leaves: Record<string, Leaf> = {}; }\n";

    #[test]
    fn dropped_guard_hint_stays_in_its_branch() {
        for (condition, guarded_arm) in [
            (
                "key !== null && h.leaves[key] !== undefined && h.leaves[key].z !== null",
                "thenValue",
            ),
            (
                "key === null || h.leaves[key] === undefined || h.leaves[key].z === null",
                "elseValue",
            ),
        ] {
            let source = format!(
                "{TYPES}
                function main(): void {{
                    const h = new Holder();
                    if ({condition}) {{
                        const thenValue: number = h.leaves[key].z;
                    }} else {{
                        const elseValue: number = h.leaves[key].z;
                    }}
                    const afterValue: number = h.leaves[key].z;
                }}"
            );
            let (_, diagnostics) = run(&source);
            let hints: Vec<_> = diagnostics
                .iter()
                .filter(|diagnostic| {
                    diagnostic
                        .help
                        .iter()
                        .any(|help| help.contains("cannot preserve this guard"))
                })
                .collect();
            assert_eq!(hints.len(), 1, "{diagnostics:?}");
            let guarded_line = source
                .lines()
                .find(|line| line.contains(guarded_arm))
                .unwrap();
            let expected_start = source.find(guarded_line).unwrap();
            assert!(
                hints[0].span.start as usize >= expected_start,
                "{diagnostics:?}"
            );
            assert!(
                (hints[0].span.start as usize) < expected_start + guarded_line.len(),
                "{diagnostics:?}"
            );
        }
    }

    #[test]
    fn early_return_keeps_the_surviving_outcomes_drop() {
        let source = format!(
            "{TYPES}
            function main(): number {{
                const h = new Holder();
                if (key === null || h.leaves[key] === undefined || h.leaves[key].z === null) return 0;
                return h.leaves[key].z;
            }}"
        );
        let (_, diagnostics) = run(&source);
        assert!(
            diagnostics.iter().any(|diagnostic| {
                diagnostic
                    .help
                    .iter()
                    .any(|help| help.contains("cannot preserve this guard"))
            }),
            "{diagnostics:?}"
        );
    }

    #[test]
    fn branch_join_keeps_only_a_common_dropped_refinement() {
        for (else_guard, expected_hint) in [
            (
                "if (key === null || h.leaves[key] === undefined || h.leaves[key].z === null) return 0;",
                true,
            ),
            ("", false),
        ] {
            let source = format!(
                "{TYPES}
                function read(h: Holder, flag: boolean): number {{
                    if (flag) {{
                        if (key === null || h.leaves[key] === undefined || h.leaves[key].z === null) return 0;
                    }} else {{ {else_guard} }}
                    return h.leaves[key].z;
                }}"
            );
            let (_, diagnostics) = run(&source);
            let has_hint = diagnostics.iter().any(|diagnostic| {
                diagnostic
                    .help
                    .iter()
                    .any(|help| help.contains("cannot preserve this guard"))
            });
            assert_eq!(has_hint, expected_hint, "{diagnostics:?}");
        }
    }

    #[test]
    fn condition_without_a_branch_cannot_leak_a_drop() {
        let source = format!(
            "{TYPES}
            function first(): void {{
                const h = new Holder();
                do {{}} while (key !== null && h.leaves[key] !== undefined && h.leaves[key].z !== null);
                const read = (): number => h.leaves[key].z;
            }}
            function second(): number {{
                const h = new Holder();
                return h.leaves[key].z;
            }}"
        );
        let (_, diagnostics) = run(&source);
        assert!(!diagnostics.is_empty());
        assert!(
            !diagnostics.iter().any(|diagnostic| {
                diagnostic
                    .help
                    .iter()
                    .any(|help| help.contains("cannot preserve this guard"))
            }),
            "{diagnostics:?}"
        );
    }
}

#[cfg(test)]
mod help_rendering_tests {
    use super::super::test_support::with_inferer;
    use crate::type_size::TypeTooLarge;

    #[test]
    fn invalid_rendering_is_fatal_at_the_checkpoint() {
        with_inferer(|tc| {
            let text = tc.render_help(Err(crate::rendering::RenderError::InvalidMetadata(
                "injected",
            )));
            assert_eq!(text, "[diagnostic help unavailable]");
            assert!(matches!(
                tc.type_size_checkpoint(None),
                Err(crate::compiler_error::CompilerFailure::Internal { .. })
            ));
        });
    }

    #[test]
    fn a_limit_pending_before_rendering_is_kept() {
        with_inferer(|tc| {
            tc.type_limits.record(TypeTooLarge::Depth);
            let text = tc.render_help(Ok("rendered".into()));
            assert_eq!(text, "rendered");
            assert_eq!(tc.type_limits.take(), Err(TypeTooLarge::Depth));
        });
    }
}