rustpython-vm 0.5.0

RustPython virtual machine.
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
pub(crate) mod monitoring;

use crate::{Py, PyPayload, PyResult, VirtualMachine, builtins::PyModule, convert::ToPyObject};

#[cfg(all(not(feature = "host_env"), feature = "stdio"))]
pub(crate) use sys::SandboxStdio;
pub(crate) use sys::{DOC, MAXSIZE, RUST_MULTIARCH, UnraisableHookArgsData, module_def, multiarch};

#[pymodule(name = "_jit")]
mod sys_jit {
    /// Return True if the current Python executable supports JIT compilation,
    /// and False otherwise.
    #[pyfunction]
    const fn is_available() -> bool {
        false // RustPython has no JIT
    }

    /// Return True if JIT compilation is enabled for the current Python process,
    /// and False otherwise.
    #[pyfunction]
    const fn is_enabled() -> bool {
        false // RustPython has no JIT
    }

    /// Return True if the topmost Python frame is currently executing JIT code,
    /// and False otherwise.
    #[pyfunction]
    const fn is_active() -> bool {
        false // RustPython has no JIT
    }
}

#[pymodule]
mod sys {
    use crate::{
        AsObject, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult,
        builtins::{
            PyBaseExceptionRef, PyDictRef, PyFrozenSet, PyNamespace, PyStr, PyStrRef, PyTuple,
            PyTupleRef, PyTypeRef, PyUtf8StrRef,
        },
        common::{
            ascii,
            hash::{PyHash, PyUHash},
        },
        convert::ToPyObject,
        frame::{Frame, FrameRef},
        function::{FuncArgs, KwArgs, OptionalArg, PosArgs},
        stdlib::{_warnings::warn, builtins},
        types::PyStructSequence,
        version,
        vm::{Settings, VirtualMachine},
    };
    use core::sync::atomic::Ordering;
    use num_traits::ToPrimitive;
    use std::{
        env::{self, VarError},
        io::{IsTerminal, Read, Write},
    };

    #[cfg(windows)]
    use windows_sys::Win32::{
        Foundation::MAX_PATH,
        Storage::FileSystem::{
            GetFileVersionInfoSizeW, GetFileVersionInfoW, VS_FIXEDFILEINFO, VerQueryValueW,
        },
        System::LibraryLoader::{GetModuleFileNameW, GetModuleHandleW},
    };

    // Rust target triple (e.g., "x86_64-unknown-linux-gnu")
    pub(crate) const RUST_MULTIARCH: &str = env!("RUSTPYTHON_TARGET_TRIPLE");

    /// Convert Rust target triple to CPython-style multiarch
    /// e.g., "x86_64-unknown-linux-gnu" -> "x86_64-linux-gnu"
    pub(crate) fn multiarch() -> String {
        RUST_MULTIARCH.replace("-unknown", "")
    }

    #[pymodule(name = "monitoring", with(super::monitoring::sys_monitoring))]
    pub(super) mod monitoring {}

    #[pyclass(no_attr, name = "_BootstrapStderr")]
    #[derive(Debug, PyPayload)]
    pub(super) struct BootstrapStderr;

    #[pyclass]
    impl BootstrapStderr {
        #[pymethod]
        fn write(&self, s: PyStrRef) -> PyResult<usize> {
            let bytes = s.as_bytes();
            let _ = std::io::stderr().write_all(bytes);
            Ok(bytes.len())
        }

        #[pymethod]
        fn flush(&self) -> PyResult<()> {
            let _ = std::io::stderr().flush();
            Ok(())
        }
    }

    /// Lightweight stdio wrapper for sandbox mode (no host_env).
    /// Directly uses Rust's std::io for stdin/stdout/stderr without FileIO.
    #[pyclass(no_attr, name = "_SandboxStdio")]
    #[derive(Debug, PyPayload)]
    pub struct SandboxStdio {
        pub fd: i32,
        pub name: String,
        pub mode: String,
    }

    #[pyclass]
    impl SandboxStdio {
        #[pymethod]
        fn write(&self, s: PyStrRef, vm: &VirtualMachine) -> PyResult<usize> {
            if self.fd == 0 {
                return Err(vm.new_os_error("not writable".to_owned()));
            }
            let bytes = s.as_bytes();
            if self.fd == 2 {
                std::io::stderr()
                    .write_all(bytes)
                    .map_err(|e| vm.new_os_error(e.to_string()))?;
            } else {
                std::io::stdout()
                    .write_all(bytes)
                    .map_err(|e| vm.new_os_error(e.to_string()))?;
            }
            Ok(bytes.len())
        }

        #[pymethod]
        fn readline(&self, size: OptionalArg<isize>, vm: &VirtualMachine) -> PyResult<String> {
            if self.fd != 0 {
                return Err(vm.new_os_error("not readable".to_owned()));
            }
            let size = size.unwrap_or(-1);
            if size == 0 {
                return Ok(String::new());
            }
            let mut line = String::new();
            std::io::stdin()
                .read_line(&mut line)
                .map_err(|e| vm.new_os_error(e.to_string()))?;
            if size > 0 {
                line.truncate(size as usize);
            }
            Ok(line)
        }

        #[pymethod]
        fn flush(&self, vm: &VirtualMachine) -> PyResult<()> {
            match self.fd {
                1 => {
                    std::io::stdout()
                        .flush()
                        .map_err(|e| vm.new_os_error(e.to_string()))?;
                }
                2 => {
                    std::io::stderr()
                        .flush()
                        .map_err(|e| vm.new_os_error(e.to_string()))?;
                }
                _ => {}
            }
            Ok(())
        }

        #[pymethod]
        fn fileno(&self) -> i32 {
            self.fd
        }

        #[pymethod]
        fn isatty(&self) -> bool {
            match self.fd {
                0 => std::io::stdin().is_terminal(),
                1 => std::io::stdout().is_terminal(),
                2 => std::io::stderr().is_terminal(),
                _ => false,
            }
        }

        #[pymethod]
        fn readable(&self) -> bool {
            self.fd == 0
        }

        #[pymethod]
        fn writable(&self) -> bool {
            self.fd == 1 || self.fd == 2
        }

        #[pygetset]
        fn closed(&self) -> bool {
            false
        }

        #[pygetset]
        fn encoding(&self) -> String {
            "utf-8".to_owned()
        }

        #[pygetset]
        fn errors(&self) -> String {
            if self.fd == 2 {
                "backslashreplace"
            } else {
                "strict"
            }
            .to_owned()
        }

        #[pygetset(name = "name")]
        fn name_prop(&self) -> String {
            self.name.clone()
        }

        #[pygetset(name = "mode")]
        fn mode_prop(&self) -> String {
            self.mode.clone()
        }
    }

    #[pyattr(name = "_rustpython_debugbuild")]
    const RUSTPYTHON_DEBUGBUILD: bool = cfg!(debug_assertions);

    #[cfg(not(windows))]
    #[pyattr(name = "abiflags")]
    const ABIFLAGS_ATTR: &str = "t"; // 't' for free-threaded (no GIL)
    // Internal constant used for sysconfigdata_name
    pub const ABIFLAGS: &str = "t";
    #[pyattr(name = "api_version")]
    const API_VERSION: u32 = 0x0; // what C api?
    #[pyattr(name = "copyright")]
    const COPYRIGHT: &str = "Copyright (c) 2019 RustPython Team";
    #[pyattr(name = "float_repr_style")]
    const FLOAT_REPR_STYLE: &str = "short";
    #[pyattr(name = "_framework")]
    const FRAMEWORK: &str = "";
    #[pyattr(name = "hexversion")]
    const HEXVERSION: usize = version::VERSION_HEX;
    #[pyattr(name = "maxsize")]
    pub(crate) const MAXSIZE: isize = isize::MAX;
    #[pyattr(name = "maxunicode")]
    const MAXUNICODE: u32 = core::char::MAX as u32;
    #[pyattr(name = "platform")]
    pub const PLATFORM: &str = {
        cfg_if::cfg_if! {
            if #[cfg(target_os = "linux")] {
                "linux"
            } else if #[cfg(target_os = "android")] {
                "android"
            } else if #[cfg(target_os = "macos")] {
                "darwin"
            } else if #[cfg(target_os = "ios")] {
                "ios"
            } else if #[cfg(windows)] {
                "win32"
            } else if #[cfg(target_os = "wasi")] {
                "wasi"
            } else {
                "unknown"
            }
        }
    };
    #[pyattr(name = "ps1")]
    const PS1: &str = ">>>>> ";
    #[pyattr(name = "ps2")]
    const PS2: &str = "..... ";

    #[cfg(windows)]
    #[pyattr(name = "_vpath")]
    const VPATH: Option<&'static str> = None; // TODO: actual VPATH value

    #[cfg(windows)]
    #[pyattr(name = "dllhandle")]
    const DLLHANDLE: usize = 0;

    #[pyattr]
    fn prefix(vm: &VirtualMachine) -> String {
        vm.state.config.paths.prefix.clone()
    }
    #[pyattr]
    fn base_prefix(vm: &VirtualMachine) -> String {
        vm.state.config.paths.base_prefix.clone()
    }
    #[pyattr]
    fn exec_prefix(vm: &VirtualMachine) -> String {
        vm.state.config.paths.exec_prefix.clone()
    }
    #[pyattr]
    fn base_exec_prefix(vm: &VirtualMachine) -> String {
        vm.state.config.paths.base_exec_prefix.clone()
    }
    #[pyattr]
    fn platlibdir(_vm: &VirtualMachine) -> &'static str {
        option_env!("RUSTPYTHON_PLATLIBDIR").unwrap_or("lib")
    }
    #[pyattr]
    fn _stdlib_dir(vm: &VirtualMachine) -> PyObjectRef {
        vm.state.config.paths.stdlib_dir.clone().to_pyobject(vm)
    }

    // alphabetical order with segments of pyattr and others

    #[pyattr]
    fn argv(vm: &VirtualMachine) -> Vec<PyObjectRef> {
        vm.state
            .config
            .settings
            .argv
            .iter()
            .map(|arg| vm.ctx.new_str(arg.clone()).into())
            .collect()
    }

    #[pyattr]
    fn builtin_module_names(vm: &VirtualMachine) -> PyTupleRef {
        let mut module_names: Vec<String> =
            vm.state.module_defs.keys().map(|&s| s.to_owned()).collect();
        module_names.push("sys".to_owned());
        module_names.push("builtins".to_owned());

        module_names.sort();
        vm.ctx.new_tuple(
            module_names
                .into_iter()
                .map(|n| vm.ctx.new_str(n).into())
                .collect(),
        )
    }

    // List from cpython/Python/stdlib_module_names.h
    const STDLIB_MODULE_NAMES: &[&str] = &[
        "__future__",
        "_abc",
        "_aix_support",
        "_android_support",
        "_apple_support",
        "_ast",
        "_asyncio",
        "_bisect",
        "_blake2",
        "_bz2",
        "_codecs",
        "_codecs_cn",
        "_codecs_hk",
        "_codecs_iso2022",
        "_codecs_jp",
        "_codecs_kr",
        "_codecs_tw",
        "_collections",
        "_collections_abc",
        "_colorize",
        "_compat_pickle",
        "_compression",
        "_contextvars",
        "_csv",
        "_ctypes",
        "_curses",
        "_curses_panel",
        "_datetime",
        "_dbm",
        "_decimal",
        "_elementtree",
        "_frozen_importlib",
        "_frozen_importlib_external",
        "_functools",
        "_gdbm",
        "_hashlib",
        "_heapq",
        "_imp",
        "_interpchannels",
        "_interpqueues",
        "_interpreters",
        "_io",
        "_ios_support",
        "_json",
        "_locale",
        "_lsprof",
        "_lzma",
        "_markupbase",
        "_md5",
        "_multibytecodec",
        "_multiprocessing",
        "_opcode",
        "_opcode_metadata",
        "_operator",
        "_osx_support",
        "_overlapped",
        "_pickle",
        "_posixshmem",
        "_posixsubprocess",
        "_py_abc",
        "_pydatetime",
        "_pydecimal",
        "_pyio",
        "_pylong",
        "_pyrepl",
        "_queue",
        "_random",
        "_scproxy",
        "_sha1",
        "_sha2",
        "_sha3",
        "_signal",
        "_sitebuiltins",
        "_socket",
        "_sqlite3",
        "_sre",
        "_ssl",
        "_stat",
        "_statistics",
        "_string",
        "_strptime",
        "_struct",
        "_suggestions",
        "_symtable",
        "_sysconfig",
        "_thread",
        "_threading_local",
        "_tkinter",
        "_tokenize",
        "_tracemalloc",
        "_typing",
        "_uuid",
        "_warnings",
        "_weakref",
        "_weakrefset",
        "_winapi",
        "_wmi",
        "_zoneinfo",
        "abc",
        "antigravity",
        "argparse",
        "array",
        "ast",
        "asyncio",
        "atexit",
        "base64",
        "bdb",
        "binascii",
        "bisect",
        "builtins",
        "bz2",
        "cProfile",
        "calendar",
        "cmath",
        "cmd",
        "code",
        "codecs",
        "codeop",
        "collections",
        "colorsys",
        "compileall",
        "concurrent",
        "configparser",
        "contextlib",
        "contextvars",
        "copy",
        "copyreg",
        "csv",
        "ctypes",
        "curses",
        "dataclasses",
        "datetime",
        "dbm",
        "decimal",
        "difflib",
        "dis",
        "doctest",
        "email",
        "encodings",
        "ensurepip",
        "enum",
        "errno",
        "faulthandler",
        "fcntl",
        "filecmp",
        "fileinput",
        "fnmatch",
        "fractions",
        "ftplib",
        "functools",
        "gc",
        "genericpath",
        "getopt",
        "getpass",
        "gettext",
        "glob",
        "graphlib",
        "grp",
        "gzip",
        "hashlib",
        "heapq",
        "hmac",
        "html",
        "http",
        "idlelib",
        "imaplib",
        "importlib",
        "inspect",
        "io",
        "ipaddress",
        "itertools",
        "json",
        "keyword",
        "linecache",
        "locale",
        "logging",
        "lzma",
        "mailbox",
        "marshal",
        "math",
        "mimetypes",
        "mmap",
        "modulefinder",
        "msvcrt",
        "multiprocessing",
        "netrc",
        "nt",
        "ntpath",
        "nturl2path",
        "numbers",
        "opcode",
        "operator",
        "optparse",
        "os",
        "pathlib",
        "pdb",
        "pickle",
        "pickletools",
        "pkgutil",
        "platform",
        "plistlib",
        "poplib",
        "posix",
        "posixpath",
        "pprint",
        "profile",
        "pstats",
        "pty",
        "pwd",
        "py_compile",
        "pyclbr",
        "pydoc",
        "pydoc_data",
        "pyexpat",
        "queue",
        "quopri",
        "random",
        "re",
        "readline",
        "reprlib",
        "resource",
        "rlcompleter",
        "runpy",
        "sched",
        "secrets",
        "select",
        "selectors",
        "shelve",
        "shlex",
        "shutil",
        "signal",
        "site",
        "smtplib",
        "socket",
        "socketserver",
        "sqlite3",
        "sre_compile",
        "sre_constants",
        "sre_parse",
        "ssl",
        "stat",
        "statistics",
        "string",
        "stringprep",
        "struct",
        "subprocess",
        "symtable",
        "sys",
        "sysconfig",
        "syslog",
        "tabnanny",
        "tarfile",
        "tempfile",
        "termios",
        "textwrap",
        "this",
        "threading",
        "time",
        "timeit",
        "tkinter",
        "token",
        "tokenize",
        "tomllib",
        "trace",
        "traceback",
        "tracemalloc",
        "tty",
        "turtle",
        "turtledemo",
        "types",
        "typing",
        "unicodedata",
        "unittest",
        "urllib",
        "uuid",
        "venv",
        "warnings",
        "wave",
        "weakref",
        "webbrowser",
        "winreg",
        "winsound",
        "wsgiref",
        "xml",
        "xmlrpc",
        "zipapp",
        "zipfile",
        "zipimport",
        "zlib",
        "zoneinfo",
    ];

    #[pyattr(once)]
    fn stdlib_module_names(vm: &VirtualMachine) -> PyObjectRef {
        let names = STDLIB_MODULE_NAMES
            .iter()
            .map(|&n| vm.ctx.new_str(n).into());
        PyFrozenSet::from_iter(vm, names)
            .expect("Creating stdlib_module_names frozen set must succeed")
            .to_pyobject(vm)
    }

    #[pyattr]
    fn byteorder(vm: &VirtualMachine) -> PyStrRef {
        // https://doc.rust-lang.org/reference/conditional-compilation.html#target_endian
        vm.ctx
            .intern_str(if cfg!(target_endian = "little") {
                "little"
            } else if cfg!(target_endian = "big") {
                "big"
            } else {
                "unknown"
            })
            .to_owned()
    }

    #[pyattr]
    fn _base_executable(vm: &VirtualMachine) -> String {
        vm.state.config.paths.base_executable.clone()
    }

    #[pyattr]
    fn dont_write_bytecode(vm: &VirtualMachine) -> bool {
        !vm.state.config.settings.write_bytecode
    }

    #[pyattr]
    fn executable(vm: &VirtualMachine) -> String {
        vm.state.config.paths.executable.clone()
    }

    #[pyattr]
    fn _git(vm: &VirtualMachine) -> PyTupleRef {
        vm.new_tuple((
            ascii!("RustPython"),
            version::get_git_identifier(),
            version::get_git_revision(),
        ))
    }

    #[pyattr]
    fn implementation(vm: &VirtualMachine) -> PyRef<PyNamespace> {
        const NAME: &str = "rustpython";

        let cache_tag = format!("{NAME}-{}{}", version::MAJOR, version::MINOR);
        let ctx = &vm.ctx;
        py_namespace!(vm, {
            "name" => ctx.new_str(NAME),
            "cache_tag" => ctx.new_str(cache_tag),
            "_multiarch" => ctx.new_str(multiarch()),
            "version" => version_info(vm),
            "hexversion" => ctx.new_int(version::VERSION_HEX),
            "supports_isolated_interpreters" => ctx.new_bool(false),
        })
    }

    #[pyattr]
    const fn meta_path(_vm: &VirtualMachine) -> Vec<PyObjectRef> {
        Vec::new()
    }

    #[pyattr]
    fn orig_argv(vm: &VirtualMachine) -> Vec<PyObjectRef> {
        env::args().map(|arg| vm.ctx.new_str(arg).into()).collect()
    }

    #[pyattr]
    fn path(vm: &VirtualMachine) -> Vec<PyObjectRef> {
        vm.state
            .config
            .paths
            .module_search_paths
            .iter()
            .map(|path| vm.ctx.new_str(path.clone()).into())
            .collect()
    }

    #[pyattr]
    const fn path_hooks(_vm: &VirtualMachine) -> Vec<PyObjectRef> {
        Vec::new()
    }

    #[pyattr]
    fn path_importer_cache(vm: &VirtualMachine) -> PyDictRef {
        vm.ctx.new_dict()
    }

    #[pyattr]
    fn pycache_prefix(vm: &VirtualMachine) -> PyObjectRef {
        vm.ctx.none()
    }

    #[pyattr]
    fn version(_vm: &VirtualMachine) -> String {
        version::get_version()
    }

    #[cfg(windows)]
    #[pyattr]
    fn winver(_vm: &VirtualMachine) -> String {
        // Note: This is Python DLL version in CPython, but we arbitrary fill it for compatibility
        version::get_winver_number()
    }

    #[pyattr]
    fn _xoptions(vm: &VirtualMachine) -> PyDictRef {
        let ctx = &vm.ctx;
        let xopts = ctx.new_dict();
        for (key, value) in &vm.state.config.settings.xoptions {
            let value = value.as_ref().map_or_else(
                || ctx.new_bool(true).into(),
                |s| ctx.new_str(s.clone()).into(),
            );
            xopts.set_item(&**key, value, vm).unwrap();
        }
        xopts
    }

    #[pyattr]
    fn warnoptions(vm: &VirtualMachine) -> Vec<PyObjectRef> {
        vm.state
            .config
            .settings
            .warnoptions
            .iter()
            .map(|s| vm.ctx.new_str(s.clone()).into())
            .collect()
    }

    #[cfg(feature = "rustpython-compiler")]
    #[pyfunction]
    fn _baserepl(vm: &VirtualMachine) -> PyResult<()> {
        // read stdin to end
        let stdin = std::io::stdin();
        let mut handle = stdin.lock();
        let mut source = String::new();
        handle
            .read_to_string(&mut source)
            .map_err(|e| vm.new_os_error(format!("Error reading from stdin: {e}")))?;
        vm.compile(&source, crate::compiler::Mode::Single, "<stdin>".to_owned())
            .map_err(|e| vm.new_os_error(format!("Error running stdin: {e}")))?;
        Ok(())
    }

    #[pyfunction]
    fn audit(_args: FuncArgs) {
        // TODO: sys.audit implementation
    }

    #[pyfunction]
    const fn _is_gil_enabled() -> bool {
        false // RustPython has no GIL (like free-threaded Python)
    }

    /// Return True if remote debugging is enabled, False otherwise.
    #[pyfunction]
    const fn is_remote_debug_enabled() -> bool {
        false // RustPython does not support remote debugging
    }

    #[pyfunction]
    fn exit(code: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult {
        let status = code.unwrap_or_none(vm);
        let args = if let Some(status_tuple) = status.downcast_ref::<PyTuple>() {
            status_tuple.as_slice().to_vec()
        } else {
            vec![status]
        };
        let exc = vm.invoke_exception(vm.ctx.exceptions.system_exit.to_owned(), args)?;
        Err(exc)
    }

    #[pyfunction]
    fn call_tracing(func: PyObjectRef, args: PyTupleRef, vm: &VirtualMachine) -> PyResult {
        // CPython temporarily enables tracing state around this call.
        // RustPython does not currently model the full C-level tracing toggles,
        // but call semantics (func(*args)) are matched.
        func.call(PosArgs::new(args.as_slice().to_vec()), vm)
    }

    #[pyfunction]
    fn exception(vm: &VirtualMachine) -> Option<PyBaseExceptionRef> {
        vm.topmost_exception()
    }

    #[pyfunction(name = "__displayhook__")]
    #[pyfunction]
    fn displayhook(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
        // Save non-None values as "_"
        if vm.is_none(&obj) {
            return Ok(());
        }
        // set to none to avoid recursion while printing
        vm.builtins.set_attr("_", vm.ctx.none(), vm)?;
        // TODO: catch encoding errors
        let repr = obj.repr(vm)?.into();
        builtins::print(PosArgs::new(vec![repr]), Default::default(), vm)?;
        vm.builtins.set_attr("_", obj, vm)?;
        Ok(())
    }

    #[pyfunction(name = "__excepthook__")]
    #[pyfunction]
    fn excepthook(
        exc_type: PyObjectRef,
        exc_val: PyObjectRef,
        exc_tb: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult<()> {
        let stderr = super::get_stderr(vm)?;
        match vm.normalize_exception(exc_type.clone(), exc_val.clone(), exc_tb) {
            Ok(exc) => {
                // PyErr_Display: try traceback._print_exception_bltin first
                if let Ok(tb_mod) = vm.import("traceback", 0)
                    && let Ok(print_exc_builtin) = tb_mod.get_attr("_print_exception_bltin", vm)
                    && print_exc_builtin
                        .call((exc.as_object().to_owned(),), vm)
                        .is_ok()
                {
                    return Ok(());
                }
                // Fallback to Rust-level exception printing
                vm.write_exception(&mut crate::py_io::PyWriter(stderr, vm), &exc)
            }
            Err(_) => {
                let type_name = exc_val.class().name();
                let msg = format!(
                    "TypeError: print_exception(): Exception expected for value, {type_name} found\n"
                );
                use crate::py_io::Write;
                write!(&mut crate::py_io::PyWriter(stderr, vm), "{msg}")?;
                Ok(())
            }
        }
    }

    #[pyfunction(name = "__breakpointhook__")]
    #[pyfunction]
    pub fn breakpointhook(args: FuncArgs, vm: &VirtualMachine) -> PyResult {
        let env_var = std::env::var("PYTHONBREAKPOINT")
            .and_then(|env_var| {
                if env_var.is_empty() {
                    Err(VarError::NotPresent)
                } else {
                    Ok(env_var)
                }
            })
            .unwrap_or_else(|_| "pdb.set_trace".to_owned());

        if env_var.eq("0") {
            return Ok(vm.ctx.none());
        };

        let print_unimportable_module_warn = || {
            warn(
                vm.ctx.exceptions.runtime_warning,
                format!("Ignoring unimportable $PYTHONBREAKPOINT: \"{env_var}\"",),
                0,
                vm,
            )
            .unwrap();
            Ok(vm.ctx.none())
        };

        let last = match env_var.rsplit_once('.') {
            Some((_, last)) => last,
            None if !env_var.is_empty() => env_var.as_str(),
            _ => return print_unimportable_module_warn(),
        };

        let (module_path, attr_name) = if last == env_var {
            ("builtins", env_var.as_str())
        } else {
            (&env_var[..(env_var.len() - last.len() - 1)], last)
        };

        let module = match vm.import(&vm.ctx.new_str(module_path), 0) {
            Ok(module) => module,
            Err(_) => {
                return print_unimportable_module_warn();
            }
        };

        match vm.get_attribute_opt(module, &vm.ctx.new_str(attr_name)) {
            Ok(Some(hook)) => hook.as_ref().call(args, vm),
            _ => print_unimportable_module_warn(),
        }
    }

    #[pyfunction]
    fn exc_info(vm: &VirtualMachine) -> (PyObjectRef, PyObjectRef, PyObjectRef) {
        match vm.topmost_exception() {
            Some(exception) => vm.split_exception(exception),
            None => (vm.ctx.none(), vm.ctx.none(), vm.ctx.none()),
        }
    }

    #[pyattr]
    fn flags(vm: &VirtualMachine) -> PyTupleRef {
        PyFlags::from_data(FlagsData::from_settings(&vm.state.config.settings), vm)
    }

    #[pyattr]
    fn float_info(vm: &VirtualMachine) -> PyTupleRef {
        PyFloatInfo::from_data(FloatInfoData::INFO, vm)
    }

    #[pyfunction]
    const fn getdefaultencoding() -> &'static str {
        crate::codecs::DEFAULT_ENCODING
    }

    #[pyfunction]
    fn getrefcount(obj: PyObjectRef) -> usize {
        obj.strong_count()
    }

    #[pyfunction]
    fn getrecursionlimit(vm: &VirtualMachine) -> usize {
        vm.recursion_limit.get()
    }

    #[derive(FromArgs)]
    struct GetsizeofArgs {
        obj: PyObjectRef,
        #[pyarg(any, optional)]
        default: Option<PyObjectRef>,
    }

    #[pyfunction]
    fn getsizeof(args: GetsizeofArgs, vm: &VirtualMachine) -> PyResult {
        let sizeof = || -> PyResult<usize> {
            let res = vm.call_special_method(&args.obj, identifier!(vm, __sizeof__), ())?;
            let res = res.try_index(vm)?.try_to_primitive::<usize>(vm)?;
            Ok(res + core::mem::size_of::<PyObject>())
        };
        sizeof()
            .map(|x| vm.ctx.new_int(x).into())
            .or_else(|err| args.default.ok_or(err))
    }

    #[pyfunction]
    fn getfilesystemencoding(vm: &VirtualMachine) -> PyStrRef {
        vm.fs_encoding().to_owned()
    }

    #[pyfunction]
    fn getfilesystemencodeerrors(vm: &VirtualMachine) -> PyUtf8StrRef {
        vm.fs_encode_errors().to_owned()
    }

    #[pyfunction]
    fn getprofile(vm: &VirtualMachine) -> PyObjectRef {
        vm.profile_func.borrow().clone()
    }

    #[pyfunction]
    fn _getframe(offset: OptionalArg<usize>, vm: &VirtualMachine) -> PyResult<FrameRef> {
        let offset = offset.into_option().unwrap_or(0);
        let frames = vm.frames.borrow();
        if offset >= frames.len() {
            return Err(vm.new_value_error("call stack is not deep enough"));
        }
        let idx = frames.len() - offset - 1;
        // SAFETY: the FrameRef is alive on the call stack while it's in the Vec
        let py: &crate::Py<Frame> = unsafe { frames[idx].as_ref() };
        Ok(py.to_owned())
    }

    #[pyfunction]
    fn _getframemodulename(depth: OptionalArg<usize>, vm: &VirtualMachine) -> PyResult {
        let depth = depth.into_option().unwrap_or(0);

        // Get the frame at the specified depth
        let func_obj = {
            let frames = vm.frames.borrow();
            if depth >= frames.len() {
                return Ok(vm.ctx.none());
            }
            let idx = frames.len() - depth - 1;
            // SAFETY: the FrameRef is alive on the call stack while it's in the Vec
            let frame: &crate::Py<Frame> = unsafe { frames[idx].as_ref() };
            frame.func_obj.clone()
        };

        // If the frame has a function object, return its __module__ attribute
        if let Some(func_obj) = func_obj {
            match func_obj.get_attr(identifier!(vm, __module__), vm) {
                Ok(module) => Ok(module),
                Err(_) => {
                    // CPython clears the error and returns None
                    Ok(vm.ctx.none())
                }
            }
        } else {
            Ok(vm.ctx.none())
        }
    }

    /// Return a dictionary mapping each thread's identifier to the topmost stack frame
    /// currently active in that thread at the time the function is called.
    #[cfg(feature = "threading")]
    #[pyfunction]
    fn _current_frames(vm: &VirtualMachine) -> PyResult<PyDictRef> {
        use crate::AsObject;
        use crate::stdlib::_thread::get_all_current_frames;

        let frames = get_all_current_frames(vm);
        let dict = vm.ctx.new_dict();

        for (thread_id, frame) in frames {
            let key = vm.ctx.new_int(thread_id);
            dict.set_item(key.as_object(), frame.into(), vm)?;
        }

        Ok(dict)
    }

    /// Return a dictionary mapping each thread's identifier to its currently
    /// active exception, or None if no exception is active.
    #[cfg(feature = "threading")]
    #[pyfunction]
    fn _current_exceptions(vm: &VirtualMachine) -> PyResult<PyDictRef> {
        use crate::AsObject;
        use crate::vm::thread::get_all_current_exceptions;

        let dict = vm.ctx.new_dict();
        for (thread_id, exc) in get_all_current_exceptions(vm) {
            let key = vm.ctx.new_int(thread_id);
            let value = exc.map_or_else(|| vm.ctx.none(), |e| e.into());
            dict.set_item(key.as_object(), value, vm)?;
        }

        Ok(dict)
    }

    #[cfg(not(feature = "threading"))]
    #[pyfunction]
    fn _current_exceptions(vm: &VirtualMachine) -> PyResult<PyDictRef> {
        let dict = vm.ctx.new_dict();
        let key = vm.ctx.new_int(0);
        dict.set_item(key.as_object(), vm.topmost_exception().to_pyobject(vm), vm)?;
        Ok(dict)
    }

    /// Stub for non-threading builds - returns empty dict
    #[cfg(not(feature = "threading"))]
    #[pyfunction]
    fn _current_frames(vm: &VirtualMachine) -> PyResult<PyDictRef> {
        Ok(vm.ctx.new_dict())
    }

    #[pyfunction]
    fn gettrace(vm: &VirtualMachine) -> PyObjectRef {
        vm.trace_func.borrow().clone()
    }

    #[cfg(windows)]
    fn get_kernel32_version() -> std::io::Result<(u32, u32, u32)> {
        use crate::common::windows::ToWideString;
        unsafe {
            // Create a wide string for "kernel32.dll"
            let module_name: Vec<u16> = std::ffi::OsStr::new("kernel32.dll").to_wide_with_nul();
            let h_kernel32 = GetModuleHandleW(module_name.as_ptr());
            if h_kernel32.is_null() {
                return Err(std::io::Error::last_os_error());
            }

            // Prepare a buffer for the module file path
            let mut kernel32_path = [0u16; MAX_PATH as usize];
            let len = GetModuleFileNameW(
                h_kernel32,
                kernel32_path.as_mut_ptr(),
                kernel32_path.len() as u32,
            );
            if len == 0 {
                return Err(std::io::Error::last_os_error());
            }

            // Get the size of the version information block
            let ver_block_size =
                GetFileVersionInfoSizeW(kernel32_path.as_ptr(), core::ptr::null_mut());
            if ver_block_size == 0 {
                return Err(std::io::Error::last_os_error());
            }

            // Allocate a buffer to hold the version information
            let mut ver_block = vec![0u8; ver_block_size as usize];
            if GetFileVersionInfoW(
                kernel32_path.as_ptr(),
                0,
                ver_block_size,
                ver_block.as_mut_ptr() as *mut _,
            ) == 0
            {
                return Err(std::io::Error::last_os_error());
            }

            // Prepare an empty sub-block string (L"") as required by VerQueryValueW
            let sub_block: Vec<u16> = std::ffi::OsStr::new("").to_wide_with_nul();

            let mut ffi_ptr: *mut VS_FIXEDFILEINFO = core::ptr::null_mut();
            let mut ffi_len: u32 = 0;
            if VerQueryValueW(
                ver_block.as_ptr() as *const _,
                sub_block.as_ptr(),
                &mut ffi_ptr as *mut *mut VS_FIXEDFILEINFO as *mut *mut _,
                &mut ffi_len as *mut u32,
            ) == 0
                || ffi_ptr.is_null()
            {
                return Err(std::io::Error::last_os_error());
            }

            // Extract the version numbers from the VS_FIXEDFILEINFO structure.
            let ffi = *ffi_ptr;
            let real_major = (ffi.dwProductVersionMS >> 16) & 0xFFFF;
            let real_minor = ffi.dwProductVersionMS & 0xFFFF;
            let real_build = (ffi.dwProductVersionLS >> 16) & 0xFFFF;

            Ok((real_major, real_minor, real_build))
        }
    }

    #[cfg(windows)]
    #[pyfunction]
    fn getwindowsversion(vm: &VirtualMachine) -> PyResult<crate::builtins::tuple::PyTupleRef> {
        use std::ffi::OsString;
        use std::os::windows::ffi::OsStringExt;
        use windows_sys::Win32::System::SystemInformation::{
            GetVersionExW, OSVERSIONINFOEXW, OSVERSIONINFOW,
        };

        let mut version: OSVERSIONINFOEXW = unsafe { core::mem::zeroed() };
        version.dwOSVersionInfoSize = core::mem::size_of::<OSVERSIONINFOEXW>() as u32;
        let result = unsafe {
            let os_vi = &mut version as *mut OSVERSIONINFOEXW as *mut OSVERSIONINFOW;
            // SAFETY: GetVersionExW accepts a pointer of OSVERSIONINFOW, but windows-sys crate's type currently doesn't allow to do so.
            // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getversionexw#parameters
            GetVersionExW(os_vi)
        };

        if result == 0 {
            return Err(vm.new_os_error("failed to get windows version".to_owned()));
        }

        let service_pack = {
            let (last, _) = version
                .szCSDVersion
                .iter()
                .take_while(|&x| x != &0)
                .enumerate()
                .last()
                .unwrap_or((0, &0));
            let sp = OsString::from_wide(&version.szCSDVersion[..last]);
            sp.into_string()
                .map_err(|_| vm.new_os_error("service pack is not ASCII".to_owned()))?
        };
        let real_version = get_kernel32_version().map_err(|e| vm.new_os_error(e.to_string()))?;
        let winver = WindowsVersionData {
            major: real_version.0,
            minor: real_version.1,
            build: real_version.2,
            platform: version.dwPlatformId,
            service_pack,
            service_pack_major: version.wServicePackMajor,
            service_pack_minor: version.wServicePackMinor,
            suite_mask: version.wSuiteMask,
            product_type: version.wProductType,
            platform_version: (real_version.0, real_version.1, real_version.2), // TODO Provide accurate version, like CPython impl
        };
        Ok(PyWindowsVersion::from_data(winver, vm))
    }

    fn _unraisablehook(unraisable: UnraisableHookArgsData, vm: &VirtualMachine) -> PyResult<()> {
        use super::PyStderr;

        let stderr = PyStderr(vm);
        if !vm.is_none(&unraisable.object) {
            if !vm.is_none(&unraisable.err_msg) {
                write!(stderr, "{}: ", unraisable.err_msg.str(vm)?);
            } else {
                write!(stderr, "Exception ignored in: ");
            }
            // exception in del will be ignored but printed
            let repr = &unraisable.object.repr(vm);
            let str = match repr {
                Ok(v) => v.to_string(),
                Err(_) => format!(
                    "<object {} repr() failed>",
                    unraisable.object.class().name()
                ),
            };
            writeln!(stderr, "{str}");
        } else if !vm.is_none(&unraisable.err_msg) {
            writeln!(stderr, "{}:", unraisable.err_msg.str(vm)?);
        }

        // Print traceback (using actual exc_traceback, not current stack)
        if !vm.is_none(&unraisable.exc_traceback) {
            let tb_module = vm.import("traceback", 0)?;
            let print_tb = tb_module.get_attr("print_tb", vm)?;
            let stderr_obj = super::get_stderr(vm)?;
            let kwargs: KwArgs = [("file".to_string(), stderr_obj)].into_iter().collect();
            let _ = print_tb.call(
                FuncArgs::new(vec![unraisable.exc_traceback.clone()], kwargs),
                vm,
            );
        }

        // Check exc_type
        if vm.is_none(unraisable.exc_type.as_object()) {
            return Ok(());
        }
        assert!(
            unraisable
                .exc_type
                .fast_issubclass(vm.ctx.exceptions.base_exception_type)
        );

        // Print module name (if not builtins or __main__)
        let module_name = unraisable.exc_type.__module__(vm);
        if let Ok(module_str) = module_name.downcast::<PyStr>() {
            let module = module_str.as_wtf8();
            if module != "builtins" && module != "__main__" {
                write!(stderr, "{}.", module);
            }
        } else {
            write!(stderr, "<unknown>.");
        }

        // Print qualname
        let qualname = unraisable.exc_type.__qualname__(vm);
        if let Ok(qualname_str) = qualname.downcast::<PyStr>() {
            write!(stderr, "{}", qualname_str.as_wtf8());
        } else {
            write!(stderr, "{}", unraisable.exc_type.name());
        }

        // Print exception value
        if !vm.is_none(&unraisable.exc_value) {
            write!(stderr, ": ");
            if let Ok(str) = unraisable.exc_value.str(vm) {
                write!(stderr, "{}", str.as_wtf8());
            } else {
                write!(stderr, "<exception str() failed>");
            }
        }
        writeln!(stderr);

        // Flush stderr
        if let Ok(stderr_obj) = super::get_stderr(vm)
            && let Ok(flush) = stderr_obj.get_attr("flush", vm)
        {
            let _ = flush.call((), vm);
        }

        Ok(())
    }

    #[pyattr]
    #[pyfunction(name = "__unraisablehook__")]
    fn unraisablehook(unraisable: UnraisableHookArgsData, vm: &VirtualMachine) {
        if let Err(e) = _unraisablehook(unraisable, vm) {
            let stderr = super::PyStderr(vm);
            writeln!(
                stderr,
                "{}",
                e.as_object()
                    .repr(vm)
                    .unwrap_or_else(|_| vm.ctx.empty_str.to_owned())
            );
        }
    }

    #[pyattr]
    fn hash_info(vm: &VirtualMachine) -> PyTupleRef {
        PyHashInfo::from_data(HashInfoData::INFO, vm)
    }

    #[pyfunction]
    fn intern(s: PyRefExact<PyStr>, vm: &VirtualMachine) -> PyRef<PyStr> {
        vm.ctx.intern_str(s).to_owned()
    }

    #[pyattr]
    fn int_info(vm: &VirtualMachine) -> PyTupleRef {
        PyIntInfo::from_data(IntInfoData::INFO, vm)
    }

    #[pyfunction]
    fn get_int_max_str_digits(vm: &VirtualMachine) -> usize {
        vm.state.int_max_str_digits.load()
    }

    #[pyfunction]
    fn set_int_max_str_digits(maxdigits: usize, vm: &VirtualMachine) -> PyResult<()> {
        let threshold = IntInfoData::INFO.str_digits_check_threshold;
        if maxdigits == 0 || maxdigits >= threshold {
            vm.state.int_max_str_digits.store(maxdigits);
            Ok(())
        } else {
            let error = format!("maxdigits must be 0 or larger than {threshold:?}");
            Err(vm.new_value_error(error))
        }
    }

    #[pyfunction]
    fn is_finalizing(vm: &VirtualMachine) -> bool {
        vm.state.finalizing.load(Ordering::Acquire)
    }

    #[pyfunction]
    fn setprofile(profilefunc: PyObjectRef, vm: &VirtualMachine) {
        vm.profile_func.replace(profilefunc);
        update_use_tracing(vm);
    }

    #[pyfunction]
    fn setrecursionlimit(recursion_limit: i32, vm: &VirtualMachine) -> PyResult<()> {
        let recursion_limit = recursion_limit
            .to_usize()
            .filter(|&u| u >= 1)
            .ok_or_else(|| {
                vm.new_value_error("recursion limit must be greater than or equal to one")
            })?;
        let recursion_depth = vm.current_recursion_depth();

        if recursion_limit > recursion_depth {
            vm.recursion_limit.set(recursion_limit);
            Ok(())
        } else {
            Err(vm.new_recursion_error(format!(
                "cannot set the recursion limit to {recursion_limit} at the recursion depth {recursion_depth}: the limit is too low"
            )))
        }
    }

    #[pyfunction]
    fn settrace(tracefunc: PyObjectRef, vm: &VirtualMachine) {
        vm.trace_func.replace(tracefunc);
        update_use_tracing(vm);
    }

    #[pyfunction]
    fn _settraceallthreads(tracefunc: PyObjectRef, vm: &VirtualMachine) {
        let func = (!vm.is_none(&tracefunc)).then(|| tracefunc.clone());
        *vm.state.global_trace_func.lock() = func;
        vm.trace_func.replace(tracefunc);
        update_use_tracing(vm);
    }

    #[pyfunction]
    fn _setprofileallthreads(profilefunc: PyObjectRef, vm: &VirtualMachine) {
        let func = (!vm.is_none(&profilefunc)).then(|| profilefunc.clone());
        *vm.state.global_profile_func.lock() = func;
        vm.profile_func.replace(profilefunc);
        update_use_tracing(vm);
    }

    #[cfg(feature = "threading")]
    #[pyattr]
    fn thread_info(vm: &VirtualMachine) -> PyTupleRef {
        PyThreadInfo::from_data(ThreadInfoData::INFO, vm)
    }

    #[pyattr]
    fn version_info(vm: &VirtualMachine) -> PyTupleRef {
        PyVersionInfo::from_data(VersionInfoData::VERSION, vm)
    }

    fn update_use_tracing(vm: &VirtualMachine) {
        let trace_is_none = vm.is_none(&vm.trace_func.borrow());
        let profile_is_none = vm.is_none(&vm.profile_func.borrow());
        let tracing = !(trace_is_none && profile_is_none);
        vm.use_tracing.set(tracing);
    }

    #[pyfunction]
    fn set_coroutine_origin_tracking_depth(depth: i32, vm: &VirtualMachine) -> PyResult<()> {
        if depth < 0 {
            return Err(vm.new_value_error("depth must be >= 0"));
        }
        crate::vm::thread::COROUTINE_ORIGIN_TRACKING_DEPTH.set(depth as u32);
        Ok(())
    }

    #[pyfunction]
    fn get_coroutine_origin_tracking_depth() -> i32 {
        crate::vm::thread::COROUTINE_ORIGIN_TRACKING_DEPTH.get() as i32
    }

    #[pyfunction]
    fn _clear_type_descriptors(type_obj: PyTypeRef, vm: &VirtualMachine) -> PyResult<()> {
        use crate::types::PyTypeFlags;

        // Check if type is immutable
        if type_obj.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
            return Err(vm.new_type_error("argument is immutable"));
        }

        let mut attributes = type_obj.attributes.write();

        // Remove __dict__ descriptor if present
        attributes.swap_remove(identifier!(vm, __dict__));

        // Remove __weakref__ descriptor if present
        attributes.swap_remove(identifier!(vm, __weakref__));

        drop(attributes);

        // Update slots to notify subclasses and recalculate cached values
        type_obj.update_slot::<true>(identifier!(vm, __dict__), &vm.ctx);
        type_obj.update_slot::<true>(identifier!(vm, __weakref__), &vm.ctx);

        Ok(())
    }

    #[pyfunction]
    fn getswitchinterval(vm: &VirtualMachine) -> f64 {
        // Return the stored switch interval
        vm.state.switch_interval.load()
    }

    // TODO: vm.state.switch_interval is currently not used anywhere in the VM
    #[pyfunction]
    fn setswitchinterval(interval: f64, vm: &VirtualMachine) -> PyResult<()> {
        // Validate the interval parameter like CPython does
        if interval <= 0.0 {
            return Err(vm.new_value_error("switch interval must be strictly positive"));
        }

        // Store the switch interval value
        vm.state.switch_interval.store(interval);
        Ok(())
    }

    #[derive(FromArgs)]
    struct SetAsyncgenHooksArgs {
        #[pyarg(any, optional)]
        firstiter: OptionalArg<Option<PyObjectRef>>,
        #[pyarg(any, optional)]
        finalizer: OptionalArg<Option<PyObjectRef>>,
    }

    #[pyfunction]
    fn set_asyncgen_hooks(args: SetAsyncgenHooksArgs, vm: &VirtualMachine) -> PyResult<()> {
        if let Some(Some(finalizer)) = args.finalizer.as_option()
            && !finalizer.is_callable()
        {
            return Err(vm.new_type_error(format!(
                "callable finalizer expected, got {:.50}",
                finalizer.class().name()
            )));
        }

        if let Some(Some(firstiter)) = args.firstiter.as_option()
            && !firstiter.is_callable()
        {
            return Err(vm.new_type_error(format!(
                "callable firstiter expected, got {:.50}",
                firstiter.class().name()
            )));
        }

        if let Some(finalizer) = args.finalizer.into_option() {
            *vm.async_gen_finalizer.borrow_mut() = finalizer;
        }
        if let Some(firstiter) = args.firstiter.into_option() {
            *vm.async_gen_firstiter.borrow_mut() = firstiter;
        }

        Ok(())
    }

    #[pystruct_sequence_data]
    pub(super) struct AsyncgenHooksData {
        firstiter: PyObjectRef,
        finalizer: PyObjectRef,
    }

    #[pyattr]
    #[pystruct_sequence(name = "asyncgen_hooks", data = "AsyncgenHooksData")]
    pub(super) struct PyAsyncgenHooks;

    #[pyclass(with(PyStructSequence))]
    impl PyAsyncgenHooks {}

    #[pyfunction]
    fn get_asyncgen_hooks(vm: &VirtualMachine) -> AsyncgenHooksData {
        AsyncgenHooksData {
            firstiter: vm.async_gen_firstiter.borrow().clone().to_pyobject(vm),
            finalizer: vm.async_gen_finalizer.borrow().clone().to_pyobject(vm),
        }
    }

    /// sys.flags
    ///
    /// Flags provided through command line arguments or environment vars.
    #[derive(Debug)]
    #[pystruct_sequence_data]
    pub(super) struct FlagsData {
        /// -d
        debug: u8,
        /// -i
        inspect: u8,
        /// -i
        interactive: u8,
        /// -O or -OO
        optimize: u8,
        /// -B
        dont_write_bytecode: u8,
        /// -s
        no_user_site: u8,
        /// -S
        no_site: u8,
        /// -E
        ignore_environment: u8,
        /// -v
        verbose: u8,
        /// -b
        bytes_warning: u64,
        /// -q
        quiet: u8,
        /// -R
        hash_randomization: u8,
        /// -I
        isolated: u8,
        /// -X dev
        dev_mode: bool,
        /// -X utf8
        utf8_mode: u8,
        /// -X int_max_str_digits=number
        int_max_str_digits: i64,
        /// -P, `PYTHONSAFEPATH`
        safe_path: bool,
        /// -X warn_default_encoding, PYTHONWARNDEFAULTENCODING
        warn_default_encoding: u8,
    }

    impl FlagsData {
        const fn from_settings(settings: &Settings) -> Self {
            Self {
                debug: settings.debug,
                inspect: settings.inspect as u8,
                interactive: settings.interactive as u8,
                optimize: settings.optimize,
                dont_write_bytecode: (!settings.write_bytecode) as u8,
                no_user_site: (!settings.user_site_directory) as u8,
                no_site: (!settings.import_site) as u8,
                ignore_environment: settings.ignore_environment as u8,
                verbose: settings.verbose,
                bytes_warning: settings.bytes_warning,
                quiet: settings.quiet as u8,
                hash_randomization: settings.hash_seed.is_none() as u8,
                isolated: settings.isolated as u8,
                dev_mode: settings.dev_mode,
                utf8_mode: if settings.utf8_mode < 0 {
                    1
                } else {
                    settings.utf8_mode as u8
                },
                int_max_str_digits: settings.int_max_str_digits,
                safe_path: settings.safe_path,
                warn_default_encoding: settings.warn_default_encoding as u8,
            }
        }
    }

    #[pystruct_sequence(name = "flags", data = "FlagsData", no_attr)]
    pub(super) struct PyFlags;

    #[pyclass(with(PyStructSequence))]
    impl PyFlags {
        #[pyslot]
        fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
            Err(vm.new_type_error("cannot create 'sys.flags' instances"))
        }

        #[pygetset]
        fn context_aware_warnings(&self, vm: &VirtualMachine) -> bool {
            vm.state.config.settings.context_aware_warnings
        }

        #[pygetset]
        fn thread_inherit_context(&self, vm: &VirtualMachine) -> bool {
            vm.state.config.settings.thread_inherit_context
        }
    }

    #[cfg(feature = "threading")]
    #[pystruct_sequence_data]
    pub(super) struct ThreadInfoData {
        name: Option<&'static str>,
        lock: Option<&'static str>,
        version: Option<&'static str>,
    }

    #[cfg(feature = "threading")]
    impl ThreadInfoData {
        const INFO: Self = Self {
            name: crate::stdlib::_thread::_thread::PYTHREAD_NAME,
            // As I know, there's only way to use lock as "Mutex" in Rust
            // with satisfying python document spec.
            lock: Some("mutex+cond"),
            version: None,
        };
    }

    #[cfg(feature = "threading")]
    #[pystruct_sequence(name = "thread_info", data = "ThreadInfoData", no_attr)]
    pub(super) struct PyThreadInfo;

    #[cfg(feature = "threading")]
    #[pyclass(with(PyStructSequence))]
    impl PyThreadInfo {}

    #[pystruct_sequence_data]
    pub(super) struct FloatInfoData {
        max: f64,
        max_exp: i32,
        max_10_exp: i32,
        min: f64,
        min_exp: i32,
        min_10_exp: i32,
        dig: u32,
        mant_dig: u32,
        epsilon: f64,
        radix: u32,
        rounds: i32,
    }

    impl FloatInfoData {
        const INFO: Self = Self {
            max: f64::MAX,
            max_exp: f64::MAX_EXP,
            max_10_exp: f64::MAX_10_EXP,
            min: f64::MIN_POSITIVE,
            min_exp: f64::MIN_EXP,
            min_10_exp: f64::MIN_10_EXP,
            dig: f64::DIGITS,
            mant_dig: f64::MANTISSA_DIGITS,
            epsilon: f64::EPSILON,
            radix: f64::RADIX,
            rounds: 1, // FE_TONEAREST
        };
    }

    #[pystruct_sequence(name = "float_info", data = "FloatInfoData", no_attr)]
    pub(super) struct PyFloatInfo;

    #[pyclass(with(PyStructSequence))]
    impl PyFloatInfo {}

    #[pystruct_sequence_data]
    pub(super) struct HashInfoData {
        width: usize,
        modulus: PyUHash,
        inf: PyHash,
        nan: PyHash,
        imag: PyHash,
        algorithm: &'static str,
        hash_bits: usize,
        seed_bits: usize,
        cutoff: usize,
    }

    impl HashInfoData {
        const INFO: Self = {
            use rustpython_common::hash::*;
            Self {
                width: core::mem::size_of::<PyHash>() * 8,
                modulus: MODULUS,
                inf: INF,
                nan: NAN,
                imag: IMAG,
                algorithm: ALGO,
                hash_bits: HASH_BITS,
                seed_bits: SEED_BITS,
                cutoff: 0, // no small string optimizations
            }
        };
    }

    #[pystruct_sequence(name = "hash_info", data = "HashInfoData", no_attr)]
    pub(super) struct PyHashInfo;

    #[pyclass(with(PyStructSequence))]
    impl PyHashInfo {}

    #[pystruct_sequence_data]
    pub(super) struct IntInfoData {
        bits_per_digit: usize,
        sizeof_digit: usize,
        default_max_str_digits: usize,
        str_digits_check_threshold: usize,
    }

    impl IntInfoData {
        const INFO: Self = Self {
            bits_per_digit: 30, //?
            sizeof_digit: core::mem::size_of::<u32>(),
            default_max_str_digits: 4300,
            str_digits_check_threshold: 640,
        };
    }

    #[pystruct_sequence(name = "int_info", data = "IntInfoData", no_attr)]
    pub(super) struct PyIntInfo;

    #[pyclass(with(PyStructSequence))]
    impl PyIntInfo {}

    #[derive(Default, Debug)]
    #[pystruct_sequence_data]
    pub struct VersionInfoData {
        major: usize,
        minor: usize,
        micro: usize,
        releaselevel: &'static str,
        serial: usize,
    }

    impl VersionInfoData {
        pub const VERSION: Self = Self {
            major: version::MAJOR,
            minor: version::MINOR,
            micro: version::MICRO,
            releaselevel: version::RELEASELEVEL,
            serial: version::SERIAL,
        };
    }

    #[pystruct_sequence(name = "version_info", data = "VersionInfoData", no_attr)]
    pub struct PyVersionInfo;

    #[pyclass(with(PyStructSequence))]
    impl PyVersionInfo {
        #[pyslot]
        fn slot_new(
            _cls: crate::builtins::type_::PyTypeRef,
            _args: crate::function::FuncArgs,
            vm: &crate::VirtualMachine,
        ) -> crate::PyResult {
            Err(vm.new_type_error("cannot create 'sys.version_info' instances"))
        }
    }

    #[cfg(windows)]
    #[derive(Default, Debug)]
    #[pystruct_sequence_data]
    pub(super) struct WindowsVersionData {
        major: u32,
        minor: u32,
        build: u32,
        platform: u32,
        service_pack: String,
        #[pystruct_sequence(skip)]
        service_pack_major: u16,
        #[pystruct_sequence(skip)]
        service_pack_minor: u16,
        #[pystruct_sequence(skip)]
        suite_mask: u16,
        #[pystruct_sequence(skip)]
        product_type: u8,
        #[pystruct_sequence(skip)]
        platform_version: (u32, u32, u32),
    }

    #[cfg(windows)]
    #[pystruct_sequence(name = "getwindowsversion", data = "WindowsVersionData", no_attr)]
    pub(super) struct PyWindowsVersion;

    #[cfg(windows)]
    #[pyclass(with(PyStructSequence))]
    impl PyWindowsVersion {
        #[pyslot]
        fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
            Err(vm.new_type_error("cannot create 'sys.getwindowsversion' instances"))
        }
    }

    #[derive(Debug)]
    #[pystruct_sequence_data(try_from_object)]
    pub struct UnraisableHookArgsData {
        pub exc_type: PyTypeRef,
        pub exc_value: PyObjectRef,
        pub exc_traceback: PyObjectRef,
        pub err_msg: PyObjectRef,
        pub object: PyObjectRef,
    }

    #[pystruct_sequence(name = "UnraisableHookArgs", data = "UnraisableHookArgsData", no_attr)]
    pub struct PyUnraisableHookArgs;

    #[pyclass(with(PyStructSequence))]
    impl PyUnraisableHookArgs {}
}

pub(crate) fn init_module(vm: &VirtualMachine, module: &Py<PyModule>, builtins: &Py<PyModule>) {
    module.__init_methods(vm).unwrap();
    sys::module_exec(vm, module).unwrap();

    let modules = vm.ctx.new_dict();
    modules
        .set_item("sys", module.to_owned().into(), vm)
        .unwrap();
    modules
        .set_item("builtins", builtins.to_owned().into(), vm)
        .unwrap();

    // Create sys._jit submodule
    let jit_def = sys_jit::module_def(&vm.ctx);
    let jit_module = jit_def.create_module(vm).unwrap();

    extend_module!(vm, module, {
        "__doc__" => sys::DOC.to_owned().to_pyobject(vm),
        "modules" => modules,
        "_jit" => jit_module,
    });
}

pub(crate) fn set_bootstrap_stderr(vm: &VirtualMachine) -> PyResult<()> {
    let stderr = sys::BootstrapStderr.into_ref(&vm.ctx);
    let stderr_obj: crate::PyObjectRef = stderr.into();
    vm.sys_module.set_attr("stderr", stderr_obj.clone(), vm)?;
    vm.sys_module.set_attr("__stderr__", stderr_obj, vm)?;
    Ok(())
}

/// Similar to PySys_WriteStderr in CPython.
///
/// # Usage
///
/// ```rust,ignore
/// writeln!(sys::PyStderr(vm), "foo bar baz :)");
/// ```
///
/// Unlike writing to a `std::io::Write` with the `write[ln]!()` macro, there's no error condition here;
/// this is intended to be a replacement for the `eprint[ln]!()` macro, so `write!()`-ing to PyStderr just
/// returns `()`.
pub struct PyStderr<'vm>(pub &'vm VirtualMachine);

impl PyStderr<'_> {
    pub fn write_fmt(&self, args: core::fmt::Arguments<'_>) {
        use crate::py_io::Write;

        let vm = self.0;
        if let Ok(stderr) = get_stderr(vm) {
            let mut stderr = crate::py_io::PyWriter(stderr, vm);
            if let Ok(()) = stderr.write_fmt(args) {
                return;
            }
        }
        eprint!("{args}")
    }
}

pub fn get_stdin(vm: &VirtualMachine) -> PyResult {
    vm.sys_module
        .get_attr("stdin", vm)
        .map_err(|_| vm.new_runtime_error("lost sys.stdin"))
}
pub fn get_stdout(vm: &VirtualMachine) -> PyResult {
    vm.sys_module
        .get_attr("stdout", vm)
        .map_err(|_| vm.new_runtime_error("lost sys.stdout"))
}
pub fn get_stderr(vm: &VirtualMachine) -> PyResult {
    vm.sys_module
        .get_attr("stderr", vm)
        .map_err(|_| vm.new_runtime_error("lost sys.stderr"))
}

pub(crate) fn sysconfigdata_name() -> String {
    format!(
        "_sysconfigdata_{}_{}_{}",
        sys::ABIFLAGS,
        sys::PLATFORM,
        sys::multiarch()
    )
}