monty 0.0.21

A sandboxed, snapshotable Python interpreter written in Rust.
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
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
use std::{
    borrow::Cow,
    fmt::{self, Display, Write},
};

use monty_types::{ExcData, JsonErrorData, MontyException, StackFrame, UnicodeErrorData};
use smallvec::smallvec;

use crate::{
    args::ArgValues,
    bytecode::{CallResult, VM},
    defer_drop,
    fstring::{FormatError, ascii_escape},
    heap::{HeapData, HeapRead},
    intern::{Interns, StaticStrings, StringId},
    parse::CodeRange,
    source_map::{SourceMap, StackFrameExt},
    types::{
        PyTrait, Type, allocate_tuple,
        long_int::INT_MAX_STR_DIGITS,
        str::{StringRepr, allocate_string, string_repr_fmt},
    },
    value::{EitherStr, Value},
};

/// Result type alias for operations that can produce a runtime error.
pub type RunResult<T> = Result<T, RunError>;

pub use monty_types::{ExcType, unicode_decode_error_msg};

/// Crate-internal error constructors on [`ExcType`].
///
/// `ExcType` itself lives in `monty-types`; these constructors build
/// interpreter-side [`RunError`]s (which carry raw stack frames), so they
/// stay in `monty` as a `pub(crate)` extension trait with default bodies.
/// Import the trait to call them as `ExcType::type_error(...)`.
pub(crate) trait ExcTypeExt: Sized {
    /// Creates an exception instance from an exception type and arguments,
    /// handling constructor calls like `ValueError('message')`.
    fn call(self, vm: &mut VM<'_>, args: ArgValues) -> RunResult<Value>;

    /// Creates an AttributeError for when an attribute is not found (GET operation).
    ///
    /// Sets `hide_caret: true` because CPython doesn't show carets for attribute GET errors.
    #[must_use]
    fn attribute_error(type_name: impl Display, attr: &str) -> RunError {
        let exc = SimpleException::new_msg(
            ExcType::AttributeError,
            format!("'{type_name}' object has no attribute '{attr}'"),
        );
        RunError::Exc(ExceptionRaise {
            exc,
            frame: None,
            hide_caret: true, // CPython doesn't show carets for attribute GET errors
        })
    }

    /// Creates an AttributeError for a missing attribute on a class object.
    ///
    /// Matches CPython's wording for type objects: `type object 'Foo' has no
    /// attribute 'nope'` (instances use [`Self::attribute_error`] instead).
    /// Sets `hide_caret: true` because CPython doesn't show carets for attribute GET errors.
    #[must_use]
    fn attribute_error_type(class_name: &str, attr: &str) -> RunError {
        let exc = SimpleException::new_msg(
            ExcType::AttributeError,
            format!("type object '{class_name}' has no attribute '{attr}'"),
        );
        RunError::Exc(ExceptionRaise {
            exc,
            frame: None,
            hide_caret: true, // CPython doesn't show carets for attribute GET errors
        })
    }

    /// Creates an AttributeError for attribute assignment on types that don't support it.
    ///
    /// Matches CPython's format for setting attributes on built-in types.
    #[must_use]
    fn attribute_error_no_setattr(type_: &str, attr_name: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::AttributeError,
            format!("'{type_}' object has no attribute '{attr_name}' and no __dict__ for setting new attributes"),
        )
        .into()
    }

    /// Creates an AttributeError for a missing module attribute.
    ///
    /// Matches CPython's format: `AttributeError: module 'name' has no attribute 'attr'`
    /// Sets `hide_caret: true` because CPython doesn't show carets for attribute GET errors.
    #[must_use]
    fn attribute_error_module(module_name: &str, attr_name: &str) -> RunError {
        let exc = SimpleException::new_msg(
            ExcType::AttributeError,
            format!("module '{module_name}' has no attribute '{attr_name}'"),
        );
        RunError::Exc(ExceptionRaise {
            exc,
            frame: None,
            hide_caret: true, // CPython doesn't show carets for attribute GET errors
        })
    }

    #[must_use]
    fn type_error_not_sub(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not subscriptable")).into()
    }

    /// Creates the TypeError for an ordering comparison (`<`, `<=`, `>`, `>=`)
    /// between values whose types define no ordering, e.g. `1 < 'a'` or two
    /// instances of a user class without comparison dunders.
    ///
    /// Matches CPython's format:
    /// `TypeError: '{op}' not supported between instances of '{left}' and '{right}'`
    #[must_use]
    fn type_error_ordering(operator: &str, left_type: &str, right_type: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("'{operator}' not supported between instances of '{left_type}' and '{right_type}'"),
        )
        .into()
    }

    /// Creates a TypeError for awaiting a non-awaitable object.
    ///
    /// Matches CPython's format: `TypeError: '{type}' object can't be awaited`
    #[must_use]
    fn object_not_awaitable(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object can't be awaited")).into()
    }

    /// Creates the canonical `RuntimeError: cannot reuse already awaited coroutine`,
    /// raised on direct re-await and on cross-gather coroutine reuse.
    #[must_use]
    fn cannot_reuse_already_awaited_coroutine() -> RunError {
        SimpleException::new_msg(ExcType::RuntimeError, "cannot reuse already awaited coroutine").into()
    }

    /// Creates a TypeError for item assignment on types that don't support it.
    ///
    /// Matches CPython's format: `TypeError: '{type}' object does not support item assignment`
    #[must_use]
    fn type_error_not_sub_assignment(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("'{type_}' object does not support item assignment"),
        )
        .into()
    }

    /// Creates a TypeError for unhashable types when calling `hash()`.
    ///
    /// This matches Python 3.14's error message: `TypeError: unhashable type: 'list'`
    #[must_use]
    fn type_error_unhashable(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("unhashable type: '{type_}'")).into()
    }

    /// Creates a TypeError for unhashable types used as dict keys.
    ///
    /// This matches Python 3.14's error message:
    /// `TypeError: cannot use 'list' as a dict key (unhashable type: 'list')`
    #[must_use]
    fn type_error_unhashable_dict_key(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("cannot use '{type_}' as a dict key (unhashable type: '{type_}')"),
        )
        .into()
    }

    /// Creates a TypeError for an unhashable value used as a set element.
    #[must_use]
    fn type_error_unhashable_set_element(element_type: &str, unhashable_type: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("cannot use '{element_type}' as a set element (unhashable type: '{unhashable_type}')"),
        )
        .into()
    }

    /// Creates a KeyError for a missing dict key.
    ///
    /// For string keys, uses the raw string value without extra quoting.
    /// If the key's string conversion fails (e.g. huge LongInt exceeding
    /// `INT_MAX_STR_DIGITS`), falls back to the type name so that a
    /// `KeyError` is always raised rather than a spurious `ValueError`.
    fn key_error(key: &Value, vm: &mut VM<'_>) -> RunError {
        let key_str = match key.py_str(vm) {
            Ok(key_value) => {
                // `key_value` is a heap `str` `Value`; extract its text and drop it.
                defer_drop!(key_value, vm);
                if let Ok(s) = key_value.to_str(vm) {
                    s.to_owned()
                } else {
                    format!("<{}>", key.py_type_name(vm))
                }
            }
            Err(_) => format!("<{}>", key.py_type_name(vm)),
        };
        SimpleException::new_msg(ExcType::KeyError, key_str).into()
    }

    /// Creates a KeyError for popping from an empty set.
    ///
    /// Matches CPython's error format: `KeyError: 'pop from an empty set'`
    #[must_use]
    fn key_error_pop_empty_set() -> RunError {
        SimpleException::new_msg(ExcType::KeyError, "pop from an empty set").into()
    }

    /// Creates a TypeError for when a function receives the wrong number of arguments.
    ///
    /// Matches CPython's error format exactly:
    /// - For 1 expected arg: `{name}() takes exactly one argument ({actual} given)`
    /// - For N expected args: `{name} expected {expected} arguments, got {actual}`
    ///
    /// # Arguments
    /// * `name` - The function name (e.g., "len" for builtins, "list.append" for methods)
    /// * `expected` - Number of expected arguments
    /// * `actual` - Number of arguments actually provided
    #[must_use]
    fn type_error_arg_count(name: &str, expected: usize, actual: usize) -> RunError {
        if expected == 1 {
            // CPython: "len() takes exactly one argument (2 given)"
            SimpleException::new_msg(
                ExcType::TypeError,
                format!("{name}() takes exactly one argument ({actual} given)"),
            )
            .into()
        } else {
            // CPython: "insert expected 2 arguments, got 1"
            SimpleException::new_msg(
                ExcType::TypeError,
                format!("{name} expected {expected} arguments, got {actual}"),
            )
            .into()
        }
    }

    /// Creates a TypeError for when a method that takes no arguments receives some.
    ///
    /// Matches CPython's format: `{name}() takes no arguments ({actual} given)`
    ///
    /// # Arguments
    /// * `name` - The method name (e.g., "dict.keys")
    /// * `actual` - Number of arguments actually provided
    #[must_use]
    fn type_error_no_args(name: &str, actual: usize) -> RunError {
        // CPython: "dict.keys() takes no arguments (1 given)"
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() takes no arguments ({actual} given)"),
        )
        .into()
    }

    /// Creates a TypeError for when a function receives fewer arguments than required.
    ///
    /// Matches CPython's format: `{name} expected at least {min} argument, got {actual}`
    ///
    /// # Arguments
    /// * `name` - The function name (e.g., "get", "pop")
    /// * `min` - Minimum number of required arguments
    /// * `actual` - Number of arguments actually provided
    #[must_use]
    fn type_error_at_least(name: &str, min: usize, actual: usize) -> RunError {
        // CPython: "get expected at least 1 argument, got 0"
        let plural = if min == 1 { "" } else { "s" };
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name} expected at least {min} argument{plural}, got {actual}"),
        )
        .into()
    }

    /// Creates a TypeError for when a function receives more arguments than allowed.
    ///
    /// Matches CPython's `PyArg_UnpackTuple` format:
    /// - `{name} expected at most {max} argument, got {actual}` (singular when max=1)
    /// - `{name} expected at most {max} arguments, got {actual}` (plural otherwise)
    ///
    /// # Arguments
    /// * `name` - The function name (e.g., "get", "pop")
    /// * `max` - Maximum number of allowed arguments
    /// * `actual` - Number of arguments actually provided
    #[must_use]
    fn type_error_at_most(name: &str, max: usize, actual: usize) -> RunError {
        let plural = if max == 1 { "" } else { "s" };
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name} expected at most {max} argument{plural}, got {actual}"),
        )
        .into()
    }

    /// Creates a TypeError for a `startswith`/`endswith` affix argument that is
    /// neither the expected string type nor a tuple.
    ///
    /// Matches CPython: `{method} first arg must be {expected} or a tuple of {expected}, not {type}`
    /// (`expected` is `str` for `str` methods, `bytes` for `bytes` methods).
    #[must_use]
    fn type_error_affix_arg(method: &str, expected: &str, type_name: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{method} first arg must be {expected} or a tuple of {expected}, not {type_name}"),
        )
        .into()
    }

    /// Creates a TypeError for a non-string element in a `startswith`/`endswith`
    /// affix tuple.
    ///
    /// Matches CPython: `tuple for {method} must only contain {expected}, not {type}`.
    /// Raised lazily while matching — elements after a successful match are never checked.
    #[must_use]
    fn type_error_affix_tuple_item(method: &str, expected: &str, type_name: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("tuple for {method} must only contain {expected}, not {type_name}"),
        )
        .into()
    }

    /// Creates a TypeError for too many arguments to a method or named function.
    ///
    /// Matches CPython's format for method-style calls:
    /// `{name}() takes at most {max} argument ({actual} given)` (singular when max=1)
    /// `{name}() takes at most {max} arguments ({actual} given)` (plural otherwise)
    ///
    /// Both C parsers insert `keyword ` before `argument` when the call passed
    /// no positionals at all (`nargs == 0` in `vgetargskeywords` /
    /// `vgetargskeywordsfast_impl`), so pass `all_keyword` accordingly:
    /// `fspath() takes at most 1 keyword argument (2 given)`.
    ///
    /// Use this instead of `type_error_at_most` for methods and type constructors that
    /// CPython formats with parentheses, e.g. `now()`, `timezone()`, `expandtabs()`.
    #[must_use]
    fn type_error_method_at_most(name: &str, max: usize, actual: usize, all_keyword: bool) -> RunError {
        let kind = if all_keyword { "keyword " } else { "" };
        let plural = if max == 1 { "" } else { "s" };
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() takes at most {max} {kind}argument{plural} ({actual} given)"),
        )
        .into()
    }

    /// Creates a TypeError for too few positional arguments to a method-style call.
    ///
    /// Matches CPython's format used by methods like `str.replace`:
    /// `{name}() takes at least {min} positional argument ({actual} given)` (singular when min=1)
    /// `{name}() takes at least {min} positional arguments ({actual} given)` (plural otherwise)
    ///
    /// Distinct from [`type_error_at_least`] which uses CPython's
    /// `PyArg_UnpackTuple` wording (no parens, no "positional"). Emitted by
    /// `FromArgs` for any struct with required positional-only fields,
    /// matching CPython's C-method `_PyArg_UnpackKeywords` dispatch.
    #[must_use]
    fn type_error_at_least_positional(name: &str, min: usize, actual: usize) -> RunError {
        let plural = if min == 1 { "" } else { "s" };
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() takes at least {min} positional argument{plural} ({actual} given)"),
        )
        .into()
    }

    /// Creates the bespoke `map()` arity error that CPython hard-codes.
    ///
    /// CPython's `map()` uses a single fixed message regardless of whether
    /// 0 or 1 args were given: `map() must have at least two arguments.`
    /// (note the trailing period). We mirror it here so `map()` / `map(f)`
    /// match byte-for-byte rather than falling through to the generic
    /// "missing N required positional arguments" wording the macro would
    /// otherwise emit.
    #[must_use]
    fn type_error_map_arity() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "map() must have at least two arguments.".to_owned()).into()
    }

    /// Creates a TypeError for exact-arity functions reporting too many *or* too few.
    ///
    /// Matches CPython's `PyArg_UnpackTuple` wording for fixed-arity callables
    /// (e.g. `sorted`):
    /// `{name} expected {exact} argument, got {actual}` (singular when exact=1)
    /// `{name} expected {exact} arguments, got {actual}` (plural otherwise)
    ///
    /// Use this for the macro's `expected_exact` attribute.
    #[must_use]
    fn type_error_expected_exact(name: &str, exact: usize, actual: usize) -> RunError {
        let plural = if exact == 1 { "" } else { "s" };
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name} expected {exact} argument{plural}, got {actual}"),
        )
        .into()
    }

    /// Creates a TypeError for missing positional arguments.
    ///
    /// Matches CPython's format: `{name}() missing {count} required positional argument(s): 'a' and 'b'`
    #[must_use]
    fn type_error_missing_positional_with_names(name: &str, missing_names: &[&str]) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, Self::missing_positional_msg(name, missing_names)).into()
    }

    /// Message body for [`type_error_missing_positional_with_names`], exposed
    /// separately so `args/bind_python.rs` can attach a call position to the same
    /// CPython-exact wording.
    #[must_use]
    fn missing_positional_msg(name: &str, missing_names: &[&str]) -> String {
        let count = missing_names.len();
        let names_str = format_param_names(missing_names);
        if count == 1 {
            format!("{name}() missing 1 required positional argument: {names_str}")
        } else {
            format!("{name}() missing {count} required positional arguments: {names_str}")
        }
    }

    /// Creates a TypeError for missing keyword-only arguments.
    ///
    /// Matches CPython's format: `{name}() missing {count} required keyword-only argument(s): 'a' and 'b'`
    #[must_use]
    fn type_error_missing_kwonly_with_names(name: &str, missing_names: &[&str]) -> RunError {
        let count = missing_names.len();
        let names_str = format_param_names(missing_names);
        if count == 1 {
            SimpleException::new_msg(
                ExcType::TypeError,
                format!("{name}() missing 1 required keyword-only argument: {names_str}"),
            )
            .into()
        } else {
            SimpleException::new_msg(
                ExcType::TypeError,
                format!("{name}() missing {count} required keyword-only arguments: {names_str}"),
            )
            .into()
        }
    }

    /// Creates a TypeError for too many positional arguments to a callable whose
    /// positional count is a range (some positional parameters have defaults).
    ///
    /// Matches CPython's pure-Python `def` wording: when `min == max` it emits
    /// `{name}() takes {max} positional argument(s) but {actual} was/were given`;
    /// otherwise `{name}() takes from {min} to {max} positional arguments but
    /// {actual} were given` (always-plural "arguments" in the range form). Both
    /// get the `(and N keyword-only argument(s))` suffix when `kwonly_given > 0`.
    /// Used by `FromArgs` structs marked `py_def` and by user `def` bindings.
    #[must_use]
    fn type_error_too_many_positional_range(
        name: &str,
        min: usize,
        max: usize,
        actual: usize,
        kwonly_given: usize,
    ) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            Self::too_many_positional_range_msg(name, min, max, actual, kwonly_given),
        )
        .into()
    }

    /// Message body for [`type_error_too_many_positional_range`], exposed
    /// separately so `args/bind_python.rs` can attach a call position to the same
    /// CPython-exact wording.
    #[must_use]
    fn too_many_positional_range_msg(name: &str, min: usize, max: usize, actual: usize, kwonly_given: usize) -> String {
        let takes = if min == max {
            // `max == 0` still reads "0 positional arguments" (plural) in CPython.
            let takes_word = if max == 1 { "argument" } else { "arguments" };
            format!("{max} positional {takes_word}")
        } else {
            format!("from {min} to {max} positional arguments")
        };
        if kwonly_given > 0 {
            // CPython includes keyword-only args in the "given" part when present
            let given_word = if actual == 1 { "argument" } else { "arguments" };
            let kwonly_word = if kwonly_given == 1 { "argument" } else { "arguments" };
            format!(
                "{name}() takes {takes} but {actual} positional {given_word} (and {kwonly_given} keyword-only {kwonly_word}) were given"
            )
        } else {
            let was_were = if actual == 1 { "was" } else { "were" };
            format!("{name}() takes {takes} but {actual} {was_were} given")
        }
    }

    /// Creates a TypeError for positional-only parameter passed as keyword.
    ///
    /// Matches CPython's format: `{name}() got some positional-only arguments passed as keyword arguments: '{param}'`
    #[must_use]
    fn type_error_positional_only(name: &str, param: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() got some positional-only arguments passed as keyword arguments: '{param}'"),
        )
        .into()
    }

    /// Creates a TypeError for duplicate argument.
    ///
    /// Matches CPython's format: `{name}() got multiple values for argument '{param}'`
    #[must_use]
    fn type_error_duplicate_arg(name: &str, param: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() got multiple values for argument '{param}'"),
        )
        .into()
    }

    /// Creates a TypeError for duplicate keyword argument.
    ///
    /// Matches CPython's format: `{name}() got multiple values for keyword argument '{key}'`
    #[must_use]
    fn type_error_multiple_values(name: &str, key: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() got multiple values for keyword argument '{key}'"),
        )
        .into()
    }

    /// Creates a TypeError for when a positional argument conflicts with a keyword argument
    /// of the same name in a C-implemented type constructor.
    ///
    /// Matches CPython's `PyArg_ParseTupleAndKeywords` format:
    /// `argument for function given by name ('{key}') and position ({pos})`
    ///
    /// The position is 1-indexed, matching CPython's convention. The `func_descriptor` is
    /// typically `"function"` for most C types (like `datetime`), matching CPython's generic
    /// wording for `PyArg_ParseTupleAndKeywords`.
    #[must_use]
    fn type_error_positional_keyword_conflict(func_descriptor: &str, key: &str, pos: usize) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("argument for {func_descriptor} given by name ('{key}') and position ({pos})"),
        )
        .into()
    }

    /// Creates a TypeError for unexpected keyword argument.
    ///
    /// Matches CPython's format: `{name}() got an unexpected keyword argument '{key}'`
    #[must_use]
    fn type_error_unexpected_keyword(name: &str, key: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() got an unexpected keyword argument '{key}'"),
        )
        .into()
    }

    /// Creates a TypeError for unexpected keyword argument in C-implemented types.
    ///
    /// Matches CPython's `PyArg_ParseTupleAndKeywords` format:
    /// `this function got an unexpected keyword argument '{key}'`
    #[must_use]
    fn type_error_c_unexpected_keyword(key: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("this function got an unexpected keyword argument '{key}'"),
        )
        .into()
    }

    /// Creates a TypeError for too many arguments to a C-implemented type.
    ///
    /// Matches CPython's `PyArg_ParseTupleAndKeywords` format:
    /// `function takes at most {max} arguments ({actual} given)`
    #[must_use]
    fn type_error_c_at_most(max: usize, actual: usize) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("function takes at most {max} arguments ({actual} given)"),
        )
        .into()
    }

    /// Variant of [`type_error_c_at_most`] used by C constructors that explicitly
    /// say "positional arguments" (e.g. `datetime`):
    /// `function takes at most {max} positional arguments ({actual} given)`
    #[must_use]
    fn type_error_c_at_most_positional(max: usize, actual: usize) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("function takes at most {max} positional arguments ({actual} given)"),
        )
        .into()
    }

    /// Hybrid wording used by C constructors that mix positional-or-keyword
    /// slots with keyword-only slots (e.g. `datetime`, where `fold` is
    /// keyword-only). CPython's `PyArg_ParseTupleAndKeywords` emits two
    /// distinct messages depending on whether the caller could conceivably
    /// have meant the overflow args to fill the keyword-only tail:
    ///
    /// - `actual <= max_total`: the extra positionals *could* have filled the
    ///   trailing keyword-only slots, so the error pins blame on positional
    ///   overflow specifically — `function takes at most {max_pos} positional
    ///   arguments ({actual} given)`.
    /// - `actual > max_total`: there is no slot of any kind for the extras,
    ///   so the error reports the total slot count without the "positional"
    ///   qualifier — `function takes at most {max_total} arguments ({actual}
    ///   given)`.
    ///
    /// `max_pos` is the number of positional-or-keyword slots; `max_total`
    /// adds the trailing keyword-only slot count. When `max_total == max_pos`
    /// (no kw-only fields) this collapses to [`type_error_c_at_most_positional`].
    #[must_use]
    fn type_error_c_at_most_positional_or_total(max_pos: usize, max_total: usize, actual: usize) -> RunError {
        if actual > max_total && max_total > max_pos {
            Self::type_error_c_at_most(max_total, actual)
        } else {
            Self::type_error_c_at_most_positional(max_pos, actual)
        }
    }

    /// Creates a TypeError for a missing required argument in a C-implemented type.
    ///
    /// Matches CPython's `PyArg_ParseTupleAndKeywords` format:
    /// `function missing required argument '{arg_name}' (pos {pos})`
    #[must_use]
    fn type_error_c_missing_required(arg_name: &str, pos: usize) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("function missing required argument '{arg_name}' (pos {pos})"),
        )
        .into()
    }

    /// Creates a TypeError for a missing required argument in a C-implemented type,
    /// with a function name prefix.
    ///
    /// Matches CPython's format for types like `timezone`:
    /// `{name}() missing required argument '{arg_name}' (pos {pos})`
    #[must_use]
    fn type_error_c_missing_required_named(name: &str, arg_name: &str, pos: usize) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() missing required argument '{arg_name}' (pos {pos})"),
        )
        .into()
    }

    /// Named positional-overflow wording used by clinic functions with
    /// keyword-only slots (e.g. `os.stat`/`os.mkdir`): `{name}() takes
    /// {exactly|at most} {max} positional argument{s} ({actual} given)` —
    /// "exactly" when every positional param is required.
    #[must_use]
    fn type_error_named_positional(name: &str, max: usize, actual: usize, exact: bool) -> RunError {
        let qualifier = if exact { "exactly" } else { "at most" };
        let plural = if max == 1 { "" } else { "s" };
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() takes {qualifier} {max} positional argument{plural} ({actual} given)"),
        )
        .into()
    }

    /// Creates a TypeError matching the `os` module's `path_t` converter:
    /// `{func}: {arg} should be {accepted}, not {type}` — `accepted` is the
    /// per-function accepted-types phrase (e.g. `string, bytes or os.PathLike`).
    #[must_use]
    fn type_error_os_path(func: &str, arg: &str, accepted: &str, type_name: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{func}: {arg} should be {accepted}, not {type_name}"),
        )
        .into()
    }

    /// Creates the `os.fspath` TypeError, also raised by pure-Python `os`
    /// functions that call `fspath` internally (e.g. `os.makedirs`):
    /// `expected str, bytes or os.PathLike object, not {type}`
    #[must_use]
    fn type_error_fspath(type_name: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("expected str, bytes or os.PathLike object, not {type_name}"),
        )
        .into()
    }

    /// Creates the `dir_fd` converter TypeError:
    /// `argument should be integer or None, not {type}`
    #[must_use]
    fn type_error_dir_fd(type_name: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("argument should be integer or None, not {type_name}"),
        )
        .into()
    }

    /// Creates the fd converter's OverflowError for fds above C `int` range:
    /// `fd is greater than maximum` (CPython's `_fd_converter`).
    #[must_use]
    fn overflow_fd_maximum() -> RunError {
        SimpleException::new_msg(ExcType::OverflowError, "fd is greater than maximum").into()
    }

    /// Creates the fd converter's OverflowError for fds below C `int` range:
    /// `fd is less than minimum` (CPython's `_fd_converter`).
    #[must_use]
    fn overflow_fd_minimum() -> RunError {
        SimpleException::new_msg(ExcType::OverflowError, "fd is less than minimum").into()
    }

    /// Creates the NotImplementedError CPython raises when an `os` argument is
    /// unsupported on the platform (`argument_unavailable_error`):
    /// `{func}: {arg} unavailable on this platform`, or just
    /// `{arg} unavailable on this platform` when `func` is `None`.
    /// Monty raises it for `dir_fd`/`follow_symlinks`, which it never supports.
    #[must_use]
    fn not_implemented_os_arg(func: Option<&str>, arg: &str) -> RunError {
        let msg = match func {
            Some(func) => format!("{func}: {arg} unavailable on this platform"),
            None => format!("{arg} unavailable on this platform"),
        };
        Self::not_implemented(msg).into()
    }

    /// Creates a TypeError for a missing required argument without a position,
    /// as raised by hand-written vectorcall fast paths like `enumerate`:
    /// `{name}() missing required argument '{arg_name}'`
    #[must_use]
    fn type_error_missing_required_no_pos(name: &str, arg_name: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() missing required argument '{arg_name}'"),
        )
        .into()
    }

    /// Creates a TypeError for a keyword rejected by a hand-written vectorcall
    /// fast path (CPython's `enumerate` wording, distinct from the parser
    /// families' "unexpected keyword argument"):
    /// `'{key}' is an invalid keyword argument for {name}()`
    #[must_use]
    fn type_error_invalid_keyword_argument(name: &str, key: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("'{key}' is an invalid keyword argument for {name}()"),
        )
        .into()
    }

    /// Creates a TypeError matching CPython's `_PyArg_BadArgument`
    /// positional-style wording: `{name}() argument {pos} must be
    /// {expected}, not {got}`.
    ///
    /// Used by the `#[derive(FromArgs)]` macro when the struct opts into
    /// `bad_arg` errors — emitted in place of the inner [`FromValue`]
    /// failure so the caller sees the same wording as CPython's C-implemented
    /// functions (e.g. `strftime() argument 1 must be str, not None`).
    ///
    /// The `got` type label should come from `Type::cpython_arg_name` so
    /// that `NoneType` becomes `"None"` to match CPython's special case.
    ///
    /// [`FromValue`]: crate::args::FromValue
    #[must_use]
    fn type_error_bad_arg_pos(name: &str, pos: usize, expected: &str, got: impl fmt::Display) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() argument {pos} must be {expected}, not {got}"),
        )
        .into()
    }

    /// Creates a TypeError matching CPython's `_PyArg_BadArgument`
    /// named-style wording: `{name}() argument '{arg_name}' must be
    /// {expected}, not {got}`.
    ///
    /// CPython uses this form for C-implemented functions that register
    /// their arguments by name (`open`, `str.encode`, `bytes.decode`, …).
    /// Sibling to [`type_error_bad_arg_pos`]; pick the variant matching the
    /// CPython output for the function being modelled.
    #[must_use]
    fn type_error_bad_arg_named(name: &str, arg_name: &str, expected: &str, got: impl fmt::Display) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() argument '{arg_name}' must be {expected}, not {got}"),
        )
        .into()
    }

    /// Creates a TypeError for **kwargs argument that is not a mapping.
    ///
    /// Matches CPython's format: `{name}() argument after ** must be a mapping, not {type_name}`
    #[must_use]
    fn type_error_kwargs_not_mapping(name: &str, type_name: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{name}() argument after ** must be a mapping, not {type_name}"),
        )
        .into()
    }

    /// Creates a TypeError for `{**x}` dict-literal unpacking where `x` is not a mapping.
    ///
    /// Matches CPython's format: `'{type_name}' object is not a mapping`
    ///
    /// Note: this differs from [`type_error_kwargs_not_mapping`] which is used for
    /// function-call `**kwargs` and includes the function name in the message.
    #[must_use]
    fn type_error_not_mapping(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not a mapping")).into()
    }

    /// Creates a TypeError for **kwargs with non-string keys.
    ///
    /// Matches CPython exactly: `keywords must be strings`, unqualified — the
    /// call machinery raises before the callee is entered, so no name is shown.
    #[must_use]
    fn type_error_kwargs_nonstring_key() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "keywords must be strings").into()
    }

    /// Creates a TypeError for an invalid `tzinfo` argument.
    ///
    /// Matches CPython: `tzinfo argument must be None or of a tzinfo subclass, not type 'int'`
    #[must_use]
    fn type_error_tzinfo(ty: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("tzinfo argument must be None or of a tzinfo subclass, not type '{ty}'"),
        )
        .into()
    }

    /// Creates a simple TypeError with a custom message.
    #[must_use]
    fn type_error(msg: impl fmt::Display) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, msg).into()
    }

    /// Creates the TypeError raised when a `with` statement's context expression
    /// does not implement the context-manager protocol.
    ///
    /// Matches CPython 3.14's wording, which names the specific missing dunder:
    /// `__exit__` when the protocol check fails outright (`BeforeWith`'s
    /// [`py_is_context_manager`](crate::types::PyTrait::py_is_context_manager)
    /// gate), `__enter__` when a user class defines `__exit__` but not
    /// `__enter__`.
    #[must_use]
    fn type_error_not_context_manager(type_name: impl Display, missing_dunder: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!(
                "'{type_name}' object does not support the context manager protocol (missed {missing_dunder} method)"
            ),
        )
        .into()
    }

    /// Creates a TypeError for `__init__` returning a value other than `None`.
    ///
    /// Matches CPython's format: `TypeError: __init__() should return None, not '{type}'`
    #[must_use]
    fn type_error_init_return(type_name: impl Display) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("__init__() should return None, not '{type_name}'"),
        )
        .into()
    }

    /// Creates a generic `ValueError` with a custom message.
    fn value_error(msg: impl fmt::Display) -> RunError {
        SimpleException::new_msg(ExcType::ValueError, msg).into()
    }

    /// Creates a TypeError for bytes() constructor with invalid type.
    ///
    /// Matches CPython's format: `TypeError: cannot convert '{type}' object to bytes`
    #[must_use]
    fn type_error_bytes_init(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("cannot convert '{type_}' object to bytes")).into()
    }

    /// Creates a TypeError for calling a non-callable type.
    ///
    /// Matches CPython's format: `TypeError: cannot create '{type}' instances`
    #[must_use]
    fn type_error_not_callable(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("cannot create '{type_}' instances")).into()
    }

    /// Creates a TypeError for calling a non-callable object.
    ///
    /// Matches CPython's format: `TypeError: '{type}' object is not callable`
    #[must_use]
    fn type_error_not_callable_object(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not callable")).into()
    }

    /// Creates a TypeError for non-iterable type in list/tuple/etc constructors.
    ///
    /// Matches CPython's format: `TypeError: '{type}' object is not iterable`
    #[must_use]
    fn type_error_not_iterable(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not iterable")).into()
    }

    /// Creates the ValueError `itertools.islice(it, stop)` raises for a `stop`
    /// that is neither `None` nor an index — the two-argument wording, which
    /// names the stop argument specifically.
    #[must_use]
    fn islice_bad_stop() -> RunError {
        Self::value_error("Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.")
    }

    /// Creates the ValueError `itertools.islice` raises for a bad `start` or
    /// `stop` in the three-or-more argument form, where CPython stops naming
    /// which of them was at fault.
    #[must_use]
    fn islice_bad_indices() -> RunError {
        Self::value_error("Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.")
    }

    /// Creates the ValueError `itertools.islice` raises for a non-positive or
    /// non-integer `step`.
    #[must_use]
    fn islice_bad_step() -> RunError {
        Self::value_error("Step for islice() must be a positive integer or None.")
    }

    /// Creates a TypeError for the right operand of `in` / `not in` supporting
    /// neither `__contains__` nor iteration.
    ///
    /// Matches CPython's format: `TypeError: argument of type '{type}' is not a
    /// container or iterable`
    #[must_use]
    fn type_error_not_container(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("argument of type '{type_}' is not a container or iterable"),
        )
        .into()
    }

    /// Creates a TypeError for a class opting out of `in` with
    /// `__contains__ = None`.
    ///
    /// Matches CPython's `slot_sq_contains` format: `TypeError: '{type}' object
    /// is not a container` — deliberately distinct from
    /// [`type_error_not_container`], which covers a type that never had
    /// `__contains__` at all.
    #[must_use]
    fn type_error_object_not_container(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not a container")).into()
    }

    /// Creates a TypeError when `next()` receives a non-iterator.
    ///
    /// Matches CPython's format: `TypeError: '{type}' object is not an iterator`
    #[must_use]
    fn type_error_not_iterator(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not an iterator")).into()
    }

    /// Creates a TypeError for a user `__iter__` returning a non-iterator.
    ///
    /// Matches CPython's format: `TypeError: iter() returned non-iterator of type '{type}'`
    #[must_use]
    fn type_error_iter_returned_non_iterator(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("iter() returned non-iterator of type '{type_}'"),
        )
        .into()
    }

    /// Creates a TypeError for non-iterable type in PEP 448 `*value` literal unpack.
    ///
    /// Used when `[*expr]`, `(*expr,)` literal unpack encounters a non-iterable — distinct
    /// from [`type_error_not_iterable`] because CPython uses a different message for this context.
    ///
    /// Matches CPython's format: `TypeError: Value after * must be an iterable, not {type}`
    #[must_use]
    fn type_error_value_after_star(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("Value after * must be an iterable, not {type_}"),
        )
        .into()
    }

    /// Creates a TypeError for int() constructor with invalid type.
    ///
    /// Matches CPython's format: `TypeError: int() argument must be a string, a bytes-like object or a real number, not '{type}'`
    #[must_use]
    fn type_error_int_conversion(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("int() argument must be a string, a bytes-like object or a real number, not '{type_}'"),
        )
        .into()
    }

    /// Creates a TypeError for float() constructor with invalid type.
    ///
    /// Matches CPython's format: `TypeError: float() argument must be a string or a real number, not '{type}'`
    #[must_use]
    fn type_error_float_conversion(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("float() argument must be a string or a real number, not '{type_}'"),
        )
        .into()
    }

    /// Creates a ValueError for negative count in bytes().
    ///
    /// Matches CPython's format: `ValueError: negative count`
    #[must_use]
    fn value_error_negative_bytes_count() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "negative count").into()
    }

    /// Creates a TypeError for isinstance() arg 2.
    ///
    /// Matches CPython's format: `TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union`
    #[must_use]
    fn isinstance_arg2_error() -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            "isinstance() arg 2 must be a type, a tuple of types, or a union",
        )
        .into()
    }

    /// Creates a TypeError for invalid exception type in except clause.
    ///
    /// Matches CPython's format: `TypeError: catching classes that do not inherit from BaseException is not allowed`
    #[must_use]
    fn except_invalid_type_error() -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            "catching classes that do not inherit from BaseException is not allowed",
        )
        .into()
    }

    /// Creates a ValueError for range() step argument being zero.
    ///
    /// Matches CPython's format: `ValueError: range() arg 3 must not be zero`
    #[must_use]
    fn value_error_range_step_zero() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "range() arg 3 must not be zero").into()
    }

    /// Creates a ValueError for slice step being zero.
    ///
    /// Matches CPython's format: `ValueError: slice step cannot be zero`
    #[must_use]
    fn value_error_slice_step_zero() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "slice step cannot be zero").into()
    }

    /// Creates a TypeError for slice indices that are not integers or None.
    ///
    /// Matches CPython's format: `TypeError: slice indices must be integers or None or have an __index__ method`
    #[must_use]
    fn type_error_slice_indices() -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            "slice indices must be integers or None or have an __index__ method",
        )
        .into()
    }

    /// Creates a RuntimeError for dict mutation during iteration.
    ///
    /// Matches CPython's format: `RuntimeError: dictionary changed size during iteration`
    #[must_use]
    fn runtime_error_dict_changed_size() -> RunError {
        SimpleException::new_msg(ExcType::RuntimeError, "dictionary changed size during iteration").into()
    }

    /// Creates a TypeError for `reversed()` on a non-reversible object.
    ///
    /// Matches CPython's format: `TypeError: '{type}' object is not reversible`
    #[must_use]
    fn type_error_not_reversible(type_: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not reversible")).into()
    }

    /// Creates a RuntimeError for set mutation during iteration.
    ///
    /// Matches CPython's format: `RuntimeError: Set changed size during iteration`
    #[must_use]
    fn runtime_error_set_changed_size() -> RunError {
        SimpleException::new_msg(ExcType::RuntimeError, "Set changed size during iteration").into()
    }

    /// Creates a TypeError for functions that don't accept keyword arguments.
    ///
    /// Matches CPython's format: `TypeError: {name}() takes no keyword arguments`
    #[must_use]
    fn type_error_no_kwargs(name: &str) -> RunError {
        SimpleException::new_msg(ExcType::TypeError, format!("{name}() takes no keyword arguments")).into()
    }

    /// Creates a NotImplementedError for functions that don't accept keyword arguments.
    #[must_use]
    fn kwargs_not_implemented(name: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::NotImplementedError,
            format!("{name}() does not yet support keyword arguments"),
        )
        .into()
    }

    /// Creates an IndexError for list index out of range (getitem).
    ///
    /// Matches CPython's format: `IndexError('list index out of range')`
    #[must_use]
    fn list_index_error() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "list index out of range").into()
    }

    /// Creates an IndexError for list assignment index out of range (setitem).
    ///
    /// Matches CPython's format: `IndexError('list assignment index out of range')`
    #[must_use]
    fn list_assignment_index_error() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "list assignment index out of range").into()
    }

    /// Creates an IndexError for tuple index out of range.
    ///
    /// Matches CPython's format: `IndexError('tuple index out of range')`
    #[must_use]
    fn tuple_index_error() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "tuple index out of range").into()
    }

    /// Creates an IndexError for string index out of range.
    ///
    /// Matches CPython's format: `IndexError('string index out of range')`
    #[must_use]
    fn str_index_error() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "string index out of range").into()
    }

    /// Creates an IndexError for bytes index out of range.
    ///
    /// Matches CPython's format: `IndexError('index out of range')`
    #[must_use]
    fn bytes_index_error() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "index out of range").into()
    }

    /// Creates an IndexError for range index out of range.
    ///
    /// Matches CPython's format: `IndexError('range object index out of range')`
    #[must_use]
    fn range_index_error() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "range object index out of range").into()
    }

    /// Creates an IndexError for `re.Match` group index out of range.
    ///
    /// Matches CPython's format: `IndexError('no such group')`
    #[must_use]
    fn re_match_group_index_error() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "no such group").into()
    }

    /// Creates a TypeError for non-integer sequence indices (getitem).
    ///
    /// Matches CPython's format: `TypeError('{type}' indices must be integers, not '{index_type}')`
    #[must_use]
    fn type_error_indices(type_str: Type, index_type: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("{type_str} indices must be integers, not '{index_type}'"),
        )
        .into()
    }

    /// Creates a TypeError for non-integer list indices (setitem/assignment).
    ///
    /// Matches CPython's format: `TypeError('list indices must be integers or slices, not {index_type}')`
    #[must_use]
    fn type_error_list_assignment_indices(index_type: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("list indices must be integers or slices, not {index_type}"),
        )
        .into()
    }

    /// Creates a NameError for accessing a free variable (nonlocal/closure) before it's assigned.
    ///
    /// Matches CPython's format: `NameError: cannot access free variable 'x' where it is not
    /// associated with a value in enclosing scope`
    #[must_use]
    fn name_error_free_variable(name: &str) -> SimpleException {
        SimpleException::new_msg(
            ExcType::NameError,
            format!("cannot access free variable '{name}' where it is not associated with a value in enclosing scope"),
        )
    }

    /// Creates a NameError for accessing an undefined variable.
    ///
    /// Matches CPython's format: `NameError: name 'x' is not defined`
    #[must_use]
    fn name_error(name: &str) -> SimpleException {
        let mut msg = format!("name '{name}' is not defined");
        // add the same suffix as cpython, but only for the modules supported by Monty
        if matches!(name, "asyncio" | "sys" | "typing" | "types" | "re" | "json") {
            write!(&mut msg, ". Did you forget to import '{name}'?").unwrap();
        }
        SimpleException::new_msg(ExcType::NameError, msg)
    }

    /// Creates an UnboundLocalError for accessing a local variable before assignment.
    ///
    /// Matches CPython's format: `UnboundLocalError: cannot access local variable 'x' where it is not associated with a value`
    #[must_use]
    fn unbound_local_error(name: &str) -> SimpleException {
        SimpleException::new_msg(
            ExcType::UnboundLocalError,
            format!("cannot access local variable '{name}' where it is not associated with a value"),
        )
    }

    /// Creates a ModuleNotFoundError for when a module cannot be found.
    ///
    /// Matches CPython's format: `ModuleNotFoundError: No module named 'name'`
    /// Sets `hide_caret: true` because CPython doesn't show carets for module not found errors.
    #[must_use]
    fn module_not_found_error(module_name: &str) -> RunError {
        let exc = SimpleException::new_msg(ExcType::ModuleNotFoundError, format!("No module named '{module_name}'"));
        RunError::Exc(ExceptionRaise {
            exc,
            frame: None,
            hide_caret: true, // CPython doesn't show carets for module not found errors
        })
    }

    /// Creates a NotImplementedError for an unimplemented Python feature.
    ///
    /// For syntax Monty cannot parse ("The monty syntax parser does not yet support
    /// {feature}") and for runtime features it refuses rather than approximates (a
    /// `@dataclass` body it cannot honour). Reserve it for "Monty has not built this
    /// yet" — a call CPython would also reject belongs in the matching CPython type.
    #[must_use]
    fn not_implemented(msg: impl fmt::Display) -> SimpleException {
        SimpleException::new_msg(ExcType::NotImplementedError, msg)
    }

    /// Creates a ZeroDivisionError for division by zero.
    ///
    /// Matches CPython 3.14's format: `ZeroDivisionError('division by zero')`
    #[must_use]
    fn zero_division() -> SimpleException {
        SimpleException::new_msg(ExcType::ZeroDivisionError, "division by zero")
    }

    /// Creates an OverflowError for string/sequence repetition with count too large.
    ///
    /// Matches CPython's format: `OverflowError('cannot fit 'int' into an index-sized integer')`
    #[must_use]
    fn overflow_repeat_count() -> SimpleException {
        SimpleException::new_msg(ExcType::OverflowError, "cannot fit 'int' into an index-sized integer")
    }

    /// Creates an IndexError for when an integer index is too large to fit in i64.
    ///
    /// Matches CPython's format: `IndexError: cannot fit 'int' into an index-sized integer`
    #[must_use]
    fn index_error_int_too_large() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "cannot fit 'int' into an index-sized integer").into()
    }

    /// Creates an ImportError for when a name cannot be imported from a module.
    ///
    /// Matches CPython's format for built-in modules:
    /// `ImportError: cannot import name 'name' from 'module' (unknown location)`
    ///
    /// Sets `hide_caret: true` because CPython doesn't show carets for import errors.
    #[must_use]
    fn cannot_import_name(name: &str, module_name: &str) -> RunError {
        let exc = SimpleException::new_msg(
            ExcType::ImportError,
            format!("cannot import name '{name}' from '{module_name}' (unknown location)"),
        );
        RunError::Exc(ExceptionRaise {
            exc,
            frame: None,
            hide_caret: true,
        })
    }

    /// Creates a ValueError when an integer is too large to convert to a decimal string.
    ///
    /// Matches CPython 3.11+'s `sys.int_max_str_digits` error message.
    #[must_use]
    fn value_error_int_too_large_for_str() -> RunError {
        SimpleException::new_msg(
            ExcType::ValueError,
            format!(
                "Exceeds the limit ({INT_MAX_STR_DIGITS} digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit"
            ),
        )
        .into()
    }

    /// Creates a ValueError when a decimal string has too many digits for `int()` conversion.
    ///
    /// Includes the actual digit count to help users diagnose the issue.
    #[must_use]
    fn value_error_int_str_too_large(digit_count: usize) -> RunError {
        SimpleException::new_msg(
            ExcType::ValueError,
            format!(
                "Exceeds the limit ({INT_MAX_STR_DIGITS} digits) for integer string conversion: value has {digit_count} digits; use sys.set_int_max_str_digits() to increase the limit"
            ),
        )
        .into()
    }

    /// Creates a ValueError for `int()` when a string cannot be parsed as an integer.
    ///
    /// Matches CPython's format: `invalid literal for int() with base {N}: '...'`.
    /// `base` is the base the caller passed (0 included, before auto-detection);
    /// the caller provides the value pre-formatted (e.g. via `StringRepr`).
    #[must_use]
    fn value_error_invalid_literal_for_int(base: u32, value: impl fmt::Display) -> RunError {
        SimpleException::new_msg(
            ExcType::ValueError,
            format!("invalid literal for int() with base {base}: {value}"),
        )
        .into()
    }

    /// Creates a ValueError for an `int()` base outside `{0} ∪ 2..=36`.
    ///
    /// Matches CPython's message: `int() base must be >= 2 and <= 36, or 0`.
    #[must_use]
    fn value_error_int_base_range() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "int() base must be >= 2 and <= 36, or 0").into()
    }

    /// Creates a TypeError for `int(base=N)` with no value to convert.
    ///
    /// Matches CPython's message: `int() missing string argument`. Raised
    /// before the base is validated, matching `long_new_impl`'s ordering.
    #[must_use]
    fn type_error_int_missing_string_argument() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "int() missing string argument").into()
    }

    /// Creates a TypeError for `int(x, base)` where `x` is not str/bytes.
    ///
    /// Matches CPython's message: `int() can't convert non-string with explicit base`.
    #[must_use]
    fn type_error_int_non_string_with_base() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "int() can't convert non-string with explicit base").into()
    }

    /// Creates a ValueError for negative shift count in bitwise shift operations.
    ///
    /// Matches CPython's format: `ValueError: negative shift count`
    #[must_use]
    fn value_error_negative_shift_count() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "negative shift count").into()
    }

    /// Creates an OverflowError when converting values to C ssize_t (i64) for operations like length checks.
    ///
    /// Matches CPython's format: `OverflowError: Python int too large to convert to C ssize_t`
    /// Note: CPython uses this message because it tries to convert to ssize_t for the shift amount.
    #[must_use]
    fn overflow_c_ssize_t() -> RunError {
        SimpleException::new_msg(ExcType::OverflowError, "Python int too large to convert to C ssize_t").into()
    }

    /// Creates an OverflowError when a Python int doesn't fit into a C `int` (i32).
    ///
    /// Matches CPython's format: `OverflowError: Python int too large to convert to C int`
    /// Used by builtins (e.g. `bytes.hex`) that parse arguments via the `i` format code.
    #[must_use]
    fn overflow_c_int() -> RunError {
        SimpleException::new_msg(ExcType::OverflowError, "Python int too large to convert to C int").into()
    }

    /// Creates an OverflowError when a Python int doesn't fit into a C `long` (i64).
    ///
    /// Matches CPython's format: `OverflowError: Python int too large to convert to C long`
    /// CPython's `i` format code converts through C long first, so ints beyond
    /// i64 report this even for C-int parameters (e.g. `datetime.date(2**100, 1, 1)`).
    #[must_use]
    fn overflow_c_long() -> RunError {
        SimpleException::new_msg(ExcType::OverflowError, "Python int too large to convert to C long").into()
    }

    /// Creates a TypeError for unsupported binary operations.
    ///
    /// For `+` or `+=` with str/list on the left side, uses CPython's special format:
    /// `can only concatenate {type} (not "{other}") to {type}`
    ///
    /// For other cases, uses the generic format:
    /// `unsupported operand type(s) for {op}: '{left}' and '{right}'`
    #[must_use]
    fn binary_type_error(op: &str, lhs_type: Type, lhs_name: impl Display, rhs_name: impl Display) -> RunError {
        let message = if (op == "+" || op == "+=") && matches!(lhs_type, Type::Deque) {
            // CPython hardcodes the bare "deque" here even though tp_name is the
            // qualified "collections.deque", so this can't share the branch below.
            format!("can only concatenate deque (not \"{rhs_name}\") to deque")
        } else if (op == "+" || op == "+=") && matches!(lhs_type, Type::Str | Type::List) {
            format!("can only concatenate {lhs_name} (not \"{rhs_name}\") to {lhs_name}")
        } else {
            format!("unsupported operand type(s) for {op}: '{lhs_name}' and '{rhs_name}'")
        };
        SimpleException::new_msg(ExcType::TypeError, message).into()
    }

    /// Creates a TypeError for unsupported unary operations.
    ///
    /// Uses CPython's format: `bad operand type for unary {op}: '{type}'`
    #[must_use]
    fn unary_type_error(op: &str, value_type: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("bad operand type for unary {op}: '{value_type}'"),
        )
        .into()
    }

    /// Creates a TypeError for functions that require an integer argument.
    ///
    /// Matches CPython's format: `TypeError: '{type}' object cannot be interpreted as an integer`
    #[must_use]
    fn type_error_not_integer(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("'{type_}' object cannot be interpreted as an integer"),
        )
        .into()
    }

    /// Creates a ZeroDivisionError for zero raised to a negative power.
    ///
    /// Matches CPython's format: `ZeroDivisionError: zero to a negative power`
    /// Note: CPython uses the same message for both int and float zero ** negative.
    #[must_use]
    fn zero_negative_power() -> RunError {
        SimpleException::new_msg(ExcType::ZeroDivisionError, "zero to a negative power").into()
    }

    /// Creates an OverflowError for exponents that are too large.
    ///
    /// Matches CPython's format: `OverflowError: exponent too large`
    #[must_use]
    fn overflow_exponent_too_large() -> RunError {
        SimpleException::new_msg(ExcType::OverflowError, "exponent too large").into()
    }

    /// Creates an OverflowError when an integer cannot be represented as a float.
    #[must_use]
    fn overflow_int_to_float() -> RunError {
        SimpleException::new_msg(ExcType::OverflowError, "int too large to convert to float").into()
    }

    /// Creates a ValueError for a zero modulus passed to `pow`.
    #[must_use]
    fn value_error_pow_modulus_zero() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "pow() 3rd argument cannot be 0").into()
    }

    /// Creates a ValueError for a negative exponent passed to modular `pow`.
    #[must_use]
    fn value_error_pow_negative_exponent() -> RunError {
        SimpleException::new_msg(
            ExcType::ValueError,
            "pow() 2nd argument cannot be negative when 3rd argument specified",
        )
        .into()
    }

    /// Creates a ZeroDivisionError for divmod by zero (both integer and float).
    ///
    /// Matches CPython's format: `ZeroDivisionError: division by zero`
    /// Note: CPython uses the same message for both integer and float divmod.
    #[must_use]
    fn divmod_by_zero() -> RunError {
        SimpleException::new_msg(ExcType::ZeroDivisionError, "division by zero").into()
    }

    /// Creates a TypeError for str.join() when an item is not a string.
    ///
    /// Matches CPython's format: `TypeError: sequence item {index}: expected str instance, {type} found`
    #[must_use]
    fn type_error_join_item(index: usize, item_type: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("sequence item {index}: expected str instance, {item_type} found"),
        )
        .into()
    }

    /// Creates a TypeError for str.join() when the argument is not iterable.
    ///
    /// Matches CPython's format: `TypeError: can only join an iterable`
    #[must_use]
    fn type_error_join_not_iterable() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "can only join an iterable").into()
    }

    /// Creates a ValueError for str.index()/str.rindex() when substring is not found.
    ///
    /// Matches CPython's format: `ValueError: substring not found`
    #[must_use]
    fn value_error_substring_not_found() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "substring not found").into()
    }

    /// Creates a ValueError for str.partition()/str.rpartition() with empty separator.
    ///
    /// Matches CPython's format: `ValueError: empty separator`
    #[must_use]
    fn value_error_empty_separator() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "empty separator").into()
    }

    /// Creates a TypeError for fillchar argument that is not a single character.
    ///
    /// Matches CPython's format: `TypeError: The fill character must be exactly one character long`
    #[must_use]
    fn type_error_fillchar_must_be_single_char() -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            "The fill character must be exactly one character long",
        )
        .into()
    }

    /// Creates a StopIteration exception for when an iterator is exhausted.
    ///
    /// Matches CPython's format: `StopIteration`
    #[must_use]
    fn stop_iteration() -> RunError {
        SimpleException::new_none(ExcType::StopIteration).into()
    }

    /// Creates a ValueError for list.index() when item is not found.
    ///
    /// Matches CPython's format: `ValueError: list.index(x): x not in list`
    #[must_use]
    fn value_error_not_in_list() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "list.index(x): x not in list").into()
    }

    /// Creates a ValueError for tuple.index() when item is not found.
    ///
    /// Matches CPython's format: `ValueError: tuple.index(x): x not in tuple`
    #[must_use]
    fn value_error_not_in_tuple() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "tuple.index(x): x not in tuple").into()
    }

    /// Creates a ValueError for list.remove() when item is not found.
    ///
    /// Matches CPython's format: `ValueError: list.remove(x): x not in list`
    #[must_use]
    fn value_error_remove_not_in_list() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "list.remove(x): x not in list").into()
    }

    /// Creates an IndexError for popping from an empty list.
    ///
    /// Matches CPython's format: `IndexError: pop from empty list`
    #[must_use]
    fn index_error_pop_empty_list() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "pop from empty list").into()
    }

    /// Creates an IndexError for list.pop(index) with invalid index.
    ///
    /// Matches CPython's format: `IndexError: pop index out of range`
    #[must_use]
    fn index_error_pop_out_of_range() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "pop index out of range").into()
    }

    /// Creates a KeyError for popping from an empty dict.
    ///
    /// Matches CPython's format: `KeyError: 'popitem(): dictionary is empty'`
    #[must_use]
    fn key_error_popitem_empty_dict() -> RunError {
        SimpleException::new_msg(ExcType::KeyError, "'popitem(): dictionary is empty'").into()
    }

    /// Creates a LookupError for unknown encoding.
    ///
    /// Matches CPython's format: `LookupError: unknown encoding: {encoding}`
    #[must_use]
    fn lookup_error_unknown_encoding(encoding: &str) -> RunError {
        SimpleException::new_msg(ExcType::LookupError, format!("unknown encoding: {encoding}")).into()
    }

    /// Creates a TypeError for `str(s, encoding=...)` with a str object.
    ///
    /// Matches CPython's message: `decoding str is not supported`.
    #[must_use]
    fn type_error_decoding_str_not_supported() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "decoding str is not supported").into()
    }

    /// Creates a TypeError for `str(x, encoding=...)` with a non-bytes object.
    ///
    /// Matches CPython's format: `decoding to str: need a bytes-like object, {type} found`.
    #[must_use]
    fn type_error_decoding_need_bytes(type_: impl Display) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("decoding to str: need a bytes-like object, {type_} found"),
        )
        .into()
    }

    /// Creates a TypeError for `bytes(s)` with a str source and no encoding.
    ///
    /// Matches CPython's message: `string argument without an encoding`.
    #[must_use]
    fn type_error_string_without_encoding() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "string argument without an encoding").into()
    }

    /// Creates a TypeError for `bytes(x, encoding=...)` with a non-str source.
    ///
    /// Matches CPython's message: `encoding without a string argument`.
    #[must_use]
    fn type_error_encoding_without_string() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "encoding without a string argument").into()
    }

    /// Creates a TypeError for `bytes(x, errors=...)` with a non-str source.
    ///
    /// Matches CPython's message: `errors without a string argument`.
    #[must_use]
    fn type_error_errors_without_string() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "errors without a string argument").into()
    }

    /// Creates a TypeError for `sum()` rejecting a str/bytes `start` value.
    ///
    /// Matches CPython: `sum() can't sum {kind} [use {join}.join(seq) instead]`
    /// — `("strings", "''")` for str, `("bytes", "b''")` for bytes.
    #[must_use]
    fn type_error_sum_start(kind: &str, join: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("sum() can't sum {kind} [use {join}.join(seq) instead]"),
        )
        .into()
    }

    /// Creates a UnicodeEncodeError for a run of `start..end` consecutive
    /// characters (character indices, not byte offsets) of `object` — the
    /// full string being encoded — that can't be represented in the target
    /// `codec`. `first_char` is the character at `start`, used for the
    /// single-character message form.
    ///
    /// Matches CPython's format, which differs for a single character vs. a run:
    /// `UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in
    /// position 1: ordinal not in range(128)` or `... can't encode characters
    /// in position 1-2: ordinal not in range(128)`.
    #[must_use]
    fn unicode_encode_error(
        codec: &str,
        object: &str,
        first_char: char,
        start: usize,
        end: usize,
        reason: &str,
    ) -> RunError {
        // Callers must pass a non-empty range; checked in debug builds only so
        // a wrong caller can't panic the VM in release (it gets a garbled
        // message position instead, which is harmless).
        debug_assert!(
            end > start,
            "unicode_encode_error: end ({end}) must be > start ({start})"
        );
        let msg = if end - start == 1 {
            format!(
                "'{codec}' codec can't encode character '{}' in position {start}: {reason}",
                ascii_escape(&first_char.to_string())
            )
        } else {
            let last = end - 1;
            format!("'{codec}' codec can't encode characters in position {start}-{last}: {reason}")
        };
        SimpleException::new_msg(ExcType::UnicodeEncodeError, msg)
            .with_data(UnicodeErrorData::encode(codec, object, start, end, reason))
            .into()
    }

    /// Creates a UnicodeDecodeError for the undecodable byte range `start..end`
    /// (byte offsets into `object` — the full input being decoded).
    ///
    /// Matches CPython's format, which differs for a single byte vs. a run:
    /// `UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 6:
    /// ordinal not in range(128)` or `'utf-8' codec can't decode bytes in
    /// position 0-1: unexpected end of data`.
    #[must_use]
    fn unicode_decode_error(codec: &str, object: &[u8], start: usize, end: usize, reason: &str) -> RunError {
        // Defensive `get`: `start` always indexes a real byte for the errors
        // Monty produces, but a wrong caller must not be able to panic the VM.
        let first_byte = object.get(start).copied().unwrap_or(0);
        SimpleException::new_msg(
            ExcType::UnicodeDecodeError,
            unicode_decode_error_msg(codec, first_byte, start, end, reason),
        )
        .with_data(UnicodeErrorData::decode(codec, object, start, end, reason))
        .into()
    }

    /// Creates a ValueError for subsequence not found in bytes/str.
    ///
    /// Matches CPython's format: `ValueError: subsection not found`
    #[must_use]
    fn value_error_subsequence_not_found() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "subsection not found").into()
    }

    /// Creates a LookupError for unknown error handler.
    ///
    /// Matches CPython's format: `LookupError: unknown error handler name '{name}'`
    #[must_use]
    fn lookup_error_unknown_error_handler(name: &str) -> RunError {
        SimpleException::new_msg(ExcType::LookupError, format!("unknown error handler name '{name}'")).into()
    }

    /// Creates a TypeError for an encode-only error handler (`xmlcharrefreplace`,
    /// `namereplace`) invoked for a decode error.
    ///
    /// Matches CPython's format: `TypeError: don't know how to handle
    /// UnicodeDecodeError in error callback`
    #[must_use]
    fn type_error_decode_error_callback() -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            "don't know how to handle UnicodeDecodeError in error callback",
        )
        .into()
    }

    /// Creates a NotImplementedError for a decode error handler that would
    /// produce lone surrogates (`surrogateescape` always; `surrogatepass` when
    /// the input actually contains an encoded surrogate).
    ///
    /// CPython's handlers put lone surrogates (e.g. U+DC80–U+DCFF for
    /// `surrogateescape`) in the resulting string. Monty strings are strict
    /// UTF-8 and cannot represent lone surrogates, so these cases cannot be
    /// supported — see `limitations/encoding.md`.
    #[must_use]
    fn not_implemented_surrogate_handler_decode(handler: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::NotImplementedError,
            format!(
                "the '{handler}' error handler is not supported by Monty for decoding: \
                 Monty strings cannot contain the lone surrogate characters it produces"
            ),
        )
        .into()
    }

    /// Creates a `re.PatternError` for an invalid regex pattern or unsupported regex feature.
    ///
    /// Matches CPython's exception type: `re.PatternError: {message}`
    #[must_use]
    fn re_pattern_error(msg: impl fmt::Display) -> RunError {
        SimpleException::new_msg(ExcType::RePatternError, msg).into()
    }

    /// Creates a `json.JSONDecodeError` with CPython-compatible location suffix,
    /// formatted as `{message}: line {line} column {column} (char {index})`.
    ///
    /// The fields also travel in a structured [`JsonErrorData`] payload
    /// (with `doc` capped) so hosts can rebuild the real `json.JSONDecodeError`
    /// with its `msg`/`doc`/`pos`/`lineno`/`colno` attributes.
    ///
    /// # Arguments
    ///
    /// * `message` - The bare error message, without the location suffix
    /// * `doc` - The document being parsed (CPython's `exc.doc`)
    /// * `line` - 1-based line of the error (CPython's `exc.lineno`)
    /// * `column` - 1-based column of the error (CPython's `exc.colno`)
    /// * `index` - Character index of the error in `doc` (CPython's `exc.pos`)
    #[must_use]
    fn json_decode_error(message: &str, doc: &[u8], line: usize, column: usize, index: usize) -> RunError {
        SimpleException::new_msg(
            ExcType::JsonDecodeError,
            format!("{message}: line {line} column {column} (char {index})"),
        )
        .with_data(JsonErrorData::build(message, doc, index, line, column))
        .into()
    }

    /// Creates the `TypeError` used by `json.loads()` for unsupported input types.
    ///
    /// Matches CPython's format:
    /// `the JSON object must be str, bytes or bytearray, not {type}`
    #[must_use]
    fn json_loads_type_error(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("the JSON object must be str, bytes or bytearray, not {type_}"),
        )
        .into()
    }

    /// Creates the `ValueError` used by `json.dumps()` for circular containers.
    ///
    /// Matches CPython's format: `Circular reference detected`
    #[must_use]
    fn json_circular_reference_error() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "Circular reference detected").into()
    }

    /// Creates the `TypeError` used by `json.dumps()` for unsupported object types.
    ///
    /// Matches CPython's format:
    /// `Object of type {type} is not JSON serializable`
    #[must_use]
    fn json_not_serializable_error(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("Object of type {type_} is not JSON serializable"),
        )
        .into()
    }

    /// Creates the `TypeError` used by `json.dumps()` for unsupported dict keys.
    ///
    /// Matches CPython's format:
    /// `keys must be str, int, float, bool or None, not {type}`
    #[must_use]
    fn json_invalid_key_error(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("keys must be str, int, float, bool or None, not {type_}"),
        )
        .into()
    }

    /// Creates the `ValueError` used by `json.dumps(..., allow_nan=False)`.
    ///
    /// Matches CPython's format:
    /// `Out of range float values are not JSON compliant: {value}`
    #[must_use]
    fn json_nan_error(value: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::ValueError,
            format!("Out of range float values are not JSON compliant: {value}"),
        )
        .into()
    }

    /// `AttributeError: attribute 'X' of 'Y' objects is not writable`.
    ///
    /// CPython distinguishes a read-only C-level attribute (`deque.maxlen`) from an
    /// attribute that simply does not exist, which gets
    /// [`attribute_error_no_setattr`](ExcType::attribute_error_no_setattr) instead.
    #[must_use]
    fn attribute_error_not_writable(attr_name: &str, type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::AttributeError,
            format!("attribute '{attr_name}' of '{type_}' objects is not writable"),
        )
        .into()
    }

    /// Creates a TypeError for slice indices that are not integers, where `None`
    /// is *not* accepted either.
    ///
    /// Used by `index()`-style bounds (`deque.index`), which — unlike real slicing —
    /// treat an explicit `None` as a bad argument rather than "use the default".
    /// Matches CPython's format: `TypeError: slice indices must be integers or have an __index__ method`
    #[must_use]
    fn type_error_slice_indices_no_none() -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            "slice indices must be integers or have an __index__ method",
        )
        .into()
    }

    /// `RuntimeError: deque mutated during iteration`.
    ///
    /// Monty tracks a per-deque mutation counter, mirroring CPython's internal
    /// state, so any structural change during iteration invalidates the iterator
    /// — including `rotate()` and a length-preserving `append()`/`popleft()` pair,
    /// which a bare length check would miss.
    #[must_use]
    fn runtime_error_deque_mutated() -> RunError {
        SimpleException::new_msg(ExcType::RuntimeError, "deque mutated during iteration").into()
    }

    /// `IndexError: deque index out of range` — indexing or assigning out of bounds.
    #[must_use]
    fn index_error_deque_out_of_range() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "deque index out of range").into()
    }

    /// `IndexError: pop from an empty deque` — shared by `pop()` and `popleft()`.
    #[must_use]
    fn index_error_pop_from_empty_deque() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "pop from an empty deque").into()
    }

    /// `IndexError: deque already at its maximum size` — `insert()` into a full deque.
    #[must_use]
    fn index_error_deque_full() -> RunError {
        SimpleException::new_msg(ExcType::IndexError, "deque already at its maximum size").into()
    }

    /// `ValueError: deque.remove(x): x not in deque`.
    #[must_use]
    fn value_error_deque_remove() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "deque.remove(x): x not in deque").into()
    }

    /// `ValueError: deque.index(x): x not in deque`.
    #[must_use]
    fn value_error_deque_index() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "deque.index(x): x not in deque").into()
    }

    /// `ValueError: maxlen must be non-negative`.
    #[must_use]
    fn value_error_maxlen_negative() -> RunError {
        SimpleException::new_msg(ExcType::ValueError, "maxlen must be non-negative").into()
    }

    /// `TypeError: an integer is required` — a non-integer `maxlen`.
    #[must_use]
    fn type_error_integer_required() -> RunError {
        SimpleException::new_msg(ExcType::TypeError, "an integer is required").into()
    }

    /// `TypeError: 'X' object cannot be interpreted as an integer`.
    #[must_use]
    fn type_error_not_an_integer(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("'{type_}' object cannot be interpreted as an integer"),
        )
        .into()
    }

    /// `TypeError: sequence index must be integer, not 'X'` — deque indexing with a
    /// slice or other non-integer key.
    #[must_use]
    fn type_error_sequence_index(type_: &str) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("sequence index must be integer, not '{type_}'"),
        )
        .into()
    }

    /// `TypeError: deque() takes at most 2 arguments (N given)` — CPython's own
    /// wording, which no `FromArgs` style reproduces.
    #[must_use]
    fn type_error_deque_too_many_args(given: usize) -> RunError {
        SimpleException::new_msg(
            ExcType::TypeError,
            format!("deque() takes at most 2 arguments ({given} given)"),
        )
        .into()
    }
}

impl ExcTypeExt for ExcType {
    /// Creates an exception instance from an exception type and arguments.
    ///
    /// Handles exception constructors like `ValueError('message')`.
    /// Currently supports zero or one string argument.
    ///
    /// The `interns` parameter provides access to interned string content.
    /// Returns a heap-allocated exception value.
    fn call(self, vm: &mut VM<'_>, args: ArgValues) -> RunResult<Value> {
        defer_drop!(args, vm);
        let exc = match args {
            ArgValues::Empty => Ok(SimpleException::new_none(self)),
            ArgValues::One(value) => match value {
                Value::InternString(string_id) => Ok(SimpleException::new_msg(
                    self,
                    vm.interns.get_str(*string_id).to_owned(),
                )),
                Value::Ref(heap_id) => {
                    if let HeapData::Str(s) = vm.heap.get(*heap_id) {
                        Ok(SimpleException::new_msg(self, s.as_str().to_owned()))
                    } else {
                        Err(RunError::internal(
                            "exceptions can only be called with zero or one string argument",
                        ))
                    }
                }
                _ => Err(RunError::internal(
                    "exceptions can only be called with zero or one string argument",
                )),
            },
            _ => Err(RunError::internal(
                "exceptions can only be called with zero or one string argument",
            )),
        }?;
        let heap_id = vm.heap.allocate(HeapData::Exception(exc));
        Ok(Value::Ref(heap_id))
    }
}

/// Simple lightweight representation of an exception.
///
/// This is used for performance reasons for common exception patterns.
/// Exception messages use `String` for owned storage.
#[derive(Debug, Clone, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) struct SimpleException {
    exc_type: ExcType,
    arg: Option<String>,
    /// Structured payload (e.g. unicode-error constructor fields), carried
    /// through catch/re-raise so it reaches the public `MontyException` when
    /// the exception escapes the sandbox. No `skip_serializing_if`:
    /// exceptions round-trip through non-self-describing snapshot formats
    /// where skipped fields break deserialization.
    #[serde(default)]
    data: ExcData,
}

impl fmt::Display for SimpleException {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.py_repr_fmt(f)
    }
}
impl From<MontyException> for SimpleException {
    fn from(mut exc: MontyException) -> Self {
        Self {
            exc_type: exc.exc_type(),
            data: exc.take_data(),
            arg: exc.into_message(),
        }
    }
}

impl SimpleException {
    /// Creates a new exception with the given type and optional argument message.
    #[must_use]
    pub fn new(exc_type: ExcType, arg: Option<String>) -> Self {
        Self {
            exc_type,
            arg,
            data: ExcData::None,
        }
    }

    /// Creates a new exception with the given type and argument message.
    #[must_use]
    pub fn new_msg(exc_type: ExcType, arg: impl fmt::Display) -> Self {
        Self {
            exc_type,
            arg: Some(arg.to_string()),
            data: ExcData::None,
        }
    }

    /// Creates a new exception with the given type and no argument message.
    #[must_use]
    pub fn new_none(exc_type: ExcType) -> Self {
        Self {
            exc_type,
            arg: None,
            data: ExcData::None,
        }
    }

    /// Attaches a structured payload — see [`ExcData`].
    #[must_use]
    pub fn with_data(mut self, data: ExcData) -> Self {
        self.data = data;
        self
    }

    #[must_use]
    pub fn exc_type(&self) -> ExcType {
        self.exc_type
    }

    #[must_use]
    pub fn arg(&self) -> Option<&String> {
        self.arg.as_ref()
    }

    /// str() for an exception
    #[must_use]
    pub fn py_str(&self) -> String {
        match (self.exc_type, &self.arg) {
            // KeyError expecificaly uses repr of the key for str(exc)
            (ExcType::KeyError, Some(exc)) => StringRepr(exc).to_string(),
            (_, Some(arg)) => arg.to_owned(),
            (_, None) => String::new(),
        }
    }
}

impl<'h> HeapRead<'h, SimpleException> {
    pub(crate) fn py_type(&self, vm: &VM<'h>) -> Type {
        Type::Exception(self.get(vm.heap).exc_type)
    }
}

impl SimpleException {
    /// Returns the exception formatted as Python would repr it.
    pub fn py_repr_fmt(&self, f: &mut impl Write) -> fmt::Result {
        let type_str: &'static str = self.exc_type.into();
        write!(f, "{type_str}(")?;

        if let Some(arg) = &self.arg {
            string_repr_fmt(arg, f)?;
        }

        f.write_char(')')
    }

    pub(crate) fn with_position(self, position: CodeRange) -> ExceptionRaise {
        ExceptionRaise {
            exc: self,
            frame: Some(RawStackFrame::from_position(position)),
            hide_caret: false,
        }
    }
}

impl<'h> HeapRead<'h, SimpleException> {
    /// Gets an attribute from this exception.
    ///
    /// Handles the `.args` attribute by allocating a tuple containing the message.
    /// Returns `None` for all other attributes.
    pub fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> Option<CallResult> {
        // Fast path: interned strings can be matched by ID
        let is_args = attr
            .static_string()
            .map_or_else(|| attr.as_str(vm.interns) == "args", |ss| ss == StaticStrings::Args);

        if is_args {
            // Construct tuple with 0 or 1 elements based on whether arg exists
            let elements = if let Some(arg_str) = &self.get(vm.heap).arg {
                smallvec![allocate_string(arg_str.as_str(), vm.heap)]
            } else {
                smallvec![]
            };
            Some(CallResult::Value(allocate_tuple(elements, vm.heap)))
        } else {
            None
        }
    }
}

/// A raised exception with optional stack frame for traceback.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExceptionRaise {
    pub exc: SimpleException,
    /// The stack frame where the exception was raised (first in vec is closest "bottom" frame).
    pub frame: Option<RawStackFrame>,
    /// Whether to hide the caret marker when creating the stack frame.
    ///
    /// CPython doesn't show carets for attribute GET errors, but does show them
    /// for attribute SET errors. This flag allows error creators to specify
    /// whether the caret should be hidden.
    #[serde(default)]
    pub hide_caret: bool,
}

impl From<SimpleException> for ExceptionRaise {
    fn from(exc: SimpleException) -> Self {
        Self {
            exc,
            frame: None,
            hide_caret: false,
        }
    }
}

impl From<MontyException> for ExceptionRaise {
    fn from(exc: MontyException) -> Self {
        Self {
            exc: exc.into(),
            frame: None,
            hide_caret: false,
        }
    }
}

impl ExceptionRaise {
    /// Adds a caller's frame as the outermost frame in the traceback chain.
    ///
    /// This is used when an exception propagates up through call frames.
    /// The new frame becomes the ultimate parent (displayed first in traceback,
    /// since tracebacks show "most recent call last").
    ///
    /// Special case: If the innermost frame has no name yet (created with `with_position`),
    /// this sets its name instead of creating a new parent. This happens when the error
    /// is raised from a namespace lookup - the initial frame has the position but not
    /// the function name, which gets filled in as the error propagates.
    pub(crate) fn add_caller_frame(&mut self, position: CodeRange, name: StringId) {
        self.add_caller_frame_inner(position, name, false);
    }

    fn add_caller_frame_inner(&mut self, position: CodeRange, name: StringId, hide_caret: bool) {
        if let Some(ref mut frame) = self.frame {
            // If innermost frame has no name, set it instead of adding a parent
            // This handles errors from namespace lookups which create nameless frames
            if frame.frame_name.is_none() {
                frame.frame_name = Some(name);
                frame.hide_caret = hide_caret;
                return;
            }
            // Find the outermost frame (the one with no parent) and add the new frame as its parent
            let mut current = frame;
            while current.parent.is_some() {
                current = current.parent.as_mut().unwrap();
            }
            let mut new_frame = RawStackFrame::new(position, name, None);
            new_frame.hide_caret = hide_caret;
            current.parent = Some(Box::new(new_frame));
        } else {
            // No frame yet - create one
            let mut new_frame = RawStackFrame::new(position, name, None);
            new_frame.hide_caret = hide_caret;
            self.frame = Some(new_frame);
        }
    }

    /// Converts this exception to a `MontyException` for the public API.
    ///
    /// Uses `Interns` to resolve `StringId` references to actual strings.
    /// Extracts preview lines from the source code for traceback display.
    /// Converts this exception into a public `MontyException`, expanding each
    /// stack frame's raw byte offsets into lines/columns/preview text via a
    /// caller-provided source lookup.
    ///
    /// The caller must supply `source_for` so that frames whose `CodeRange`
    /// points into a *different* source than the one currently executing can
    /// still be resolved. In particular, REPL tracebacks can interleave
    /// frames from multiple snippets (e.g. calling into a function defined
    /// in an earlier feed); resolving those byte offsets against only the
    /// current snippet's source would produce wrong line/column/caret
    /// information. `source_for` is called per unique filename encountered
    /// in the traceback and its result is cached, so each source is scanned
    /// at most once regardless of how many frames share it.
    #[must_use]
    pub fn into_python_exception<'s>(
        self,
        interns: &Interns,
        source_for: impl Fn(&str) -> Option<&'s str>,
    ) -> MontyException {
        // Per-filename SourceMap cache. Typical tracebacks touch 1-3 unique
        // filenames so a tiny `Vec` beats a HashMap on both allocations and
        // lookup cost.
        let mut cache: Vec<(StringId, SourceMap<'s>)> = Vec::new();
        let traceback = self
            .frame
            .map(|frame| {
                let mut frames = Vec::new();
                let mut current = Some(&frame);
                while let Some(f) = current {
                    let fname_id = f.position.filename;
                    let sm_idx = if let Some(i) = cache.iter().position(|(k, _)| *k == fname_id) {
                        i
                    } else {
                        let fname = interns.get_str(fname_id);
                        let src = source_for(fname).unwrap_or("");
                        cache.push((fname_id, SourceMap::new(src)));
                        cache.len() - 1
                    };
                    frames.push(StackFrame::from_raw(f, interns, &mut cache[sm_idx].1));
                    current = f.parent.as_deref();
                }
                // Reverse so outermost frame is first (Python's "most recent call last" ordering)
                frames.reverse();
                frames
            })
            .unwrap_or_default();

        MontyException::with_traceback(self.exc.exc_type, self.exc.arg, traceback).with_data(self.exc.data)
    }
}

/// A stack frame for traceback information.
///
/// Stores position information and optional function name as StringId.
/// The actual name string must be looked up externally when formatting the traceback.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RawStackFrame {
    pub position: CodeRange,
    /// The name of the frame (function name StringId, or None for module-level code).
    pub frame_name: Option<StringId>,
    pub parent: Option<Box<Self>>,
    /// Whether to hide the caret marker in the traceback for this frame.
    ///
    /// Set to `true` for:
    /// - `raise` statements (CPython doesn't show carets for raise)
    /// - `AttributeError` on attribute access (CPython doesn't show carets for these)
    pub hide_caret: bool,
}

impl RawStackFrame {
    pub(crate) fn new(position: CodeRange, frame_name: StringId, parent: Option<&Self>) -> Self {
        Self {
            position,
            frame_name: Some(frame_name),
            parent: parent.map(|p| Box::new(p.clone())),
            hide_caret: false,
        }
    }

    fn from_position(position: CodeRange) -> Self {
        Self {
            position,
            frame_name: None,
            parent: None,
            hide_caret: false,
        }
    }

    /// Creates a new frame for a raise statement (no caret will be shown).
    pub(crate) fn from_raise(position: CodeRange, frame_name: StringId) -> Self {
        Self {
            position,
            frame_name: Some(frame_name),
            parent: None,
            hide_caret: true,
        }
    }
}

/// Runtime error types that can occur during execution.
///
/// Three variants:
/// - `Internal`: Bug in interpreter implementation (static message)
/// - `Exc`: Python exception that can be caught by try/except (when implemented)
/// - `UncatchableExc`: Python exception from resource limits that CANNOT be caught
///
/// `Clone` is implemented so an error can be cached for later re-raising
/// (e.g. a failed `GatherFuture` replaying the same exception on every
/// re-await). Inner data is shallow-clonable: `Cow<'static, str>` is cheap,
/// and `ExceptionRaise` already derives `Clone`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub(crate) enum RunError {
    /// Internal interpreter error - indicates a bug in Monty, not user code.
    Internal(Cow<'static, str>),
    /// Catchable Python exception (e.g., ValueError, TypeError).
    Exc(ExceptionRaise),
    /// Uncatchable Python exception from resource limits (MemoryError, TimeoutError).
    ///
    /// These exceptions display with proper tracebacks like normal Python exceptions,
    /// but cannot be caught by try/except blocks. This prevents untrusted code from
    /// suppressing resource limit violations.
    UncatchableExc(ExceptionRaise),
}

impl From<ExceptionRaise> for RunError {
    fn from(exc: ExceptionRaise) -> Self {
        Self::Exc(exc)
    }
}

impl From<SimpleException> for RunError {
    fn from(exc: SimpleException) -> Self {
        Self::Exc(exc.into())
    }
}

impl From<MontyException> for RunError {
    fn from(exc: MontyException) -> Self {
        Self::Exc(exc.into())
    }
}

impl From<FormatError> for RunError {
    fn from(err: FormatError) -> Self {
        let exc_type = match &err {
            FormatError::Overflow(_) => ExcType::OverflowError,
            FormatError::InvalidAlignment(_) | FormatError::ValueError(_) => ExcType::ValueError,
        };
        Self::Exc(SimpleException::new_msg(exc_type, err).into())
    }
}

impl From<fmt::Error> for RunError {
    /// Converts a `fmt::Error` into a `RunError`.
    ///
    /// In practice, writing to a `String` buffer never fails, so `fmt::Error` only
    /// arises from our explicit error returns (e.g. INT_MAX_STR_DIGITS checks in
    /// `py_repr_fmt`). This impl exists so `write!()?` in `py_repr_fmt` auto-converts
    /// when the method returns `RunResult<()>`.
    fn from(err: fmt::Error) -> Self {
        Self::internal(format!("unexpected formatting error: {err}"))
    }
}

impl RunError {
    /// Whether this is a catchable `StopIteration`, i.e. a `__next__` reporting
    /// exhaustion.
    ///
    /// Excluding `UncatchableExc` is defensive — it is only ever built from a
    /// `ResourceError` — but spelled out so a future uncatchable variant cannot
    /// read as "the iterator finished", letting sandboxed code absorb its own
    /// limit breach.
    pub(crate) fn is_stop_iteration(&self) -> bool {
        matches!(self, Self::Exc(raise) if matches!(raise.exc.exc_type(), ExcType::StopIteration))
    }

    /// Converts this runtime error to a `MontyException` for the public API.
    ///
    /// Internal errors are converted to `RuntimeError` exceptions with no traceback.
    /// Converts this runtime error into a public `MontyException`.
    ///
    /// `source_for` is consulted per unique filename referenced by the
    /// traceback — see [`ExceptionRaise::into_python_exception`] for why
    /// this is a lookup rather than a single source string.
    #[must_use]
    pub fn into_python_exception<'s>(
        self,
        interns: &Interns,
        source_for: impl Fn(&str) -> Option<&'s str>,
    ) -> MontyException {
        match self {
            Self::Exc(exc) | Self::UncatchableExc(exc) => exc.into_python_exception(interns, source_for),
            Self::Internal(err) => MontyException::runtime_error(format!("Internal error in monty: {err}")),
        }
    }

    pub fn internal(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::Internal(msg.into())
    }
}

/// Formats a list of parameter names for error messages, matching CPython's
/// `format_missing` joining (note the Oxford comma for three or more names).
///
/// Examples:
/// - `["a"]` -> `'a'`
/// - `["a", "b"]` -> `'a' and 'b'`
/// - `["a", "b", "c"]` -> `'a', 'b', and 'c'`
fn format_param_names(names: &[&str]) -> String {
    match names.len() {
        0 => String::new(),
        1 => format!("'{}'", names[0]),
        2 => format!("'{}' and '{}'", names[0], names[1]),
        _ => {
            let last = names.last().unwrap();
            let rest: Vec<_> = names[..names.len() - 1].iter().map(|n| format!("'{n}'")).collect();
            format!("{}, and '{last}'", rest.join(", "))
        }
    }
}