File size: 489,697 Bytes
321276d | 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 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 | # Auto-generated from cpython_chunk_0.txt
TEXT_DATA = r"""
This is Python version 3.15.0 alpha 5
=====================================
.. image:: https://github.com/python/cpython/actions/workflows/build.yml/badge.svg?branch=main&event=push
:alt: CPython build status on GitHub Actions
:target: https://github.com/python/cpython/actions
.. image:: https://dev.azure.com/python/cpython/_apis/build/status/Azure%20Pipelines%20CI?branchName=main
:alt: CPython build status on Azure DevOps
:target: https://dev.azure.com/python/cpython/_build/latest?definitionId=4&branchName=main
.. image:: https://img.shields.io/badge/discourse-join_chat-brightgreen.svg
:alt: Python Discourse chat
:target: https://discuss.python.org/
Copyright © 2001 Python Software Foundation. All rights reserved.
See the end of this file for further copyright and license information.
.. contents::
General Information
-------------------
- Website: https://www.python.org
- Source code: https://github.com/python/cpython
- Issue tracker: https://github.com/python/cpython/issues
- Documentation: https://docs.python.org
- Developer's Guide: https://devguide.python.org/
Contributing to CPython
-----------------------
For more complete instructions on contributing to CPython development,
see the `Developer Guide`_.
.. _Developer Guide: https://devguide.python.org/
Using Python
------------
Installable Python kits, and information about using Python, are available at
`python.org`_.
.. _python.org: https://www.python.org/
Build Instructions
------------------
On Unix, Linux, BSD, macOS, and Cygwin::
./configure
make
make test
sudo make install
This will install Python as ``python3``.
You can pass many options to the configure script; run ``./configure --help``
to find out more. On macOS case-insensitive file systems and on Cygwin,
the executable is called ``python.exe``; elsewhere it's just ``python``.
Building a complete Python installation requires the use of various
additional third-party libraries, depending on your build platform and
configure options. Not all standard library modules are buildable or
usable on all platforms. Refer to the
`Install dependencies <https://devguide.python.org/getting-started/setup-building.html#build-dependencies>`_
section of the `Developer Guide`_ for current detailed information on
dependencies for various Linux distributions and macOS.
On macOS, there are additional configure and build options related
to macOS framework and universal builds. Refer to `Mac/README.rst
<https://github.com/python/cpython/blob/main/Mac/README.rst>`_.
On Windows, see `PCbuild/readme.txt
<https://github.com/python/cpython/blob/main/PCbuild/readme.txt>`_.
To build Windows installer, see `Tools/msi/README.txt
<https://github.com/python/cpython/blob/main/Tools/msi/README.txt>`_.
If you wish, you can create a subdirectory and invoke configure from there.
For example::
mkdir debug
cd debug
../configure --with-pydebug
make
make test
(This will fail if you *also* built at the top-level directory. You should do
a ``make clean`` at the top-level first.)
To get an optimized build of Python, ``configure --enable-optimizations``
before you run ``make``. This sets the default make targets up to enable
Profile Guided Optimization (PGO) and may be used to auto-enable Link Time
Optimization (LTO) on some platforms. For more details, see the sections
below.
Profile Guided Optimization
^^^^^^^^^^^^^^^^^^^^^^^^^^^
PGO takes advantage of recent versions of the GCC or Clang compilers. If used,
either via ``configure --enable-optimizations`` or by manually running
``make profile-opt`` regardless of configure flags, the optimized build
process will perform the following steps:
The entire Python directory is cleaned of temporary files that may have
resulted from a previous compilation.
An instrumented version of the interpreter is built, using suitable compiler
flags for each flavor. Note that this is just an intermediary step. The
binary resulting from this step is not good for real-life workloads as it has
profiling instructions embedded inside.
After the instrumented interpreter is built, the Makefile will run a training
workload. This is necessary in order to profile the interpreter's execution.
Note also that any output, both stdout and stderr, that may appear at this step
is suppressed.
The final step is to build the actual interpreter, using the information
collected from the instrumented one. The end result will be a Python binary
that is optimized; suitable for distribution or production installation.
Link Time Optimization
^^^^^^^^^^^^^^^^^^^^^^
Enabled via configure's ``--with-lto`` flag. LTO takes advantage of the
ability of recent compiler toolchains to optimize across the otherwise
arbitrary ``.o`` file boundary when building final executables or shared
libraries for additional performance gains.
What's New
----------
We have a comprehensive overview of the changes in the `What's new in Python
3.15 <https://docs.python.org/3.15/whatsnew/3.15.html>`_ document. For a more
detailed change log, read `Misc/NEWS
<https://github.com/python/cpython/tree/main/Misc/NEWS.d>`_, but a full
accounting of changes can only be gleaned from the `commit history
<https://github.com/python/cpython/commits/main>`_.
If you want to install multiple versions of Python, see the section below
entitled "Installing multiple versions".
Documentation
-------------
`Documentation for Python 3.15 <https://docs.python.org/3.15/>`_ is online,
updated daily.
It can also be downloaded in many formats for faster access. The documentation
is downloadable in HTML, EPUB, and reStructuredText formats; the latter version
is primarily for documentation authors, translators, and people with special
formatting requirements.
For information about building Python's documentation, refer to `Doc/README.rst
<https://github.com/python/cpython/blob/main/Doc/README.rst>`_.
Testing
-------
To test the interpreter, type ``make test`` in the top-level directory. The
test set produces some output. You can generally ignore the messages about
skipped tests due to optional features which can't be imported. If a message
is printed about a failed test or a traceback or core dump is produced,
something is wrong.
By default, tests are prevented from overusing resources like disk space and
memory. To enable these tests, run ``make buildbottest``.
If any tests fail, you can re-run the failing test(s) in verbose mode. For
example, if ``test_os`` and ``test_gdb`` failed, you can run::
make test TESTOPTS="-v test_os test_gdb"
If the failure persists and appears to be a problem with Python rather than
your environment, you can `file a bug report
<https://github.com/python/cpython/issues>`_ and include relevant output from
that command to show the issue.
See `Running & Writing Tests <https://devguide.python.org/testing/run-write-tests.html>`_
for more on running tests.
Installing multiple versions
----------------------------
On Unix and Mac systems if you intend to install multiple versions of Python
using the same installation prefix (``--prefix`` argument to the configure
script) you must take care that your primary python executable is not
overwritten by the installation of a different version. All files and
directories installed using ``make altinstall`` contain the major and minor
version and can thus live side-by-side. ``make install`` also creates
``${prefix}/bin/python3`` which refers to ``${prefix}/bin/python3.X``. If you
intend to install multiple versions using the same prefix you must decide which
version (if any) is your "primary" version. Install that version using
``make install``. Install all other versions using ``make altinstall``.
For example, if you want to install Python 2.7, 3.6, and 3.15 with 3.15 being the
primary version, you would execute ``make install`` in your 3.15 build directory
and ``make altinstall`` in the others.
Release Schedule
----------------
See `PEP 790 <https://peps.python.org/pep-0790/>`__ for Python 3.15 release details.
Copyright and License Information
---------------------------------
Copyright © 2001 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2001 Corporation for National Research Initiatives. All
rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See the `LICENSE <https://github.com/python/cpython/blob/main/LICENSE>`_ for
information on the history of this software, terms & conditions for usage, and a
DISCLAIMER OF ALL WARRANTIES.
This Python distribution contains *no* GNU General Public License (GPL) code,
so it may be used in proprietary projects. There are interfaces to some GNU
code but these are entirely optional.
All trademarks referenced herein are property of their respective holders.
/*
* New exceptions.c written in Iceland by Richard Jones and Georg Brandl.
*
* Thanks go to Tim Peters and Michael Hudson for debugging.
*/
#include <Python.h>
#include <stdbool.h>
#include "pycore_abstract.h" // _PyObject_RealIsSubclass()
#include "pycore_ceval.h" // _Py_EnterRecursiveCall
#include "pycore_exceptions.h" // struct _Py_exc_state
#include "pycore_initconfig.h"
#include "pycore_modsupport.h" // _PyArg_NoKeywords()
#include "pycore_object.h"
#include "pycore_pyerrors.h" // struct _PyErr_SetRaisedException
#include "osdefs.h" // SEP
#include "clinic/exceptions.c.h"
/*[clinic input]
class BaseException "PyBaseExceptionObject *" "&PyExc_BaseException"
class BaseExceptionGroup "PyBaseExceptionGroupObject *" "&PyExc_BaseExceptionGroup"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b7c45e78cff8edc3]*/
static struct _Py_exc_state*
get_exc_state(void)
{
PyInterpreterState *interp = _PyInterpreterState_GET();
return &interp->exc_state;
}
/* NOTE: If the exception class hierarchy changes, don't forget to update
* Lib/test/exception_hierarchy.txt
*/
static inline PyBaseExceptionObject *
PyBaseExceptionObject_CAST(PyObject *exc)
{
assert(PyExceptionInstance_Check(exc));
return (PyBaseExceptionObject *)exc;
}
/*
* BaseException
*/
static PyObject *
BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyBaseExceptionObject *self;
self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
if (!self)
return NULL;
/* the dict is created on the fly in PyObject_GenericSetAttr */
self->dict = NULL;
self->notes = NULL;
self->traceback = self->cause = self->context = NULL;
self->suppress_context = 0;
if (args) {
self->args = Py_NewRef(args);
return (PyObject *)self;
}
self->args = PyTuple_New(0);
if (!self->args) {
Py_DECREF(self);
return NULL;
}
return (PyObject *)self;
}
static int
BaseException_init(PyObject *op, PyObject *args, PyObject *kwds)
{
PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op);
if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
return -1;
Py_XSETREF(self->args, Py_NewRef(args));
return 0;
}
static PyObject *
BaseException_vectorcall(PyObject *type_obj, PyObject * const*args,
size_t nargsf, PyObject *kwnames)
{
PyTypeObject *type = _PyType_CAST(type_obj);
if (!_PyArg_NoKwnames(type->tp_name, kwnames)) {
return NULL;
}
PyBaseExceptionObject *self;
self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
if (!self) {
return NULL;
}
// The dict is created on the fly in PyObject_GenericSetAttr()
self->dict = NULL;
self->notes = NULL;
self->traceback = NULL;
self->cause = NULL;
self->context = NULL;
self->suppress_context = 0;
self->args = PyTuple_FromArray(args, PyVectorcall_NARGS(nargsf));
if (!self->args) {
Py_DECREF(self);
return NULL;
}
return (PyObject *)self;
}
static int
BaseException_clear(PyObject *op)
{
PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op);
Py_CLEAR(self->dict);
Py_CLEAR(self->args);
Py_CLEAR(self->notes);
Py_CLEAR(self->traceback);
Py_CLEAR(self->cause);
Py_CLEAR(self->context);
return 0;
}
static void
BaseException_dealloc(PyObject *op)
{
PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op);
PyObject_GC_UnTrack(self);
// bpo-44348: The trashcan mechanism prevents stack overflow when deleting
// long chains of exceptions. For example, exceptions can be chained
// through the __context__ attributes or the __traceback__ attribute.
(void)BaseException_clear(op);
Py_TYPE(self)->tp_free(self);
}
static int
BaseException_traverse(PyObject *op, visitproc visit, void *arg)
{
PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op);
Py_VISIT(self->dict);
Py_VISIT(self->args);
Py_VISIT(self->notes);
Py_VISIT(self->traceback);
Py_VISIT(self->cause);
Py_VISIT(self->context);
return 0;
}
static PyObject *
BaseException_str(PyObject *op)
{
PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op);
PyObject *res;
Py_BEGIN_CRITICAL_SECTION(self);
switch (PyTuple_GET_SIZE(self->args)) {
case 0:
res = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
break;
case 1:
res = PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
break;
default:
res = PyObject_Str(self->args);
break;
}
Py_END_CRITICAL_SECTION();
return res;
}
static PyObject *
BaseException_repr(PyObject *op)
{
PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op);
PyObject *res;
Py_BEGIN_CRITICAL_SECTION(self);
const char *name = _PyType_Name(Py_TYPE(self));
if (PyTuple_GET_SIZE(self->args) == 1) {
res = PyUnicode_FromFormat("%s(%R)", name,
PyTuple_GET_ITEM(self->args, 0));
}
else {
res = PyUnicode_FromFormat("%s%R", name, self->args);
}
Py_END_CRITICAL_SECTION();
return res;
}
/* Pickling support */
/*[clinic input]
@critical_section
BaseException.__reduce__
[clinic start generated code]*/
static PyObject *
BaseException___reduce___impl(PyBaseExceptionObject *self)
/*[clinic end generated code: output=af87c1247ef98748 input=283be5a10d9c964f]*/
{
if (self->args && self->dict)
return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
else
return PyTuple_Pack(2, Py_TYPE(self), self->args);
}
/*
* Needed for backward compatibility, since exceptions used to store
* all their attributes in the __dict__. Code is taken from cPickle's
* load_build function.
*/
/*[clinic input]
@critical_section
BaseException.__setstate__
state: object
/
[clinic start generated code]*/
static PyObject *
BaseException___setstate___impl(PyBaseExceptionObject *self, PyObject *state)
/*[clinic end generated code: output=f3834889950453ab input=5524b61cfe9b9856]*/
{
PyObject *d_key, *d_value;
Py_ssize_t i = 0;
if (state != Py_None) {
if (!PyDict_Check(state)) {
PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
return NULL;
}
while (PyDict_Next(state, &i, &d_key, &d_value)) {
Py_INCREF(d_key);
Py_INCREF(d_value);
int res = PyObject_SetAttr((PyObject *)self, d_key, d_value);
Py_DECREF(d_value);
Py_DECREF(d_key);
if (res < 0) {
return NULL;
}
}
}
Py_RETURN_NONE;
}
/*[clinic input]
@critical_section
BaseException.with_traceback
tb: object
/
Set self.__traceback__ to tb and return self.
[clinic start generated code]*/
static PyObject *
BaseException_with_traceback_impl(PyBaseExceptionObject *self, PyObject *tb)
/*[clinic end generated code: output=81e92f2387927f10 input=b5fb64d834717e36]*/
{
if (BaseException___traceback___set_impl(self, tb) < 0){
return NULL;
}
return Py_NewRef(self);
}
/*[clinic input]
@critical_section
BaseException.add_note
note: object(subclass_of="&PyUnicode_Type")
/
Add a note to the exception
[clinic start generated code]*/
static PyObject *
BaseException_add_note_impl(PyBaseExceptionObject *self, PyObject *note)
/*[clinic end generated code: output=fb7cbcba611c187b input=e60a6b6e9596acaf]*/
{
PyObject *notes;
if (PyObject_GetOptionalAttr((PyObject *)self, &_Py_ID(__notes__), ¬es) < 0) {
return NULL;
}
if (notes == NULL) {
notes = PyList_New(0);
if (notes == NULL) {
return NULL;
}
if (PyObject_SetAttr((PyObject *)self, &_Py_ID(__notes__), notes) < 0) {
Py_DECREF(notes);
return NULL;
}
}
else if (!PyList_Check(notes)) {
Py_DECREF(notes);
PyErr_SetString(PyExc_TypeError, "Cannot add note: __notes__ is not a list");
return NULL;
}
if (PyList_Append(notes, note) < 0) {
Py_DECREF(notes);
return NULL;
}
Py_DECREF(notes);
Py_RETURN_NONE;
}
static PyMethodDef BaseException_methods[] = {
BASEEXCEPTION___REDUCE___METHODDEF
BASEEXCEPTION___SETSTATE___METHODDEF
BASEEXCEPTION_WITH_TRACEBACK_METHODDEF
BASEEXCEPTION_ADD_NOTE_METHODDEF
{NULL, NULL, 0, NULL},
};
/*[clinic input]
@critical_section
@getter
BaseException.args
[clinic start generated code]*/
static PyObject *
BaseException_args_get_impl(PyBaseExceptionObject *self)
/*[clinic end generated code: output=e02e34e35cf4d677 input=64282386e4d7822d]*/
{
if (self->args == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(self->args);
}
/*[clinic input]
@critical_section
@setter
BaseException.args
[clinic start generated code]*/
static int
BaseException_args_set_impl(PyBaseExceptionObject *self, PyObject *value)
/*[clinic end generated code: output=331137e11d8f9e80 input=2400047ea5970a84]*/
{
PyObject *seq;
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "args may not be deleted");
return -1;
}
seq = PySequence_Tuple(value);
if (!seq)
return -1;
Py_XSETREF(self->args, seq);
return 0;
}
/*[clinic input]
@critical_section
@getter
BaseException.__traceback__
[clinic start generated code]*/
static PyObject *
BaseException___traceback___get_impl(PyBaseExceptionObject *self)
/*[clinic end generated code: output=17cf874a52339398 input=a2277f0de62170cf]*/
{
if (self->traceback == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(self->traceback);
}
/*[clinic input]
@critical_section
@setter
BaseException.__traceback__
[clinic start generated code]*/
static int
BaseException___traceback___set_impl(PyBaseExceptionObject *self,
PyObject *value)
/*[clinic end generated code: output=a82c86d9f29f48f0 input=12676035676badad]*/
{
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
return -1;
}
if (PyTraceBack_Check(value)) {
Py_XSETREF(self->traceback, Py_NewRef(value));
}
else if (value == Py_None) {
Py_CLEAR(self->traceback);
}
else {
PyErr_SetString(PyExc_TypeError,
"__traceback__ must be a traceback or None");
return -1;
}
return 0;
}
/*[clinic input]
@critical_section
@getter
BaseException.__context__
[clinic start generated code]*/
static PyObject *
BaseException___context___get_impl(PyBaseExceptionObject *self)
/*[clinic end generated code: output=6ec5d296ce8d1c93 input=b2d22687937e66ab]*/
{
if (self->context == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(self->context);
}
/*[clinic input]
@critical_section
@setter
BaseException.__context__
[clinic start generated code]*/
static int
BaseException___context___set_impl(PyBaseExceptionObject *self,
PyObject *value)
/*[clinic end generated code: output=b4cb52dcca1da3bd input=c0971adf47fa1858]*/
{
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
return -1;
} else if (value == Py_None) {
value = NULL;
} else if (!PyExceptionInstance_Check(value)) {
PyErr_SetString(PyExc_TypeError, "exception context must be None "
"or derive from BaseException");
return -1;
} else {
Py_INCREF(value);
}
Py_XSETREF(self->context, value);
return 0;
}
/*[clinic input]
@critical_section
@getter
BaseException.__cause__
[clinic start generated code]*/
static PyObject *
BaseException___cause___get_impl(PyBaseExceptionObject *self)
/*[clinic end generated code: output=987f6c4d8a0bdbab input=40e0eac427b6e602]*/
{
if (self->cause == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(self->cause);
}
/*[clinic input]
@critical_section
@setter
BaseException.__cause__
[clinic start generated code]*/
static int
BaseException___cause___set_impl(PyBaseExceptionObject *self,
PyObject *value)
/*[clinic end generated code: output=6161315398aaf541 input=e1b403c0bde3f62a]*/
{
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
return -1;
} else if (value == Py_None) {
value = NULL;
} else if (!PyExceptionInstance_Check(value)) {
PyErr_SetString(PyExc_TypeError, "exception cause must be None "
"or derive from BaseException");
return -1;
} else {
/* PyException_SetCause steals this reference */
Py_INCREF(value);
}
PyException_SetCause((PyObject *)self, value);
return 0;
}
static PyGetSetDef BaseException_getset[] = {
{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
BASEEXCEPTION_ARGS_GETSETDEF
BASEEXCEPTION___TRACEBACK___GETSETDEF
BASEEXCEPTION___CONTEXT___GETSETDEF
BASEEXCEPTION___CAUSE___GETSETDEF
{NULL},
};
PyObject *
PyException_GetTraceback(PyObject *self)
{
PyObject *traceback;
Py_BEGIN_CRITICAL_SECTION(self);
traceback = Py_XNewRef(PyBaseExceptionObject_CAST(self)->traceback);
Py_END_CRITICAL_SECTION();
return traceback;
}
int
PyException_SetTraceback(PyObject *self, PyObject *tb)
{
int res;
Py_BEGIN_CRITICAL_SECTION(self);
res = BaseException___traceback___set_impl(PyBaseExceptionObject_CAST(self), tb);
Py_END_CRITICAL_SECTION();
return res;
}
PyObject *
PyException_GetCause(PyObject *self)
{
PyObject *cause;
Py_BEGIN_CRITICAL_SECTION(self);
cause = Py_XNewRef(PyBaseExceptionObject_CAST(self)->cause);
Py_END_CRITICAL_SECTION();
return cause;
}
/* Steals a reference to cause */
void
PyException_SetCause(PyObject *self, PyObject *cause)
{
Py_BEGIN_CRITICAL_SECTION(self);
PyBaseExceptionObject *base_self = PyBaseExceptionObject_CAST(self);
base_self->suppress_context = 1;
Py_XSETREF(base_self->cause, cause);
Py_END_CRITICAL_SECTION();
}
PyObject *
PyException_GetContext(PyObject *self)
{
PyObject *context;
Py_BEGIN_CRITICAL_SECTION(self);
context = Py_XNewRef(PyBaseExceptionObject_CAST(self)->context);
Py_END_CRITICAL_SECTION();
return context;
}
/* Steals a reference to context */
void
PyException_SetContext(PyObject *self, PyObject *context)
{
Py_BEGIN_CRITICAL_SECTION(self);
Py_XSETREF(PyBaseExceptionObject_CAST(self)->context, context);
Py_END_CRITICAL_SECTION();
}
PyObject *
PyException_GetArgs(PyObject *self)
{
PyObject *args;
Py_BEGIN_CRITICAL_SECTION(self);
args = Py_NewRef(PyBaseExceptionObject_CAST(self)->args);
Py_END_CRITICAL_SECTION();
return args;
}
void
PyException_SetArgs(PyObject *self, PyObject *args)
{
Py_BEGIN_CRITICAL_SECTION(self);
Py_INCREF(args);
Py_XSETREF(PyBaseExceptionObject_CAST(self)->args, args);
Py_END_CRITICAL_SECTION();
}
const char *
PyExceptionClass_Name(PyObject *ob)
{
assert(PyExceptionClass_Check(ob));
return ((PyTypeObject*)ob)->tp_name;
}
static struct PyMemberDef BaseException_members[] = {
{"__suppress_context__", Py_T_BOOL,
offsetof(PyBaseExceptionObject, suppress_context)},
{NULL}
};
static PyTypeObject _PyExc_BaseException = {
PyVarObject_HEAD_INIT(NULL, 0)
"BaseException", /*tp_name*/
sizeof(PyBaseExceptionObject), /*tp_basicsize*/
0, /*tp_itemsize*/
BaseException_dealloc, /*tp_dealloc*/
0, /*tp_vectorcall_offset*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_as_async*/
BaseException_repr, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
BaseException_str, /*tp_str*/
PyObject_GenericGetAttr, /*tp_getattro*/
PyObject_GenericSetAttr, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
BaseException_traverse, /* tp_traverse */
BaseException_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
BaseException_methods, /* tp_methods */
BaseException_members, /* tp_members */
BaseException_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
BaseException_init, /* tp_init */
0, /* tp_alloc */
BaseException_new, /* tp_new */
.tp_vectorcall = BaseException_vectorcall,
};
/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
from the previous implementation and also allowing Python objects to be used
in the API */
PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
/* note these macros omit the last semicolon so the macro invocation may
* include it and not look strange.
*/
#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
static PyTypeObject _PyExc_ ## EXCNAME = { \
PyVarObject_HEAD_INIT(NULL, 0) \
# EXCNAME, \
sizeof(PyBaseExceptionObject), \
0, BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
0, 0, 0, 0, 0, 0, 0, \
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
PyDoc_STR(EXCDOC), BaseException_traverse, \
BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
BaseException_init, 0, BaseException_new,\
}; \
PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
#define MiddlingExtendsExceptionEx(EXCBASE, EXCNAME, PYEXCNAME, EXCSTORE, EXCDOC) \
PyTypeObject _PyExc_ ## EXCNAME = { \
PyVarObject_HEAD_INIT(NULL, 0) \
# PYEXCNAME, \
sizeof(Py ## EXCSTORE ## Object), \
0, EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
0, 0, 0, 0, 0, \
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
PyDoc_STR(EXCDOC), EXCSTORE ## _traverse, \
EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
EXCSTORE ## _init, 0, 0, \
};
#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
static MiddlingExtendsExceptionEx( \
EXCBASE, EXCNAME, EXCNAME, EXCSTORE, EXCDOC); \
PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
EXCMETHODS, EXCMEMBERS, EXCGETSET, \
EXCSTR, EXCREPR, EXCDOC) \
static PyTypeObject _PyExc_ ## EXCNAME = { \
PyVarObject_HEAD_INIT(NULL, 0) \
# EXCNAME, \
sizeof(Py ## EXCSTORE ## Object), 0, \
EXCSTORE ## _dealloc, 0, 0, 0, 0, EXCREPR, 0, 0, 0, 0, 0, \
EXCSTR, 0, 0, 0, \
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
PyDoc_STR(EXCDOC), EXCSTORE ## _traverse, \
EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
EXCSTORE ## _init, 0, EXCNEW,\
}; \
PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
/*
* Exception extends BaseException
*/
SimpleExtendsException(PyExc_BaseException, Exception,
"Common base class for all non-exit exceptions.");
/*
* TypeError extends Exception
*/
SimpleExtendsException(PyExc_Exception, TypeError,
"Inappropriate argument type.");
/*
* StopAsyncIteration extends Exception
*/
SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
"Signal the end from iterator.__anext__().");
/*
* StopIteration extends Exception
*/
static PyMemberDef StopIteration_members[] = {
{"value", _Py_T_OBJECT, offsetof(PyStopIterationObject, value), 0,
PyDoc_STR("generator return value")},
{NULL} /* Sentinel */
};
static inline PyStopIterationObject *
PyStopIterationObject_CAST(PyObject *self)
{
assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_StopIteration));
return (PyStopIterationObject *)self;
}
static int
StopIteration_init(PyObject *op, PyObject *args, PyObject *kwds)
{
Py_ssize_t size = PyTuple_GET_SIZE(args);
PyObject *value;
if (BaseException_init(op, args, kwds) == -1)
return -1;
PyStopIterationObject *self = PyStopIterationObject_CAST(op);
Py_CLEAR(self->value);
if (size > 0)
value = PyTuple_GET_ITEM(args, 0);
else
value = Py_None;
self->value = Py_NewRef(value);
return 0;
}
static int
StopIteration_clear(PyObject *op)
{
PyStopIterationObject *self = PyStopIterationObject_CAST(op);
Py_CLEAR(self->value);
return BaseException_clear(op);
}
static void
StopIteration_dealloc(PyObject *self)
{
PyObject_GC_UnTrack(self);
(void)StopIteration_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
StopIteration_traverse(PyObject *op, visitproc visit, void *arg)
{
PyStopIterationObject *self = PyStopIterationObject_CAST(op);
Py_VISIT(self->value);
return BaseException_traverse(op, visit, arg);
}
ComplexExtendsException(PyExc_Exception, StopIteration, StopIteration,
0, 0, StopIteration_members, 0, 0, 0,
"Signal the end from iterator.__next__().");
/*
* GeneratorExit extends BaseException
*/
SimpleExtendsException(PyExc_BaseException, GeneratorExit,
"Request that a generator exit.");
/*
* SystemExit extends BaseException
*/
static inline PySystemExitObject *
PySystemExitObject_CAST(PyObject *self)
{
assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_SystemExit));
return (PySystemExitObject *)self;
}
static int
SystemExit_init(PyObject *op, PyObject *args, PyObject *kwds)
{
Py_ssize_t size = PyTuple_GET_SIZE(args);
if (BaseException_init(op, args, kwds) == -1)
return -1;
PySystemExitObject *self = PySystemExitObject_CAST(op);
if (size == 0)
return 0;
if (size == 1) {
Py_XSETREF(self->code, Py_NewRef(PyTuple_GET_ITEM(args, 0)));
}
else { /* size > 1 */
Py_XSETREF(self->code, Py_NewRef(args));
}
return 0;
}
static int
SystemExit_clear(PyObject *op)
{
PySystemExitObject *self = PySystemExitObject_CAST(op);
Py_CLEAR(self->code);
return BaseException_clear(op);
}
static void
SystemExit_dealloc(PyObject *self)
{
_PyObject_GC_UNTRACK(self);
(void)SystemExit_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
SystemExit_traverse(PyObject *op, visitproc visit, void *arg)
{
PySystemExitObject *self = PySystemExitObject_CAST(op);
Py_VISIT(self->code);
return BaseException_traverse(op, visit, arg);
}
static PyMemberDef SystemExit_members[] = {
{"code", _Py_T_OBJECT, offsetof(PySystemExitObject, code), 0,
PyDoc_STR("exception code")},
{NULL} /* Sentinel */
};
ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
0, 0, SystemExit_members, 0, 0, 0,
"Request to exit from the interpreter.");
/*
* BaseExceptionGroup extends BaseException
* ExceptionGroup extends BaseExceptionGroup and Exception
*/
static inline PyBaseExceptionGroupObject*
PyBaseExceptionGroupObject_CAST(PyObject *exc)
{
assert(_PyBaseExceptionGroup_Check(exc));
return (PyBaseExceptionGroupObject *)exc;
}
static PyObject *
BaseExceptionGroup_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
struct _Py_exc_state *state = get_exc_state();
PyTypeObject *PyExc_ExceptionGroup =
(PyTypeObject*)state->PyExc_ExceptionGroup;
PyObject *message = NULL;
PyObject *exceptions = NULL;
PyObject *exceptions_str = NULL;
if (!PyArg_ParseTuple(args,
"UO:BaseExceptionGroup.__new__",
&message,
&exceptions)) {
return NULL;
}
if (!PySequence_Check(exceptions)) {
PyErr_SetString(
PyExc_TypeError,
"second argument (exceptions) must be a sequence");
return NULL;
}
/* Save initial exceptions sequence as a string in case sequence is mutated */
if (!PyList_Check(exceptions) && !PyTuple_Check(exceptions)) {
exceptions_str = PyObject_Repr(exceptions);
if (exceptions_str == NULL) {
/* We don't hold a reference to exceptions, so clear it before
* attempting a decref in the cleanup.
*/
exceptions = NULL;
goto error;
}
}
exceptions = PySequence_Tuple(exceptions);
if (!exceptions) {
return NULL;
}
/* We are now holding a ref to the exceptions tuple */
Py_ssize_t numexcs = PyTuple_GET_SIZE(exceptions);
if (numexcs == 0) {
PyErr_SetString(
PyExc_ValueError,
"second argument (exceptions) must be a non-empty sequence");
goto error;
}
bool nested_base_exceptions = false;
for (Py_ssize_t i = 0; i < numexcs; i++) {
PyObject *exc = PyTuple_GET_ITEM(exceptions, i);
if (!exc) {
goto error;
}
if (!PyExceptionInstance_Check(exc)) {
PyErr_Format(
PyExc_ValueError,
"Item %d of second argument (exceptions) is not an exception",
i);
goto error;
}
int is_nonbase_exception = PyObject_IsInstance(exc, PyExc_Exception);
if (is_nonbase_exception < 0) {
goto error;
}
else if (is_nonbase_exception == 0) {
nested_base_exceptions = true;
}
}
PyTypeObject *cls = type;
if (cls == PyExc_ExceptionGroup) {
if (nested_base_exceptions) {
PyErr_SetString(PyExc_TypeError,
"Cannot nest BaseExceptions in an ExceptionGroup");
goto error;
}
}
else if (cls == (PyTypeObject*)PyExc_BaseExceptionGroup) {
if (!nested_base_exceptions) {
/* All nested exceptions are Exception subclasses,
* wrap them in an ExceptionGroup
*/
cls = PyExc_ExceptionGroup;
}
}
else {
/* user-defined subclass */
if (nested_base_exceptions) {
int nonbase = PyObject_IsSubclass((PyObject*)cls, PyExc_Exception);
if (nonbase == -1) {
goto error;
}
else if (nonbase == 1) {
PyErr_Format(PyExc_TypeError,
"Cannot nest BaseExceptions in '%.200s'",
cls->tp_name);
goto error;
}
}
}
if (!cls) {
/* Don't crash during interpreter shutdown
* (PyExc_ExceptionGroup may have been cleared)
*/
cls = (PyTypeObject*)PyExc_BaseExceptionGroup;
}
PyBaseExceptionGroupObject *self =
PyBaseExceptionGroupObject_CAST(BaseException_new(cls, args, kwds));
if (!self) {
goto error;
}
self->msg = Py_NewRef(message);
self->excs = exceptions;
self->excs_str = exceptions_str;
return (PyObject*)self;
error:
Py_XDECREF(exceptions);
Py_XDECREF(exceptions_str);
return NULL;
}
PyObject *
_PyExc_CreateExceptionGroup(const char *msg_str, PyObject *excs)
{
PyObject *msg = PyUnicode_FromString(msg_str);
if (!msg) {
return NULL;
}
PyObject *args = PyTuple_Pack(2, msg, excs);
Py_DECREF(msg);
if (!args) {
return NULL;
}
PyObject *result = PyObject_CallObject(PyExc_BaseExceptionGroup, args);
Py_DECREF(args);
return result;
}
static int
BaseExceptionGroup_init(PyObject *self, PyObject *args, PyObject *kwds)
{
if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) {
return -1;
}
if (BaseException_init(self, args, kwds) == -1) {
return -1;
}
return 0;
}
static int
BaseExceptionGroup_clear(PyObject *op)
{
PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op);
Py_CLEAR(self->msg);
Py_CLEAR(self->excs);
Py_CLEAR(self->excs_str);
return BaseException_clear(op);
}
static void
BaseExceptionGroup_dealloc(PyObject *self)
{
_PyObject_GC_UNTRACK(self);
(void)BaseExceptionGroup_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
BaseExceptionGroup_traverse(PyObject *op, visitproc visit, void *arg)
{
PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op);
Py_VISIT(self->msg);
Py_VISIT(self->excs);
Py_VISIT(self->excs_str);
return BaseException_traverse(op, visit, arg);
}
static PyObject *
BaseExceptionGroup_str(PyObject *op)
{
PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op);
assert(self->msg);
assert(PyUnicode_Check(self->msg));
assert(PyTuple_CheckExact(self->excs));
Py_ssize_t num_excs = PyTuple_Size(self->excs);
return PyUnicode_FromFormat(
"%S (%zd sub-exception%s)",
self->msg, num_excs, num_excs > 1 ? "s" : "");
}
static PyObject *
BaseExceptionGroup_repr(PyObject *op)
{
PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op);
assert(self->msg);
PyObject *exceptions_str = NULL;
/* Use the saved exceptions string for custom sequences. */
if (self->excs_str) {
exceptions_str = Py_NewRef(self->excs_str);
}
else {
assert(self->excs);
/* Older versions delegated to BaseException, inserting the current
* value of self.args[1]; but this can be mutable and go out-of-sync
* with self.exceptions. Instead, use self.exceptions for accuracy,
* making it look like self.args[1] for backwards compatibility. */
if (PyList_Check(PyTuple_GET_ITEM(self->args, 1))) {
PyObject *exceptions_list = PySequence_List(self->excs);
if (!exceptions_list) {
return NULL;
}
exceptions_str = PyObject_Repr(exceptions_list);
Py_DECREF(exceptions_list);
}
else {
exceptions_str = PyObject_Repr(self->excs);
}
if (!exceptions_str) {
return NULL;
}
}
assert(exceptions_str != NULL);
const char *name = _PyType_Name(Py_TYPE(self));
PyObject *repr = PyUnicode_FromFormat(
"%s(%R, %U)", name,
self->msg, exceptions_str);
Py_DECREF(exceptions_str);
return repr;
}
/*[clinic input]
@critical_section
BaseExceptionGroup.derive
excs: object
/
[clinic start generated code]*/
static PyObject *
BaseExceptionGroup_derive_impl(PyBaseExceptionGroupObject *self,
PyObject *excs)
/*[clinic end generated code: output=4307564218dfbf06 input=f72009d38e98cec1]*/
{
PyObject *init_args = PyTuple_Pack(2, self->msg, excs);
if (!init_args) {
return NULL;
}
PyObject *eg = PyObject_CallObject(
PyExc_BaseExceptionGroup, init_args);
Py_DECREF(init_args);
return eg;
}
static int
exceptiongroup_subset(
PyBaseExceptionGroupObject *_orig, PyObject *excs, PyObject **result)
{
/* Sets *result to an ExceptionGroup wrapping excs with metadata from
* _orig. If excs is empty, sets *result to NULL.
* Returns 0 on success and -1 on error.
* This function is used by split() to construct the match/rest parts,
* so excs is the matching or non-matching sub-sequence of orig->excs
* (this function does not verify that it is a subsequence).
*/
PyObject *orig = (PyObject *)_orig;
*result = NULL;
Py_ssize_t num_excs = PySequence_Size(excs);
if (num_excs < 0) {
return -1;
}
else if (num_excs == 0) {
return 0;
}
PyObject *eg = PyObject_CallMethod(
orig, "derive", "(O)", excs);
if (!eg) {
return -1;
}
if (!_PyBaseExceptionGroup_Check(eg)) {
PyErr_SetString(PyExc_TypeError,
"derive must return an instance of BaseExceptionGroup");
goto error;
}
/* Now we hold a reference to the new eg */
PyObject *tb = PyException_GetTraceback(orig);
if (tb) {
int res = PyException_SetTraceback(eg, tb);
Py_DECREF(tb);
if (res < 0) {
goto error;
}
}
PyException_SetContext(eg, PyException_GetContext(orig));
PyException_SetCause(eg, PyException_GetCause(orig));
PyObject *notes;
if (PyObject_GetOptionalAttr(orig, &_Py_ID(__notes__), ¬es) < 0) {
goto error;
}
if (notes) {
if (PySequence_Check(notes)) {
/* Make a copy so the parts have independent notes lists. */
PyObject *notes_copy = PySequence_List(notes);
Py_DECREF(notes);
if (notes_copy == NULL) {
goto error;
}
int res = PyObject_SetAttr(eg, &_Py_ID(__notes__), notes_copy);
Py_DECREF(notes_copy);
if (res < 0) {
goto error;
}
}
else {
/* __notes__ is supposed to be a list, and split() is not a
* good place to report earlier user errors, so we just ignore
* notes of non-sequence type.
*/
Py_DECREF(notes);
}
}
*result = eg;
return 0;
error:
Py_DECREF(eg);
return -1;
}
typedef enum {
/* Exception type or tuple of thereof */
EXCEPTION_GROUP_MATCH_BY_TYPE = 0,
/* A PyFunction returning True for matching exceptions */
EXCEPTION_GROUP_MATCH_BY_PREDICATE = 1,
/* A set of the IDs of leaf exceptions to include in the result.
* This matcher type is used internally by the interpreter
* to construct reraised exceptions.
*/
EXCEPTION_GROUP_MATCH_INSTANCE_IDS = 2
} _exceptiongroup_split_matcher_type;
static int
get_matcher_type(PyObject *value,
_exceptiongroup_split_matcher_type *type)
{
assert(value);
if (PyCallable_Check(value) && !PyType_Check(value)) {
*type = EXCEPTION_GROUP_MATCH_BY_PREDICATE;
return 0;
}
if (PyExceptionClass_Check(value)) {
*type = EXCEPTION_GROUP_MATCH_BY_TYPE;
return 0;
}
if (PyTuple_CheckExact(value)) {
Py_ssize_t n = PyTuple_GET_SIZE(value);
for (Py_ssize_t i=0; i<n; i++) {
if (!PyExceptionClass_Check(PyTuple_GET_ITEM(value, i))) {
goto error;
}
}
*type = EXCEPTION_GROUP_MATCH_BY_TYPE;
return 0;
}
error:
PyErr_SetString(
PyExc_TypeError,
"expected an exception type, a tuple of exception types, or a callable (other than a class)");
return -1;
}
static int
exceptiongroup_split_check_match(PyObject *exc,
_exceptiongroup_split_matcher_type matcher_type,
PyObject *matcher_value)
{
switch (matcher_type) {
case EXCEPTION_GROUP_MATCH_BY_TYPE: {
assert(PyExceptionClass_Check(matcher_value) ||
PyTuple_CheckExact(matcher_value));
return PyErr_GivenExceptionMatches(exc, matcher_value);
}
case EXCEPTION_GROUP_MATCH_BY_PREDICATE: {
assert(PyCallable_Check(matcher_value) && !PyType_Check(matcher_value));
PyObject *exc_matches = PyObject_CallOneArg(matcher_value, exc);
if (exc_matches == NULL) {
return -1;
}
int is_true = PyObject_IsTrue(exc_matches);
Py_DECREF(exc_matches);
return is_true;
}
case EXCEPTION_GROUP_MATCH_INSTANCE_IDS: {
assert(PySet_Check(matcher_value));
if (!_PyBaseExceptionGroup_Check(exc)) {
PyObject *exc_id = PyLong_FromVoidPtr(exc);
if (exc_id == NULL) {
return -1;
}
int res = PySet_Contains(matcher_value, exc_id);
Py_DECREF(exc_id);
return res;
}
return 0;
}
}
return 0;
}
typedef struct {
PyObject *match;
PyObject *rest;
} _exceptiongroup_split_result;
static int
exceptiongroup_split_recursive(PyObject *exc,
_exceptiongroup_split_matcher_type matcher_type,
PyObject *matcher_value,
bool construct_rest,
_exceptiongroup_split_result *result)
{
result->match = NULL;
result->rest = NULL;
int is_match = exceptiongroup_split_check_match(
exc, matcher_type, matcher_value);
if (is_match < 0) {
return -1;
}
if (is_match) {
/* Full match */
result->match = Py_NewRef(exc);
return 0;
}
else if (!_PyBaseExceptionGroup_Check(exc)) {
/* Leaf exception and no match */
if (construct_rest) {
result->rest = Py_NewRef(exc);
}
return 0;
}
/* Partial match */
PyBaseExceptionGroupObject *eg = PyBaseExceptionGroupObject_CAST(exc);
assert(PyTuple_CheckExact(eg->excs));
Py_ssize_t num_excs = PyTuple_Size(eg->excs);
if (num_excs < 0) {
return -1;
}
assert(num_excs > 0); /* checked in constructor, and excs is read-only */
int retval = -1;
PyObject *match_list = PyList_New(0);
if (!match_list) {
return -1;
}
PyObject *rest_list = NULL;
if (construct_rest) {
rest_list = PyList_New(0);
if (!rest_list) {
goto done;
}
}
/* recursive calls */
for (Py_ssize_t i = 0; i < num_excs; i++) {
PyObject *e = PyTuple_GET_ITEM(eg->excs, i);
_exceptiongroup_split_result rec_result;
if (_Py_EnterRecursiveCall(" in exceptiongroup_split_recursive")) {
goto done;
}
if (exceptiongroup_split_recursive(
e, matcher_type, matcher_value,
construct_rest, &rec_result) < 0) {
assert(!rec_result.match);
assert(!rec_result.rest);
_Py_LeaveRecursiveCall();
goto done;
}
_Py_LeaveRecursiveCall();
if (rec_result.match) {
assert(PyList_CheckExact(match_list));
if (PyList_Append(match_list, rec_result.match) < 0) {
Py_DECREF(rec_result.match);
Py_XDECREF(rec_result.rest);
goto done;
}
Py_DECREF(rec_result.match);
}
if (rec_result.rest) {
assert(construct_rest);
assert(PyList_CheckExact(rest_list));
if (PyList_Append(rest_list, rec_result.rest) < 0) {
Py_DECREF(rec_result.rest);
goto done;
}
Py_DECREF(rec_result.rest);
}
}
/* construct result */
if (exceptiongroup_subset(eg, match_list, &result->match) < 0) {
goto done;
}
if (construct_rest) {
assert(PyList_CheckExact(rest_list));
if (exceptiongroup_subset(eg, rest_list, &result->rest) < 0) {
Py_CLEAR(result->match);
goto done;
}
}
retval = 0;
done:
Py_DECREF(match_list);
Py_XDECREF(rest_list);
if (retval < 0) {
Py_CLEAR(result->match);
Py_CLEAR(result->rest);
}
return retval;
}
/*[clinic input]
@critical_section
BaseExceptionGroup.split
matcher_value: object
/
[clinic start generated code]*/
static PyObject *
BaseExceptionGroup_split_impl(PyBaseExceptionGroupObject *self,
PyObject *matcher_value)
/*[clinic end generated code: output=d74db579da4df6e2 input=0c5cfbfed57e0052]*/
{
_exceptiongroup_split_matcher_type matcher_type;
if (get_matcher_type(matcher_value, &matcher_type) < 0) {
return NULL;
}
_exceptiongroup_split_result split_result;
bool construct_rest = true;
if (exceptiongroup_split_recursive(
(PyObject *)self, matcher_type, matcher_value,
construct_rest, &split_result) < 0) {
return NULL;
}
PyObject *result = PyTuple_Pack(
2,
split_result.match ? split_result.match : Py_None,
split_result.rest ? split_result.rest : Py_None);
Py_XDECREF(split_result.match);
Py_XDECREF(split_result.rest);
return result;
}
/*[clinic input]
@critical_section
BaseExceptionGroup.subgroup
matcher_value: object
/
[clinic start generated code]*/
static PyObject *
BaseExceptionGroup_subgroup_impl(PyBaseExceptionGroupObject *self,
PyObject *matcher_value)
/*[clinic end generated code: output=07dbec8f77d4dd8e input=988ffdd755a151ce]*/
{
_exceptiongroup_split_matcher_type matcher_type;
if (get_matcher_type(matcher_value, &matcher_type) < 0) {
return NULL;
}
_exceptiongroup_split_result split_result;
bool construct_rest = false;
if (exceptiongroup_split_recursive(
(PyObject *)self, matcher_type, matcher_value,
construct_rest, &split_result) < 0) {
return NULL;
}
PyObject *result = Py_NewRef(
split_result.match ? split_result.match : Py_None);
Py_XDECREF(split_result.match);
assert(!split_result.rest);
return result;
}
static int
collect_exception_group_leaf_ids(PyObject *exc, PyObject *leaf_ids)
{
if (Py_IsNone(exc)) {
return 0;
}
assert(PyExceptionInstance_Check(exc));
assert(PySet_Check(leaf_ids));
/* Add IDs of all leaf exceptions in exc to the leaf_ids set */
if (!_PyBaseExceptionGroup_Check(exc)) {
PyObject *exc_id = PyLong_FromVoidPtr(exc);
if (exc_id == NULL) {
return -1;
}
int res = PySet_Add(leaf_ids, exc_id);
Py_DECREF(exc_id);
return res;
}
PyBaseExceptionGroupObject *eg = PyBaseExceptionGroupObject_CAST(exc);
Py_ssize_t num_excs = PyTuple_GET_SIZE(eg->excs);
/* recursive calls */
for (Py_ssize_t i = 0; i < num_excs; i++) {
PyObject *e = PyTuple_GET_ITEM(eg->excs, i);
if (_Py_EnterRecursiveCall(" in collect_exception_group_leaf_ids")) {
return -1;
}
int res = collect_exception_group_leaf_ids(e, leaf_ids);
_Py_LeaveRecursiveCall();
if (res < 0) {
return -1;
}
}
return 0;
}
/* This function is used by the interpreter to construct reraised
* exception groups. It takes an exception group eg and a list
* of exception groups keep and returns the sub-exception group
* of eg which contains all leaf exceptions that are contained
* in any exception group in keep.
*/
static PyObject *
exception_group_projection(PyObject *eg, PyObject *keep)
{
assert(_PyBaseExceptionGroup_Check(eg));
assert(PyList_CheckExact(keep));
PyObject *leaf_ids = PySet_New(NULL);
if (!leaf_ids) {
return NULL;
}
Py_ssize_t n = PyList_GET_SIZE(keep);
for (Py_ssize_t i = 0; i < n; i++) {
PyObject *e = PyList_GET_ITEM(keep, i);
assert(e != NULL);
assert(_PyBaseExceptionGroup_Check(e));
if (collect_exception_group_leaf_ids(e, leaf_ids) < 0) {
Py_DECREF(leaf_ids);
return NULL;
}
}
_exceptiongroup_split_result split_result;
bool construct_rest = false;
int err = exceptiongroup_split_recursive(
eg, EXCEPTION_GROUP_MATCH_INSTANCE_IDS, leaf_ids,
construct_rest, &split_result);
Py_DECREF(leaf_ids);
if (err < 0) {
return NULL;
}
PyObject *result = split_result.match ?
split_result.match : Py_NewRef(Py_None);
assert(split_result.rest == NULL);
return result;
}
static bool
is_same_exception_metadata(PyObject *exc1, PyObject *exc2)
{
assert(PyExceptionInstance_Check(exc1));
assert(PyExceptionInstance_Check(exc2));
PyBaseExceptionObject *e1 = (PyBaseExceptionObject *)exc1;
PyBaseExceptionObject *e2 = (PyBaseExceptionObject *)exc2;
return (e1->notes == e2->notes &&
e1->traceback == e2->traceback &&
e1->cause == e2->cause &&
e1->context == e2->context);
}
/*
This function is used by the interpreter to calculate
the exception group to be raised at the end of a
try-except* construct.
orig: the original except that was caught.
excs: a list of exceptions that were raised/reraised
in the except* clauses.
Calculates an exception group to raise. It contains
all exceptions in excs, where those that were reraised
have same nesting structure as in orig, and those that
were raised (if any) are added as siblings in a new EG.
Returns NULL and sets an exception on failure.
*/
PyObject *
_PyExc_PrepReraiseStar(PyObject *orig, PyObject *excs)
{
/* orig must be a raised & caught exception, so it has a traceback */
assert(PyExceptionInstance_Check(orig));
assert(PyBaseExceptionObject_CAST(orig)->traceback != NULL);
assert(PyList_Check(excs));
Py_ssize_t numexcs = PyList_GET_SIZE(excs);
if (numexcs == 0) {
return Py_NewRef(Py_None);
}
if (!_PyBaseExceptionGroup_Check(orig)) {
/* a naked exception was caught and wrapped. Only one except* clause
* could have executed,so there is at most one exception to raise.
*/
assert(numexcs == 1 || (numexcs == 2 && PyList_GET_ITEM(excs, 1) == Py_None));
PyObject *e = PyList_GET_ITEM(excs, 0);
assert(e != NULL);
return Py_NewRef(e);
}
PyObject *raised_list = PyList_New(0);
if (raised_list == NULL) {
return NULL;
}
PyObject* reraised_list = PyList_New(0);
if (reraised_list == NULL) {
Py_DECREF(raised_list);
return NULL;
}
/* Now we are holding refs to raised_list and reraised_list */
PyObject *result = NULL;
/* Split excs into raised and reraised by comparing metadata with orig */
for (Py_ssize_t i = 0; i < numexcs; i++) {
PyObject *e = PyList_GET_ITEM(excs, i);
assert(e != NULL);
if (Py_IsNone(e)) {
continue;
}
bool is_reraise = is_same_exception_metadata(e, orig);
PyObject *append_list = is_reraise ? reraised_list : raised_list;
if (PyList_Append(append_list, e) < 0) {
goto done;
}
}
PyObject *reraised_eg = exception_group_projection(orig, reraised_list);
if (reraised_eg == NULL) {
goto done;
}
if (!Py_IsNone(reraised_eg)) {
assert(is_same_exception_metadata(reraised_eg, orig));
}
Py_ssize_t num_raised = PyList_GET_SIZE(raised_list);
if (num_raised == 0) {
result = reraised_eg;
}
else if (num_raised > 0) {
int res = 0;
if (!Py_IsNone(reraised_eg)) {
res = PyList_Append(raised_list, reraised_eg);
}
Py_DECREF(reraised_eg);
if (res < 0) {
goto done;
}
if (PyList_GET_SIZE(raised_list) > 1) {
result = _PyExc_CreateExceptionGroup("", raised_list);
}
else {
result = Py_NewRef(PyList_GetItem(raised_list, 0));
}
if (result == NULL) {
goto done;
}
}
done:
Py_XDECREF(raised_list);
Py_XDECREF(reraised_list);
return result;
}
PyObject *
PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs)
{
if (orig == NULL || !PyExceptionInstance_Check(orig)) {
PyErr_SetString(PyExc_TypeError, "orig must be an exception instance");
return NULL;
}
if (excs == NULL || !PyList_Check(excs)) {
PyErr_SetString(PyExc_TypeError,
"excs must be a list of exception instances");
return NULL;
}
Py_ssize_t numexcs = PyList_GET_SIZE(excs);
for (Py_ssize_t i = 0; i < numexcs; i++) {
PyObject *exc = PyList_GET_ITEM(excs, i);
if (exc == NULL || !(PyExceptionInstance_Check(exc) || Py_IsNone(exc))) {
PyErr_Format(PyExc_TypeError,
"item %d of excs is not an exception", i);
return NULL;
}
}
/* Make sure that orig has something as traceback, in the interpreter
* it always does because it's a raised exception.
*/
PyObject *tb = PyException_GetTraceback(orig);
if (tb == NULL) {
PyErr_Format(PyExc_ValueError, "orig must be a raised exception");
return NULL;
}
Py_DECREF(tb);
return _PyExc_PrepReraiseStar(orig, excs);
}
static PyMemberDef BaseExceptionGroup_members[] = {
{"message", _Py_T_OBJECT, offsetof(PyBaseExceptionGroupObject, msg), Py_READONLY,
PyDoc_STR("exception message")},
{"exceptions", _Py_T_OBJECT, offsetof(PyBaseExceptionGroupObject, excs), Py_READONLY,
PyDoc_STR("nested exceptions")},
{NULL} /* Sentinel */
};
static PyMethodDef BaseExceptionGroup_methods[] = {
{"__class_getitem__", Py_GenericAlias,
METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
BASEEXCEPTIONGROUP_DERIVE_METHODDEF
BASEEXCEPTIONGROUP_SPLIT_METHODDEF
BASEEXCEPTIONGROUP_SUBGROUP_METHODDEF
{NULL}
};
ComplexExtendsException(PyExc_BaseException, BaseExceptionGroup,
BaseExceptionGroup, BaseExceptionGroup_new /* new */,
BaseExceptionGroup_methods, BaseExceptionGroup_members,
0 /* getset */, BaseExceptionGroup_str, BaseExceptionGroup_repr,
"A combination of multiple unrelated exceptions.");
/*
* ExceptionGroup extends BaseExceptionGroup, Exception
*/
static PyObject*
create_exception_group_class(void) {
struct _Py_exc_state *state = get_exc_state();
PyObject *bases = PyTuple_Pack(
2, PyExc_BaseExceptionGroup, PyExc_Exception);
if (bases == NULL) {
return NULL;
}
assert(!state->PyExc_ExceptionGroup);
state->PyExc_ExceptionGroup = PyErr_NewException(
"builtins.ExceptionGroup", bases, NULL);
Py_DECREF(bases);
return state->PyExc_ExceptionGroup;
}
/*
* KeyboardInterrupt extends BaseException
*/
SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
"Program interrupted by user.");
/*
* ImportError extends Exception
*/
static inline PyImportErrorObject *
PyImportErrorObject_CAST(PyObject *self)
{
assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_ImportError));
return (PyImportErrorObject *)self;
}
static int
ImportError_init(PyObject *op, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"name", "path", "name_from", 0};
PyObject *empty_tuple;
PyObject *msg = NULL;
PyObject *name = NULL;
PyObject *path = NULL;
PyObject *name_from = NULL;
if (BaseException_init(op, args, NULL) == -1)
return -1;
PyImportErrorObject *self = PyImportErrorObject_CAST(op);
empty_tuple = PyTuple_New(0);
if (!empty_tuple)
return -1;
if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OOO:ImportError", kwlist,
&name, &path, &name_from)) {
Py_DECREF(empty_tuple);
return -1;
}
Py_DECREF(empty_tuple);
Py_XSETREF(self->name, Py_XNewRef(name));
Py_XSETREF(self->path, Py_XNewRef(path));
Py_XSETREF(self->name_from, Py_XNewRef(name_from));
if (PyTuple_GET_SIZE(args) == 1) {
msg = Py_NewRef(PyTuple_GET_ITEM(args, 0));
}
Py_XSETREF(self->msg, msg);
return 0;
}
static int
ImportError_clear(PyObject *op)
{
PyImportErrorObject *self = PyImportErrorObject_CAST(op);
Py_CLEAR(self->msg);
Py_CLEAR(self->name);
Py_CLEAR(self->path);
Py_CLEAR(self->name_from);
return BaseException_clear(op);
}
static void
ImportError_dealloc(PyObject *self)
{
_PyObject_GC_UNTRACK(self);
(void)ImportError_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
ImportError_traverse(PyObject *op, visitproc visit, void *arg)
{
PyImportErrorObject *self = PyImportErrorObject_CAST(op);
Py_VISIT(self->msg);
Py_VISIT(self->name);
Py_VISIT(self->path);
Py_VISIT(self->name_from);
return BaseException_traverse(op, visit, arg);
}
static PyObject *
ImportError_str(PyObject *op)
{
PyImportErrorObject *self = PyImportErrorObject_CAST(op);
if (self->msg && PyUnicode_CheckExact(self->msg)) {
return Py_NewRef(self->msg);
}
return BaseException_str(op);
}
static PyObject *
ImportError_getstate(PyObject *op)
{
PyImportErrorObject *self = PyImportErrorObject_CAST(op);
PyObject *dict = self->dict;
if (self->name || self->path || self->name_from) {
dict = dict ? PyDict_Copy(dict) : PyDict_New();
if (dict == NULL)
return NULL;
if (self->name && PyDict_SetItem(dict, &_Py_ID(name), self->name) < 0) {
Py_DECREF(dict);
return NULL;
}
if (self->path && PyDict_SetItem(dict, &_Py_ID(path), self->path) < 0) {
Py_DECREF(dict);
return NULL;
}
if (self->name_from && PyDict_SetItem(dict, &_Py_ID(name_from), self->name_from) < 0) {
Py_DECREF(dict);
return NULL;
}
return dict;
}
else if (dict) {
return Py_NewRef(dict);
}
else {
Py_RETURN_NONE;
}
}
/* Pickling support */
static PyObject *
ImportError_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *res;
PyObject *state = ImportError_getstate(self);
if (state == NULL)
return NULL;
PyBaseExceptionObject *exc = PyBaseExceptionObject_CAST(self);
if (state == Py_None)
res = PyTuple_Pack(2, Py_TYPE(self), exc->args);
else
res = PyTuple_Pack(3, Py_TYPE(self), exc->args, state);
Py_DECREF(state);
return res;
}
static PyObject *
ImportError_repr(PyObject *self)
{
int hasargs = PyTuple_GET_SIZE(((PyBaseExceptionObject *)self)->args) != 0;
PyImportErrorObject *exc = PyImportErrorObject_CAST(self);
if (exc->name == NULL && exc->path == NULL) {
return BaseException_repr(self);
}
PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
if (writer == NULL) {
goto error;
}
PyObject *r = BaseException_repr(self);
if (r == NULL) {
goto error;
}
if (PyUnicodeWriter_WriteSubstring(
writer, r, 0, PyUnicode_GET_LENGTH(r) - 1) < 0)
{
Py_DECREF(r);
goto error;
}
Py_DECREF(r);
if (exc->name) {
if (hasargs) {
if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) {
goto error;
}
}
if (PyUnicodeWriter_Format(writer, "name=%R", exc->name) < 0) {
goto error;
}
hasargs = 1;
}
if (exc->path) {
if (hasargs) {
if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) {
goto error;
}
}
if (PyUnicodeWriter_Format(writer, "path=%R", exc->path) < 0) {
goto error;
}
}
if (PyUnicodeWriter_WriteChar(writer, ')') < 0) {
goto error;
}
return PyUnicodeWriter_Finish(writer);
error:
PyUnicodeWriter_Discard(writer);
return NULL;
}
static PyMemberDef ImportError_members[] = {
{"msg", _Py_T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
PyDoc_STR("exception message")},
{"name", _Py_T_OBJECT, offsetof(PyImportErrorObject, name), 0,
PyDoc_STR("module name")},
{"path", _Py_T_OBJECT, offsetof(PyImportErrorObject, path), 0,
PyDoc_STR("module path")},
{"name_from", _Py_T_OBJECT, offsetof(PyImportErrorObject, name_from), 0,
PyDoc_STR("name imported from module")},
{NULL} /* Sentinel */
};
static PyMethodDef ImportError_methods[] = {
{"__reduce__", ImportError_reduce, METH_NOARGS},
{NULL}
};
static PyTypeObject _PyExc_ImportError = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "ImportError",
.tp_basicsize = sizeof(PyImportErrorObject),
.tp_dealloc = ImportError_dealloc,
.tp_repr = ImportError_repr,
.tp_str = ImportError_str,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
.tp_doc = PyDoc_STR(
"Import can't find module, "
"or can't find name in module."),
.tp_traverse = ImportError_traverse,
.tp_clear = ImportError_clear,
.tp_methods = ImportError_methods,
.tp_members = ImportError_members,
.tp_base = &_PyExc_Exception,
.tp_dictoffset = offsetof(PyImportErrorObject, dict),
.tp_init = ImportError_init,
};
PyObject *PyExc_ImportError = (PyObject *)&_PyExc_ImportError;
/*
* ModuleNotFoundError extends ImportError
*/
MiddlingExtendsException(PyExc_ImportError, ModuleNotFoundError, ImportError,
"Module not found.");
/*
* OSError extends Exception
*/
static inline PyOSErrorObject *
PyOSErrorObject_CAST(PyObject *self)
{
assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_OSError));
return (PyOSErrorObject *)self;
}
#ifdef MS_WINDOWS
#include "errmap.h"
#endif
/* Where a function has a single filename, such as open() or some
* of the os module functions, PyErr_SetFromErrnoWithFilename() is
* called, giving a third argument which is the filename. But, so
* that old code using in-place unpacking doesn't break, e.g.:
*
* except OSError, (errno, strerror):
*
* we hack args so that it only contains two items. This also
* means we need our own __str__() which prints out the filename
* when it was supplied.
*
* (If a function has two filenames, such as rename(), symlink(),
* or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
* which allows passing in a second filename.)
*/
/* This function doesn't cleanup on error, the caller should */
static int
oserror_parse_args(PyObject **p_args,
PyObject **myerrno, PyObject **strerror,
PyObject **filename, PyObject **filename2
#ifdef MS_WINDOWS
, PyObject **winerror
#endif
)
{
Py_ssize_t nargs;
PyObject *args = *p_args;
#ifndef MS_WINDOWS
/*
* ignored on non-Windows platforms,
* but parsed so OSError has a consistent signature
*/
PyObject *_winerror = NULL;
PyObject **winerror = &_winerror;
#endif /* MS_WINDOWS */
nargs = PyTuple_GET_SIZE(args);
if (nargs >= 2 && nargs <= 5) {
if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
myerrno, strerror,
filename, winerror, filename2))
return -1;
#ifdef MS_WINDOWS
if (*winerror && PyLong_Check(*winerror)) {
long errcode, winerrcode;
PyObject *newargs;
Py_ssize_t i;
winerrcode = PyLong_AsLong(*winerror);
if (winerrcode == -1 && PyErr_Occurred())
return -1;
errcode = winerror_to_errno(winerrcode);
*myerrno = PyLong_FromLong(errcode);
if (!*myerrno)
return -1;
newargs = PyTuple_New(nargs);
if (!newargs)
return -1;
PyTuple_SET_ITEM(newargs, 0, *myerrno);
for (i = 1; i < nargs; i++) {
PyObject *val = PyTuple_GET_ITEM(args, i);
PyTuple_SET_ITEM(newargs, i, Py_NewRef(val));
}
Py_DECREF(args);
args = *p_args = newargs;
}
#endif /* MS_WINDOWS */
}
return 0;
}
static int
oserror_init(PyOSErrorObject *self, PyObject **p_args,
PyObject *myerrno, PyObject *strerror,
PyObject *filename, PyObject *filename2
#ifdef MS_WINDOWS
, PyObject *winerror
#endif
)
{
PyObject *args = *p_args;
Py_ssize_t nargs = PyTuple_GET_SIZE(args);
/* self->filename will remain Py_None otherwise */
if (filename && filename != Py_None) {
if (Py_IS_TYPE(self, (PyTypeObject *) PyExc_BlockingIOError) &&
PyNumber_Check(filename)) {
/* BlockingIOError's 3rd argument can be the number of
* characters written.
*/
self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
if (self->written == -1 && PyErr_Occurred())
return -1;
}
else {
self->filename = Py_NewRef(filename);
if (filename2 && filename2 != Py_None) {
self->filename2 = Py_NewRef(filename2);
}
if (nargs >= 2 && nargs <= 5) {
/* filename, filename2, and winerror are removed from the args tuple
(for compatibility purposes, see test_exceptions.py) */
PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
if (!subslice)
return -1;
Py_DECREF(args); /* replacing args */
*p_args = args = subslice;
}
}
}
self->myerrno = Py_XNewRef(myerrno);
self->strerror = Py_XNewRef(strerror);
#ifdef MS_WINDOWS
self->winerror = Py_XNewRef(winerror);
#endif
/* Steals the reference to args */
Py_XSETREF(self->args, args);
*p_args = args = NULL;
return 0;
}
static PyObject *
OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int
OSError_init(PyObject *self, PyObject *args, PyObject *kwds);
static int
oserror_use_init(PyTypeObject *type)
{
/* When __init__ is defined in an OSError subclass, we want any
extraneous argument to __new__ to be ignored. The only reasonable
solution, given __new__ takes a variable number of arguments,
is to defer arg parsing and initialization to __init__.
But when __new__ is overridden as well, it should call our __new__
with the right arguments.
(see http://bugs.python.org/issue12555#msg148829 )
*/
if (type->tp_init != OSError_init && type->tp_new == OSError_new) {
assert((PyObject *) type != PyExc_OSError);
return 1;
}
return 0;
}
static PyObject *
OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyOSErrorObject *self = NULL;
PyObject *myerrno = NULL, *strerror = NULL;
PyObject *filename = NULL, *filename2 = NULL;
#ifdef MS_WINDOWS
PyObject *winerror = NULL;
#endif
Py_INCREF(args);
if (!oserror_use_init(type)) {
if (!_PyArg_NoKeywords(type->tp_name, kwds))
goto error;
if (oserror_parse_args(&args, &myerrno, &strerror,
&filename, &filename2
#ifdef MS_WINDOWS
, &winerror
#endif
))
goto error;
struct _Py_exc_state *state = get_exc_state();
if (myerrno && PyLong_Check(myerrno) &&
state->errnomap && (PyObject *) type == PyExc_OSError) {
PyObject *newtype;
newtype = PyDict_GetItemWithError(state->errnomap, myerrno);
if (newtype) {
type = _PyType_CAST(newtype);
}
else if (PyErr_Occurred())
goto error;
}
}
self = (PyOSErrorObject *) type->tp_alloc(type, 0);
if (!self)
goto error;
self->dict = NULL;
self->traceback = self->cause = self->context = NULL;
self->written = -1;
if (!oserror_use_init(type)) {
if (oserror_init(self, &args, myerrno, strerror, filename, filename2
#ifdef MS_WINDOWS
, winerror
#endif
))
goto error;
}
else {
self->args = PyTuple_New(0);
if (self->args == NULL)
goto error;
}
Py_XDECREF(args);
return (PyObject *) self;
error:
Py_XDECREF(args);
Py_XDECREF(self);
return NULL;
}
static int
OSError_init(PyObject *op, PyObject *args, PyObject *kwds)
{
PyOSErrorObject *self = PyOSErrorObject_CAST(op);
PyObject *myerrno = NULL, *strerror = NULL;
PyObject *filename = NULL, *filename2 = NULL;
#ifdef MS_WINDOWS
PyObject *winerror = NULL;
#endif
if (!oserror_use_init(Py_TYPE(self)))
/* Everything already done in OSError_new */
return 0;
if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
return -1;
Py_INCREF(args);
if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
#ifdef MS_WINDOWS
, &winerror
#endif
))
goto error;
if (oserror_init(self, &args, myerrno, strerror, filename, filename2
#ifdef MS_WINDOWS
, winerror
#endif
))
goto error;
return 0;
error:
Py_DECREF(args);
return -1;
}
static int
OSError_clear(PyObject *op)
{
PyOSErrorObject *self = PyOSErrorObject_CAST(op);
Py_CLEAR(self->myerrno);
Py_CLEAR(self->strerror);
Py_CLEAR(self->filename);
Py_CLEAR(self->filename2);
#ifdef MS_WINDOWS
Py_CLEAR(self->winerror);
#endif
return BaseException_clear(op);
}
static void
OSError_dealloc(PyObject *self)
{
_PyObject_GC_UNTRACK(self);
(void)OSError_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
OSError_traverse(PyObject *op, visitproc visit, void *arg)
{
PyOSErrorObject *self = PyOSErrorObject_CAST(op);
Py_VISIT(self->myerrno);
Py_VISIT(self->strerror);
Py_VISIT(self->filename);
Py_VISIT(self->filename2);
#ifdef MS_WINDOWS
Py_VISIT(self->winerror);
#endif
return BaseException_traverse(op, visit, arg);
}
static PyObject *
OSError_str(PyObject *op)
{
PyOSErrorObject *self = PyOSErrorObject_CAST(op);
#define OR_NONE(x) ((x)?(x):Py_None)
#ifdef MS_WINDOWS
/* If available, winerror has the priority over myerrno */
if (self->winerror && self->filename) {
if (self->filename2) {
return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
OR_NONE(self->winerror),
OR_NONE(self->strerror),
self->filename,
self->filename2);
} else {
return PyUnicode_FromFormat("[WinError %S] %S: %R",
OR_NONE(self->winerror),
OR_NONE(self->strerror),
self->filename);
}
}
if (self->winerror && self->strerror)
return PyUnicode_FromFormat("[WinError %S] %S",
self->winerror ? self->winerror: Py_None,
self->strerror ? self->strerror: Py_None);
#endif
if (self->filename) {
if (self->filename2) {
return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
OR_NONE(self->myerrno),
OR_NONE(self->strerror),
self->filename,
self->filename2);
} else {
return PyUnicode_FromFormat("[Errno %S] %S: %R",
OR_NONE(self->myerrno),
OR_NONE(self->strerror),
self->filename);
}
}
if (self->myerrno && self->strerror)
return PyUnicode_FromFormat("[Errno %S] %S",
self->myerrno, self->strerror);
return BaseException_str(op);
}
static PyObject *
OSError_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
{
PyOSErrorObject *self = PyOSErrorObject_CAST(op);
PyObject *args = self->args;
PyObject *res = NULL;
/* self->args is only the first two real arguments if there was a
* file name given to OSError. */
if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Py_ssize_t size = self->filename2 ? 5 : 3;
args = PyTuple_New(size);
if (!args)
return NULL;
PyTuple_SET_ITEM(args, 0, Py_NewRef(PyTuple_GET_ITEM(self->args, 0)));
PyTuple_SET_ITEM(args, 1, Py_NewRef(PyTuple_GET_ITEM(self->args, 1)));
PyTuple_SET_ITEM(args, 2, Py_NewRef(self->filename));
if (self->filename2) {
/*
* This tuple is essentially used as OSError(*args).
* So, to recreate filename2, we need to pass in
* winerror as well.
*/
PyTuple_SET_ITEM(args, 3, Py_NewRef(Py_None));
/* filename2 */
PyTuple_SET_ITEM(args, 4, Py_NewRef(self->filename2));
}
} else
Py_INCREF(args);
if (self->dict)
res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
else
res = PyTuple_Pack(2, Py_TYPE(self), args);
Py_DECREF(args);
return res;
}
static PyObject *
OSError_written_get(PyObject *op, void *context)
{
PyOSErrorObject *self = PyOSErrorObject_CAST(op);
if (self->written == -1) {
PyErr_SetString(PyExc_AttributeError, "characters_written");
return NULL;
}
return PyLong_FromSsize_t(self->written);
}
static int
OSError_written_set(PyObject *op, PyObject *arg, void *context)
{
PyOSErrorObject *self = PyOSErrorObject_CAST(op);
if (arg == NULL) {
if (self->written == -1) {
PyErr_SetString(PyExc_AttributeError, "characters_written");
return -1;
}
self->written = -1;
return 0;
}
Py_ssize_t n;
n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
if (n == -1 && PyErr_Occurred())
return -1;
self->written = n;
return 0;
}
static PyMemberDef OSError_members[] = {
{"errno", _Py_T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
PyDoc_STR("POSIX exception code")},
{"strerror", _Py_T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
PyDoc_STR("exception strerror")},
{"filename", _Py_T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
PyDoc_STR("exception filename")},
{"filename2", _Py_T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
PyDoc_STR("second exception filename")},
#ifdef MS_WINDOWS
{"winerror", _Py_T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
PyDoc_STR("Win32 exception code")},
#endif
{NULL} /* Sentinel */
};
static PyMethodDef OSError_methods[] = {
{"__reduce__", OSError_reduce, METH_NOARGS},
{NULL}
};
static PyGetSetDef OSError_getset[] = {
{"characters_written", OSError_written_get,
OSError_written_set, NULL},
{NULL}
};
ComplexExtendsException(PyExc_Exception, OSError,
OSError, OSError_new,
OSError_methods, OSError_members, OSError_getset,
OSError_str, 0,
"Base class for I/O related errors.");
/*
* Various OSError subclasses
*/
MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
"I/O operation would block.");
MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
"Connection error.");
MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
"Child process error.");
MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
"Broken pipe.");
MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
"Connection aborted.");
MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
"Connection refused.");
MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
"Connection reset.");
MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
"File already exists.");
MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
"File not found.");
MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
"Operation doesn't work on directories.");
MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
"Operation only works on directories.");
MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
"Interrupted by signal.");
MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
"Not enough permissions.");
MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
"Process not found.");
MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
"Timeout expired.");
/* Compatibility aliases */
PyObject *PyExc_EnvironmentError = (PyObject *)&_PyExc_OSError; // borrowed ref
PyObject *PyExc_IOError = (PyObject *)&_PyExc_OSError; // borrowed ref
#ifdef MS_WINDOWS
PyObject *PyExc_WindowsError = (PyObject *)&_PyExc_OSError; // borrowed ref
#endif
/*
* EOFError extends Exception
*/
SimpleExtendsException(PyExc_Exception, EOFError,
"Read beyond end of file.");
/*
* RuntimeError extends Exception
*/
SimpleExtendsException(PyExc_Exception, RuntimeError,
"Unspecified run-time error.");
/*
* RecursionError extends RuntimeError
*/
SimpleExtendsException(PyExc_RuntimeError, RecursionError,
"Recursion limit exceeded.");
// PythonFinalizationError extends RuntimeError
SimpleExtendsException(PyExc_RuntimeError, PythonFinalizationError,
"Operation blocked during Python finalization.");
/*
* NotImplementedError extends RuntimeError
*/
SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
"Method or function hasn't been implemented yet.");
/*
* NameError extends Exception
*/
static inline PyNameErrorObject *
PyNameErrorObject_CAST(PyObject *self)
{
assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_NameError));
return (PyNameErrorObject *)self;
}
static int
NameError_init(PyObject *op, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"name", NULL};
PyObject *name = NULL;
if (BaseException_init(op, args, NULL) == -1) {
return -1;
}
PyObject *empty_tuple = PyTuple_New(0);
if (!empty_tuple) {
return -1;
}
if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$O:NameError", kwlist,
&name)) {
Py_DECREF(empty_tuple);
return -1;
}
Py_DECREF(empty_tuple);
PyNameErrorObject *self = PyNameErrorObject_CAST(op);
Py_XSETREF(self->name, Py_XNewRef(name));
return 0;
}
static int
NameError_clear(PyObject *op)
{
PyNameErrorObject *self = PyNameErrorObject_CAST(op);
Py_CLEAR(self->name);
return BaseException_clear(op);
}
static void
NameError_dealloc(PyObject *self)
{
_PyObject_GC_UNTRACK(self);
(void)NameError_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
NameError_traverse(PyObject *op, visitproc visit, void *arg)
{
PyNameErrorObject *self = PyNameErrorObject_CAST(op);
Py_VISIT(self->name);
return BaseException_traverse(op, visit, arg);
}
static PyMemberDef NameError_members[] = {
{"name", _Py_T_OBJECT, offsetof(PyNameErrorObject, name), 0, PyDoc_STR("name")},
{NULL} /* Sentinel */
};
static PyMethodDef NameError_methods[] = {
{NULL} /* Sentinel */
};
ComplexExtendsException(PyExc_Exception, NameError,
NameError, 0,
NameError_methods, NameError_members,
0, BaseException_str, 0, "Name not found globally.");
/*
* UnboundLocalError extends NameError
*/
MiddlingExtendsException(PyExc_NameError, UnboundLocalError, NameError,
"Local name referenced but not bound to a value.");
/*
* AttributeError extends Exception
*/
static inline PyAttributeErrorObject *
PyAttributeErrorObject_CAST(PyObject *self)
{
assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_AttributeError));
return (PyAttributeErrorObject *)self;
}
static int
AttributeError_init(PyObject *op, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"name", "obj", NULL};
PyObject *name = NULL;
PyObject *obj = NULL;
if (BaseException_init(op, args, NULL) == -1) {
return -1;
}
PyObject *empty_tuple = PyTuple_New(0);
if (!empty_tuple) {
return -1;
}
if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OO:AttributeError", kwlist,
&name, &obj)) {
Py_DECREF(empty_tuple);
return -1;
}
Py_DECREF(empty_tuple);
PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op);
Py_XSETREF(self->name, Py_XNewRef(name));
Py_XSETREF(self->obj, Py_XNewRef(obj));
return 0;
}
static int
AttributeError_clear(PyObject *op)
{
PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op);
Py_CLEAR(self->obj);
Py_CLEAR(self->name);
return BaseException_clear(op);
}
static void
AttributeError_dealloc(PyObject *self)
{
_PyObject_GC_UNTRACK(self);
(void)AttributeError_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
AttributeError_traverse(PyObject *op, visitproc visit, void *arg)
{
PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op);
Py_VISIT(self->obj);
Py_VISIT(self->name);
return BaseException_traverse(op, visit, arg);
}
/* Pickling support */
static PyObject *
AttributeError_getstate(PyObject *op, PyObject *Py_UNUSED(ignored))
{
PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op);
PyObject *dict = self->dict;
if (self->name || self->args) {
dict = dict ? PyDict_Copy(dict) : PyDict_New();
if (dict == NULL) {
return NULL;
}
if (self->name && PyDict_SetItemString(dict, "name", self->name) < 0) {
Py_DECREF(dict);
return NULL;
}
/* We specifically are not pickling the obj attribute since there are many
cases where it is unlikely to be picklable. See GH-103352.
*/
if (self->args && PyDict_SetItemString(dict, "args", self->args) < 0) {
Py_DECREF(dict);
return NULL;
}
return dict;
}
else if (dict) {
return Py_NewRef(dict);
}
Py_RETURN_NONE;
}
static PyObject *
AttributeError_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
{
PyObject *state = AttributeError_getstate(op, NULL);
if (state == NULL) {
return NULL;
}
PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op);
PyObject *return_value = PyTuple_Pack(3, Py_TYPE(self), self->args, state);
Py_DECREF(state);
return return_value;
}
static PyMemberDef AttributeError_members[] = {
{"name", _Py_T_OBJECT, offsetof(PyAttributeErrorObject, name), 0, PyDoc_STR("attribute name")},
{"obj", _Py_T_OBJECT, offsetof(PyAttributeErrorObject, obj), 0, PyDoc_STR("object")},
{NULL} /* Sentinel */
};
static PyMethodDef AttributeError_methods[] = {
{"__getstate__", AttributeError_getstate, METH_NOARGS},
{"__reduce__", AttributeError_reduce, METH_NOARGS },
{NULL}
};
ComplexExtendsException(PyExc_Exception, AttributeError,
AttributeError, 0,
AttributeError_methods, AttributeError_members,
0, BaseException_str, 0, "Attribute not found.");
/*
* SyntaxError extends Exception
*/
static inline PySyntaxErrorObject *
PySyntaxErrorObject_CAST(PyObject *self)
{
assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_SyntaxError));
return (PySyntaxErrorObject *)self;
}
static int
SyntaxError_init(PyObject *op, PyObject *args, PyObject *kwds)
{
PyObject *info = NULL;
Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
if (BaseException_init(op, args, kwds) == -1)
return -1;
PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op);
if (lenargs >= 1) {
Py_XSETREF(self->msg, Py_NewRef(PyTuple_GET_ITEM(args, 0)));
}
if (lenargs == 2) {
info = PyTuple_GET_ITEM(args, 1);
info = PySequence_Tuple(info);
if (!info) {
return -1;
}
self->end_lineno = NULL;
self->end_offset = NULL;
if (!PyArg_ParseTuple(info, "OOOO|OOO",
&self->filename, &self->lineno,
&self->offset, &self->text,
&self->end_lineno, &self->end_offset, &self->metadata)) {
Py_DECREF(info);
return -1;
}
Py_INCREF(self->filename);
Py_INCREF(self->lineno);
Py_INCREF(self->offset);
Py_INCREF(self->text);
Py_XINCREF(self->end_lineno);
Py_XINCREF(self->end_offset);
Py_XINCREF(self->metadata);
Py_DECREF(info);
if (self->end_lineno != NULL && self->end_offset == NULL) {
PyErr_SetString(PyExc_TypeError, "end_offset must be provided when end_lineno is provided");
return -1;
}
}
return 0;
}
static int
SyntaxError_clear(PyObject *op)
{
PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op);
Py_CLEAR(self->msg);
Py_CLEAR(self->filename);
Py_CLEAR(self->lineno);
Py_CLEAR(self->offset);
Py_CLEAR(self->end_lineno);
Py_CLEAR(self->end_offset);
Py_CLEAR(self->text);
Py_CLEAR(self->print_file_and_line);
Py_CLEAR(self->metadata);
return BaseException_clear(op);
}
static void
SyntaxError_dealloc(PyObject *self)
{
_PyObject_GC_UNTRACK(self);
(void)SyntaxError_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
SyntaxError_traverse(PyObject *op, visitproc visit, void *arg)
{
PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op);
Py_VISIT(self->msg);
Py_VISIT(self->filename);
Py_VISIT(self->lineno);
Py_VISIT(self->offset);
Py_VISIT(self->end_lineno);
Py_VISIT(self->end_offset);
Py_VISIT(self->text);
Py_VISIT(self->print_file_and_line);
Py_VISIT(self->metadata);
return BaseException_traverse(op, visit, arg);
}
/* This is called "my_basename" instead of just "basename" to avoid name
conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
defined, and Python does define that. */
static PyObject*
my_basename(PyObject *name)
{
Py_ssize_t i, size, offset;
int kind;
const void *data;
kind = PyUnicode_KIND(name);
data = PyUnicode_DATA(name);
size = PyUnicode_GET_LENGTH(name);
offset = 0;
for(i=0; i < size; i++) {
if (PyUnicode_READ(kind, data, i) == SEP) {
offset = i + 1;
}
}
if (offset != 0) {
return PyUnicode_Substring(name, offset, size);
}
else {
return Py_NewRef(name);
}
}
static PyObject *
SyntaxError_str(PyObject *op)
{
PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op);
int have_lineno = 0;
PyObject *filename;
PyObject *result;
/* Below, we always ignore overflow errors, just printing -1.
Still, we cannot allow an OverflowError to be raised, so
we need to call PyLong_AsLongAndOverflow. */
int overflow;
/* XXX -- do all the additional formatting with filename and
lineno here */
if (self->filename && PyUnicode_Check(self->filename)) {
filename = my_basename(self->filename);
if (filename == NULL)
return NULL;
} else {
filename = NULL;
}
have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
if (!filename && !have_lineno)
return PyObject_Str(self->msg ? self->msg : Py_None);
// Even if 'filename' can be an instance of a subclass of 'str',
// we only render its "true" content and do not use str(filename).
if (filename && have_lineno)
result = PyUnicode_FromFormat("%S (%U, line %ld)",
self->msg ? self->msg : Py_None,
filename,
PyLong_AsLongAndOverflow(self->lineno, &overflow));
else if (filename)
result = PyUnicode_FromFormat("%S (%U)",
self->msg ? self->msg : Py_None,
filename);
else /* only have_lineno */
result = PyUnicode_FromFormat("%S (line %ld)",
self->msg ? self->msg : Py_None,
PyLong_AsLongAndOverflow(self->lineno, &overflow));
Py_XDECREF(filename);
return result;
}
static PyMemberDef SyntaxError_members[] = {
{"msg", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
PyDoc_STR("exception msg")},
{"filename", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
PyDoc_STR("exception filename")},
{"lineno", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
PyDoc_STR("exception lineno")},
{"offset", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
PyDoc_STR("exception offset")},
{"text", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
PyDoc_STR("exception text")},
{"end_lineno", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, end_lineno), 0,
PyDoc_STR("exception end lineno")},
{"end_offset", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, end_offset), 0,
PyDoc_STR("exception end offset")},
{"print_file_and_line", _Py_T_OBJECT,
offsetof(PySyntaxErrorObject, print_file_and_line), 0,
PyDoc_STR("exception print_file_and_line")},
{"_metadata", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, metadata), 0,
PyDoc_STR("exception private metadata")},
{NULL} /* Sentinel */
};
ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
0, 0, SyntaxError_members, 0,
SyntaxError_str, 0, "Invalid syntax.");
/*
* IndentationError extends SyntaxError
*/
MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
"Improper indentation.");
/*
* TabError extends IndentationError
*/
MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
"Improper mixture of spaces and tabs.");
/*
* IncompleteInputError extends SyntaxError
*/
MiddlingExtendsExceptionEx(PyExc_SyntaxError, IncompleteInputError, _IncompleteInputError,
SyntaxError, "incomplete input.");
/*
* LookupError extends Exception
*/
SimpleExtendsException(PyExc_Exception, LookupError,
"Base class for lookup errors.");
/*
* IndexError extends LookupError
*/
SimpleExtendsException(PyExc_LookupError, IndexError,
"Sequence index out of range.");
/*
* KeyError extends LookupError
*/
static PyObject *
KeyError_str(PyObject *op)
{
/* If args is a tuple of exactly one item, apply repr to args[0].
This is done so that e.g. the exception raised by {}[''] prints
KeyError: ''
rather than the confusing
KeyError
alone. The downside is that if KeyError is raised with an explanatory
string, that string will be displayed in quotes. Too bad.
If args is anything else, use the default BaseException__str__().
*/
PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op);
if (PyTuple_GET_SIZE(self->args) == 1) {
return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
}
return BaseException_str(op);
}
ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
0, 0, 0, 0, KeyError_str, 0, "Mapping key not found.");
/*
* ValueError extends Exception
*/
SimpleExtendsException(PyExc_Exception, ValueError,
"Inappropriate argument value (of correct type).");
/*
* UnicodeError extends ValueError
*/
SimpleExtendsException(PyExc_ValueError, UnicodeError,
"Unicode related error.");
/*
* Check the validity of 'attr' as a unicode or bytes object depending
* on 'as_bytes'.
*
* The 'name' is the attribute name and is only used for error reporting.
*
* On success, this returns 0.
* On failure, this sets a TypeError and returns -1.
*/
static int
check_unicode_error_attribute(PyObject *attr, const char *name, int as_bytes)
{
assert(as_bytes == 0 || as_bytes == 1);
if (attr == NULL) {
PyErr_Format(PyExc_TypeError,
"UnicodeError '%s' attribute is not set",
name);
return -1;
}
if (!(as_bytes ? PyBytes_Check(attr) : PyUnicode_Check(attr))) {
PyErr_Format(PyExc_TypeError,
"UnicodeError '%s' attribute must be a %s",
name, as_bytes ? "bytes" : "string");
return -1;
}
return 0;
}
/*
* Check the validity of 'attr' as a unicode or bytes object depending
* on 'as_bytes' and return a new reference on it if it is the case.
*
* The 'name' is the attribute name and is only used for error reporting.
*
* On success, this returns a strong reference on 'attr'.
* On failure, this sets a TypeError and returns NULL.
*/
static PyObject *
as_unicode_error_attribute(PyObject *attr, const char *name, int as_bytes)
{
int rc = check_unicode_error_attribute(attr, name, as_bytes);
return rc < 0 ? NULL : Py_NewRef(attr);
}
#define PyUnicodeError_Check(PTR) \
PyObject_TypeCheck((PTR), (PyTypeObject *)PyExc_UnicodeError)
#define PyUnicodeError_CAST(PTR) \
(assert(PyUnicodeError_Check(PTR)), ((PyUnicodeErrorObject *)(PTR)))
/* class names to use when reporting errors */
#define Py_UNICODE_ENCODE_ERROR_NAME "UnicodeEncodeError"
#define Py_UNICODE_DECODE_ERROR_NAME "UnicodeDecodeError"
#define Py_UNICODE_TRANSLATE_ERROR_NAME "UnicodeTranslateError"
/*
* Check that 'self' is a UnicodeError object.
*
* On success, this returns 0.
* On failure, this sets a TypeError exception and returns -1.
*
* The 'expect_type' is the name of the expected type, which is
* only used for error reporting.
*
* As an implementation detail, the `PyUnicode*Error_*` functions
* currently allow *any* subclass of UnicodeError as 'self'.
*
* Use one of the `Py_UNICODE_*_ERROR_NAME` macros to avoid typos.
*/
static inline int
check_unicode_error_type(PyObject *self, const char *expect_type)
{
assert(self != NULL);
if (!PyUnicodeError_Check(self)) {
PyErr_Format(PyExc_TypeError,
"expecting a %s object, got %T", expect_type, self);
return -1;
}
return 0;
}
// --- PyUnicodeEncodeObject: internal helpers --------------------------------
//
// In the helpers below, the caller is responsible to ensure that 'self'
// is a PyUnicodeErrorObject, although this is verified on DEBUG builds
// through PyUnicodeError_CAST().
/*
* Return the underlying (str) 'encoding' attribute of a UnicodeError object.
*/
static inline PyObject *
unicode_error_get_encoding_impl(PyObject *self)
{
assert(self != NULL);
PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self);
return as_unicode_error_attribute(exc->encoding, "encoding", false);
}
/*
* Return the underlying 'object' attribute of a UnicodeError object
* as a bytes or a string instance, depending on the 'as_bytes' flag.
*/
static inline PyObject *
unicode_error_get_object_impl(PyObject *self, int as_bytes)
{
assert(self != NULL);
PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self);
return as_unicode_error_attribute(exc->object, "object", as_bytes);
}
/*
* Return the underlying (str) 'reason' attribute of a UnicodeError object.
*/
static inline PyObject *
unicode_error_get_reason_impl(PyObject *self)
{
assert(self != NULL);
PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self);
return as_unicode_error_attribute(exc->reason, "reason", false);
}
/*
* Set the underlying (str) 'reason' attribute of a UnicodeError object.
*
* Return 0 on success and -1 on failure.
*/
static inline int
unicode_error_set_reason_impl(PyObject *self, const char *reason)
{
assert(self != NULL);
PyObject *value = PyUnicode_FromString(reason);
if (value == NULL) {
return -1;
}
PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self);
Py_XSETREF(exc->reason, value);
return 0;
}
/*
* Set the 'start' attribute of a UnicodeError object.
*
* Return 0 on success and -1 on failure.
*/
static inline int
unicode_error_set_start_impl(PyObject *self, Py_ssize_t start)
{
assert(self != NULL);
PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self);
exc->start = start;
return 0;
}
/*
* Set the 'end' attribute of a UnicodeError object.
*
* Return 0 on success and -1 on failure.
*/
static inline int
unicode_error_set_end_impl(PyObject *self, Py_ssize_t end)
{
assert(self != NULL);
PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self);
exc->end = end;
return 0;
}
// --- PyUnicodeEncodeObject: internal getters --------------------------------
/*
* Adjust the (inclusive) 'start' value of a UnicodeError object.
*
* The 'start' can be negative or not, but when adjusting the value,
* we clip it in [0, max(0, objlen - 1)] and do not interpret it as
* a relative offset.
*
* This function always succeeds.
*/
static Py_ssize_t
unicode_error_adjust_start(Py_ssize_t start, Py_ssize_t objlen)
{
assert(objlen >= 0);
if (start < 0) {
start = 0;
}
if (start >= objlen) {
start = objlen == 0 ? 0 : objlen - 1;
}
return start;
}
/* Assert some properties of the adjusted 'start' value. */
#ifndef NDEBUG
static void
assert_adjusted_unicode_error_start(Py_ssize_t start, Py_ssize_t objlen)
{
assert(objlen >= 0);
/* in the future, `min_start` may be something else */
Py_ssize_t min_start = 0;
assert(start >= min_start);
/* in the future, `max_start` may be something else */
Py_ssize_t max_start = Py_MAX(min_start, objlen - 1);
assert(start <= max_start);
}
#else
#define assert_adjusted_unicode_error_start(...)
#endif
/*
* Adjust the (exclusive) 'end' value of a UnicodeError object.
*
* The 'end' can be negative or not, but when adjusting the value,
* we clip it in [min(1, objlen), max(min(1, objlen), objlen)] and
* do not interpret it as a relative offset.
*
* This function always succeeds.
*/
static Py_ssize_t
unicode_error_adjust_end(Py_ssize_t end, Py_ssize_t objlen)
{
assert(objlen >= 0);
if (end < 1) {
end = 1;
}
if (end > objlen) {
end = objlen;
}
return end;
}
#define PyUnicodeError_Check(PTR) \
PyObject_TypeCheck((PTR), (PyTypeObject *)PyExc_UnicodeError)
#define PyUnicodeErrorObject_CAST(op) \
(assert(PyUnicodeError_Check(op)), ((PyUnicodeErrorObject *)(op)))
/* Assert some properties of the adjusted 'end' value. */
#ifndef NDEBUG
static void
assert_adjusted_unicode_error_end(Py_ssize_t end, Py_ssize_t objlen)
{
assert(objlen >= 0);
/* in the future, `min_end` may be something else */
Py_ssize_t min_end = Py_MIN(1, objlen);
assert(end >= min_end);
/* in the future, `max_end` may be something else */
Py_ssize_t max_end = Py_MAX(min_end, objlen);
assert(end <= max_end);
}
#else
#define assert_adjusted_unicode_error_end(...)
#endif
/*
* Adjust the length of the range described by a UnicodeError object.
*
* The 'start' and 'end' arguments must have been obtained by
* unicode_error_adjust_start() and unicode_error_adjust_end().
*
* The result is clipped in [0, objlen]. By construction, it
* will always be smaller than 'objlen' as 'start' and 'end'
* are smaller than 'objlen'.
*/
static Py_ssize_t
unicode_error_adjust_len(Py_ssize_t start, Py_ssize_t end, Py_ssize_t objlen)
{
assert_adjusted_unicode_error_start(start, objlen);
assert_adjusted_unicode_error_end(end, objlen);
Py_ssize_t ranlen = end - start;
assert(ranlen <= objlen);
return ranlen < 0 ? 0 : ranlen;
}
/* Assert some properties of the adjusted range 'len' value. */
#ifndef NDEBUG
static void
assert_adjusted_unicode_error_len(Py_ssize_t ranlen, Py_ssize_t objlen)
{
assert(objlen >= 0);
assert(ranlen >= 0);
assert(ranlen <= objlen);
}
#else
#define assert_adjusted_unicode_error_len(...)
#endif
/*
* Get various common parameters of a UnicodeError object.
*
* The caller is responsible to ensure that 'self' is a PyUnicodeErrorObject,
* although this condition is verified by this function on DEBUG builds.
*
* Return 0 on success and -1 on failure.
*
* Output parameters:
*
* obj A strong reference to the 'object' attribute.
* objlen The 'object' length.
* start The clipped 'start' attribute.
* end The clipped 'end' attribute.
* slen The length of the slice described by the clipped 'start'
* and 'end' values. It always lies in [0, objlen].
*
* An output parameter can be NULL to indicate that
* the corresponding value does not need to be stored.
*
* Input parameter:
*
* as_bytes If true, the error's 'object' attribute must be a `bytes`,
* i.e. 'self' is a `UnicodeDecodeError` instance. Otherwise,
* the 'object' attribute must be a string.
*
* A TypeError is raised if the 'object' type is incompatible.
*/
int
_PyUnicodeError_GetParams(PyObject *self,
PyObject **obj, Py_ssize_t *objlen,
Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t *slen,
int as_bytes)
{
assert(self != NULL);
assert(as_bytes == 0 || as_bytes == 1);
PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self);
PyObject *r = as_unicode_error_attribute(exc->object, "object", as_bytes);
if (r == NULL) {
return -1;
}
Py_ssize_t n = as_bytes ? PyBytes_GET_SIZE(r) : PyUnicode_GET_LENGTH(r);
if (objlen != NULL) {
*objlen = n;
}
Py_ssize_t start_value = -1;
if (start != NULL || slen != NULL) {
start_value = unicode_error_adjust_start(exc->start, n);
}
if (start != NULL) {
assert_adjusted_unicode_error_start(start_value, n);
*start = start_value;
}
Py_ssize_t end_value = -1;
if (end != NULL || slen != NULL) {
end_value = unicode_error_adjust_end(exc->end, n);
}
if (end != NULL) {
assert_adjusted_unicode_error_end(end_value, n);
*end = end_value;
}
if (slen != NULL) {
*slen = unicode_error_adjust_len(start_value, end_value, n);
assert_adjusted_unicode_error_len(*slen, n);
}
if (obj != NULL) {
*obj = r;
}
else {
Py_DECREF(r);
}
return 0;
}
// --- PyUnicodeEncodeObject: 'encoding' getters ------------------------------
// Note: PyUnicodeTranslateError does not have an 'encoding' attribute.
PyObject *
PyUnicodeEncodeError_GetEncoding(PyObject *self)
{
int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME);
return rc < 0 ? NULL : unicode_error_get_encoding_impl(self);
}
PyObject *
PyUnicodeDecodeError_GetEncoding(PyObject *self)
{
int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME);
return rc < 0 ? NULL : unicode_error_get_encoding_impl(self);
}
// --- PyUnicodeEncodeObject: 'object' getters --------------------------------
PyObject *
PyUnicodeEncodeError_GetObject(PyObject *self)
{
int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME);
return rc < 0 ? NULL : unicode_error_get_object_impl(self, false);
}
PyObject *
PyUnicodeDecodeError_GetObject(PyObject *self)
{
int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME);
return rc < 0 ? NULL : unicode_error_get_object_impl(self, true);
}
PyObject *
PyUnicodeTranslateError_GetObject(PyObject *self)
{
int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME);
return rc < 0 ? NULL : unicode_error_get_object_impl(self, false);
}
// --- PyUnicodeEncodeObject: 'start' getters ---------------------------------
/*
* Specialization of _PyUnicodeError_GetParams() for the 'start' attribute.
*
* The caller is responsible to ensure that 'self' is a PyUnicodeErrorObject,
* although this condition is verified by this function on DEBUG builds.
*/
static inline int
unicode_error_get_start_impl(PyObject *self, Py_ssize_t *start, int as_bytes)
{
assert(self != NULL);
return _PyUnicodeError_GetParams(self, NULL, NULL,
start, NULL, NULL,
as_bytes);
}
int
PyUnicodeEncodeError_GetStart(PyObject *self, Py_ssize_t *start)
{
int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_get_start_impl(self, start, false);
}
int
PyUnicodeDecodeError_GetStart(PyObject *self, Py_ssize_t *start)
{
int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_get_start_impl(self, start, true);
}
int
PyUnicodeTranslateError_GetStart(PyObject *self, Py_ssize_t *start)
{
int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_get_start_impl(self, start, false);
}
// --- PyUnicodeEncodeObject: 'start' setters ---------------------------------
int
PyUnicodeEncodeError_SetStart(PyObject *self, Py_ssize_t start)
{
int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_set_start_impl(self, start);
}
int
PyUnicodeDecodeError_SetStart(PyObject *self, Py_ssize_t start)
{
int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_set_start_impl(self, start);
}
int
PyUnicodeTranslateError_SetStart(PyObject *self, Py_ssize_t start)
{
int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_set_start_impl(self, start);
}
// --- PyUnicodeEncodeObject: 'end' getters -----------------------------------
/*
* Specialization of _PyUnicodeError_GetParams() for the 'end' attribute.
*
* The caller is responsible to ensure that 'self' is a PyUnicodeErrorObject,
* although this condition is verified by this function on DEBUG builds.
*/
static inline int
unicode_error_get_end_impl(PyObject *self, Py_ssize_t *end, int as_bytes)
{
assert(self != NULL);
return _PyUnicodeError_GetParams(self, NULL, NULL,
NULL, end, NULL,
as_bytes);
}
int
PyUnicodeEncodeError_GetEnd(PyObject *self, Py_ssize_t *end)
{
int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_get_end_impl(self, end, false);
}
int
PyUnicodeDecodeError_GetEnd(PyObject *self, Py_ssize_t *end)
{
int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_get_end_impl(self, end, true);
}
int
PyUnicodeTranslateError_GetEnd(PyObject *self, Py_ssize_t *end)
{
int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_get_end_impl(self, end, false);
}
// --- PyUnicodeEncodeObject: 'end' setters -----------------------------------
int
PyUnicodeEncodeError_SetEnd(PyObject *self, Py_ssize_t end)
{
int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_set_end_impl(self, end);
}
int
PyUnicodeDecodeError_SetEnd(PyObject *self, Py_ssize_t end)
{
int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_set_end_impl(self, end);
}
int
PyUnicodeTranslateError_SetEnd(PyObject *self, Py_ssize_t end)
{
int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_set_end_impl(self, end);
}
// --- PyUnicodeEncodeObject: 'reason' getters --------------------------------
PyObject *
PyUnicodeEncodeError_GetReason(PyObject *self)
{
int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME);
return rc < 0 ? NULL : unicode_error_get_reason_impl(self);
}
PyObject *
PyUnicodeDecodeError_GetReason(PyObject *self)
{
int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME);
return rc < 0 ? NULL : unicode_error_get_reason_impl(self);
}
PyObject *
PyUnicodeTranslateError_GetReason(PyObject *self)
{
int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME);
return rc < 0 ? NULL : unicode_error_get_reason_impl(self);
}
// --- PyUnicodeEncodeObject: 'reason' setters --------------------------------
int
PyUnicodeEncodeError_SetReason(PyObject *self, const char *reason)
{
int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_set_reason_impl(self, reason);
}
int
PyUnicodeDecodeError_SetReason(PyObject *self, const char *reason)
{
int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_set_reason_impl(self, reason);
}
int
PyUnicodeTranslateError_SetReason(PyObject *self, const char *reason)
{
int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME);
return rc < 0 ? -1 : unicode_error_set_reason_impl(self, reason);
}
static int
UnicodeError_clear(PyObject *self)
{
PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self);
Py_CLEAR(exc->encoding);
Py_CLEAR(exc->object);
Py_CLEAR(exc->reason);
return BaseException_clear(self);
}
static void
UnicodeError_dealloc(PyObject *self)
{
PyTypeObject *type = Py_TYPE(self);
_PyObject_GC_UNTRACK(self);
(void)UnicodeError_clear(self);
type->tp_free(self);
}
static int
UnicodeError_traverse(PyObject *self, visitproc visit, void *arg)
{
PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self);
Py_VISIT(exc->encoding);
Py_VISIT(exc->object);
Py_VISIT(exc->reason);
return BaseException_traverse(self, visit, arg);
}
static PyMemberDef UnicodeError_members[] = {
{"encoding", _Py_T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
PyDoc_STR("exception encoding")},
{"object", _Py_T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
PyDoc_STR("exception object")},
{"start", Py_T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
PyDoc_STR("exception start")},
{"end", Py_T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
PyDoc_STR("exception end")},
{"reason", _Py_T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
PyDoc_STR("exception reason")},
{NULL} /* Sentinel */
};
/*
* UnicodeEncodeError extends UnicodeError
*/
static int
UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
{
if (BaseException_init(self, args, kwds) == -1) {
return -1;
}
PyObject *encoding = NULL, *object = NULL, *reason = NULL; // borrowed
Py_ssize_t start = -1, end = -1;
if (!PyArg_ParseTuple(args, "UUnnU",
&encoding, &object, &start, &end, &reason))
{
return -1;
}
PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self);
Py_XSETREF(exc->encoding, Py_NewRef(encoding));
Py_XSETREF(exc->object, Py_NewRef(object));
exc->start = start;
exc->end = end;
Py_XSETREF(exc->reason, Py_NewRef(reason));
return 0;
}
static PyObject *
UnicodeEncodeError_str(PyObject *self)
{
PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self);
PyObject *result = NULL;
PyObject *reason_str = NULL;
PyObject *encoding_str = NULL;
if (exc->object == NULL) {
/* Not properly initialized. */
return Py_GetConstant(Py_CONSTANT_EMPTY_STR);
}
/* Get reason and encoding as strings, which they might not be if
they've been modified after we were constructed. */
reason_str = PyObject_Str(exc->reason);
if (reason_str == NULL) {
goto done;
}
encoding_str = PyObject_Str(exc->encoding);
if (encoding_str == NULL) {
goto done;
}
// calls to PyObject_Str(...) above might mutate 'exc->object'
if (check_unicode_error_attribute(exc->object, "object", false) < 0) {
goto done;
}
Py_ssize_t len = PyUnicode_GET_LENGTH(exc->object);
Py_ssize_t start = exc->start, end = exc->end;
if ((start >= 0 && start < len) && (end >= 0 && end <= len) && end == start + 1) {
Py_UCS4 badchar = PyUnicode_ReadChar(exc->object, start);
const char *fmt;
if (badchar <= 0xff) {
fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
}
else if (badchar <= 0xffff) {
fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
}
else {
fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
}
result = PyUnicode_FromFormat(
fmt,
encoding_str,
(int)badchar,
start,
reason_str);
}
else {
result = PyUnicode_FromFormat(
"'%U' codec can't encode characters in position %zd-%zd: %U",
encoding_str,
start,
end - 1,
reason_str);
}
done:
Py_XDECREF(reason_str);
Py_XDECREF(encoding_str);
return result;
}
static PyTypeObject _PyExc_UnicodeEncodeError = {
PyVarObject_HEAD_INIT(NULL, 0)
"UnicodeEncodeError",
sizeof(PyUnicodeErrorObject), 0,
UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
UnicodeEncodeError_str, 0, 0, 0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
PyDoc_STR("Unicode encoding error."), UnicodeError_traverse,
UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
UnicodeEncodeError_init, 0, BaseException_new,
};
PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
/*
* UnicodeDecodeError extends UnicodeError
*/
static int
UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
{
if (BaseException_init(self, args, kwds) == -1) {
return -1;
}
PyObject *encoding = NULL, *object = NULL, *reason = NULL; // borrowed
Py_ssize_t start = -1, end = -1;
if (!PyArg_ParseTuple(args, "UOnnU",
&encoding, &object, &start, &end, &reason))
{
return -1;
}
if (PyBytes_Check(object)) {
Py_INCREF(object); // make 'object' a strong reference
}
else {
Py_buffer view;
if (PyObject_GetBuffer(object, &view, PyBUF_SIMPLE) != 0) {
return -1;
}
// 'object' is borrowed, so we can re-use the variable
object = PyBytes_FromStringAndSize(view.buf, view.len);
PyBuffer_Release(&view);
if (object == NULL) {
return -1;
}
}
PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self);
Py_XSETREF(exc->encoding, Py_NewRef(encoding));
Py_XSETREF(exc->object, object /* already a strong reference */);
exc->start = start;
exc->end = end;
Py_XSETREF(exc->reason, Py_NewRef(reason));
return 0;
}
static PyObject *
UnicodeDecodeError_str(PyObject *self)
{
PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self);
PyObject *result = NULL;
PyObject *reason_str = NULL;
PyObject *encoding_str = NULL;
if (exc->object == NULL) {
/* Not properly initialized. */
return Py_GetConstant(Py_CONSTANT_EMPTY_STR);
}
/* Get reason and encoding as strings, which they might not be if
they've been modified after we were constructed. */
reason_str = PyObject_Str(exc->reason);
if (reason_str == NULL) {
goto done;
}
encoding_str = PyObject_Str(exc->encoding);
if (encoding_str == NULL) {
goto done;
}
// calls to PyObject_Str(...) above might mutate 'exc->object'
if (check_unicode_error_attribute(exc->object, "object", true) < 0) {
goto done;
}
Py_ssize_t len = PyBytes_GET_SIZE(exc->object);
Py_ssize_t start = exc->start, end = exc->end;
if ((start >= 0 && start < len) && (end >= 0 && end <= len) && end == start + 1) {
int badbyte = (int)(PyBytes_AS_STRING(exc->object)[start] & 0xff);
result = PyUnicode_FromFormat(
"'%U' codec can't decode byte 0x%02x in position %zd: %U",
encoding_str,
badbyte,
start,
reason_str);
}
else {
result = PyUnicode_FromFormat(
"'%U' codec can't decode bytes in position %zd-%zd: %U",
encoding_str,
start,
end - 1,
reason_str);
}
done:
Py_XDECREF(reason_str);
Py_XDECREF(encoding_str);
return result;
}
static PyTypeObject _PyExc_UnicodeDecodeError = {
PyVarObject_HEAD_INIT(NULL, 0)
"UnicodeDecodeError",
sizeof(PyUnicodeErrorObject), 0,
UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
UnicodeDecodeError_str, 0, 0, 0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
PyDoc_STR("Unicode decoding error."), UnicodeError_traverse,
UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
UnicodeDecodeError_init, 0, BaseException_new,
};
PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
PyObject *
PyUnicodeDecodeError_Create(
const char *encoding, const char *object, Py_ssize_t length,
Py_ssize_t start, Py_ssize_t end, const char *reason)
{
return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
encoding, object, length, start, end, reason);
}
/*
* UnicodeTranslateError extends UnicodeError
*/
static int
UnicodeTranslateError_init(PyObject *self, PyObject *args, PyObject *kwds)
{
if (BaseException_init(self, args, kwds) == -1) {
return -1;
}
PyObject *object = NULL, *reason = NULL; // borrowed
Py_ssize_t start = -1, end = -1;
if (!PyArg_ParseTuple(args, "UnnU", &object, &start, &end, &reason)) {
return -1;
}
PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self);
Py_XSETREF(exc->object, Py_NewRef(object));
exc->start = start;
exc->end = end;
Py_XSETREF(exc->reason, Py_NewRef(reason));
return 0;
}
static PyObject *
UnicodeTranslateError_str(PyObject *self)
{
PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self);
PyObject *result = NULL;
PyObject *reason_str = NULL;
if (exc->object == NULL) {
/* Not properly initialized. */
return Py_GetConstant(Py_CONSTANT_EMPTY_STR);
}
/* Get reason as a string, which it might not be if it's been
modified after we were constructed. */
reason_str = PyObject_Str(exc->reason);
if (reason_str == NULL) {
goto done;
}
// call to PyObject_Str(...) above might mutate 'exc->object'
if (check_unicode_error_attribute(exc->object, "object", false) < 0) {
goto done;
}
Py_ssize_t len = PyUnicode_GET_LENGTH(exc->object);
Py_ssize_t start = exc->start, end = exc->end;
if ((start >= 0 && start < len) && (end >= 0 && end <= len) && end == start + 1) {
Py_UCS4 badchar = PyUnicode_ReadChar(exc->object, start);
const char *fmt;
if (badchar <= 0xff) {
fmt = "can't translate character '\\x%02x' in position %zd: %U";
}
else if (badchar <= 0xffff) {
fmt = "can't translate character '\\u%04x' in position %zd: %U";
}
else {
fmt = "can't translate character '\\U%08x' in position %zd: %U";
}
result = PyUnicode_FromFormat(
fmt,
(int)badchar,
start,
reason_str);
}
else {
result = PyUnicode_FromFormat(
"can't translate characters in position %zd-%zd: %U",
start,
end - 1,
reason_str);
}
done:
Py_XDECREF(reason_str);
return result;
}
static PyTypeObject _PyExc_UnicodeTranslateError = {
PyVarObject_HEAD_INIT(NULL, 0)
"UnicodeTranslateError",
sizeof(PyUnicodeErrorObject), 0,
UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
UnicodeTranslateError_str, 0, 0, 0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
PyDoc_STR("Unicode translation error."), UnicodeError_traverse,
UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
UnicodeTranslateError_init, 0, BaseException_new,
};
PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
PyObject *
_PyUnicodeTranslateError_Create(
PyObject *object,
Py_ssize_t start, Py_ssize_t end, const char *reason)
{
return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
object, start, end, reason);
}
/*
* AssertionError extends Exception
*/
SimpleExtendsException(PyExc_Exception, AssertionError,
"Assertion failed.");
/*
* ArithmeticError extends Exception
*/
SimpleExtendsException(PyExc_Exception, ArithmeticError,
"Base class for arithmetic errors.");
/*
* FloatingPointError extends ArithmeticError
*/
SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
"Floating-point operation failed.");
/*
* OverflowError extends ArithmeticError
*/
SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
"Result too large to be represented.");
/*
* ZeroDivisionError extends ArithmeticError
*/
SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
"Second argument to a division or modulo operation was zero.");
/*
* SystemError extends Exception
*/
SimpleExtendsException(PyExc_Exception, SystemError,
"Internal error in the Python interpreter.\n"
"\n"
"Please report this to the Python maintainer, along with the traceback,\n"
"the Python version, and the hardware/OS platform and version.");
/*
* ReferenceError extends Exception
*/
SimpleExtendsException(PyExc_Exception, ReferenceError,
"Weak ref proxy used after referent went away.");
/*
* MemoryError extends Exception
*/
#define MEMERRORS_SAVE 16
#ifdef Py_GIL_DISABLED
# define MEMERRORS_LOCK(state) PyMutex_LockFlags(&state->memerrors_lock, _Py_LOCK_DONT_DETACH)
# define MEMERRORS_UNLOCK(state) PyMutex_Unlock(&state->memerrors_lock)
#else
# define MEMERRORS_LOCK(state) ((void)0)
# define MEMERRORS_UNLOCK(state) ((void)0)
#endif
static PyObject *
get_memory_error(int allow_allocation, PyObject *args, PyObject *kwds)
{
PyBaseExceptionObject *self = NULL;
struct _Py_exc_state *state = get_exc_state();
MEMERRORS_LOCK(state);
if (state->memerrors_freelist != NULL) {
/* Fetch MemoryError from freelist and initialize it */
self = state->memerrors_freelist;
state->memerrors_freelist = (PyBaseExceptionObject *) self->dict;
state->memerrors_numfree--;
self->dict = NULL;
self->args = (PyObject *)&_Py_SINGLETON(tuple_empty);
_Py_NewReference((PyObject *)self);
_PyObject_GC_TRACK(self);
}
MEMERRORS_UNLOCK(state);
if (self != NULL) {
return (PyObject *)self;
}
if (!allow_allocation) {
PyInterpreterState *interp = _PyInterpreterState_GET();
return Py_NewRef(
&_Py_INTERP_SINGLETON(interp, last_resort_memory_error));
}
return BaseException_new((PyTypeObject *)PyExc_MemoryError, args, kwds);
}
static PyObject *
MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
/* If this is a subclass of MemoryError, don't use the freelist
* and just return a fresh object */
if (type != (PyTypeObject *) PyExc_MemoryError) {
return BaseException_new(type, args, kwds);
}
return get_memory_error(1, args, kwds);
}
PyObject *
_PyErr_NoMemory(PyThreadState *tstate)
{
if (Py_IS_TYPE(PyExc_MemoryError, NULL)) {
/* PyErr_NoMemory() has been called before PyExc_MemoryError has been
initialized by _PyExc_Init() */
Py_FatalError("Out of memory and PyExc_MemoryError is not "
"initialized yet");
}
PyObject *err = get_memory_error(0, NULL, NULL);
if (err != NULL) {
_PyErr_SetRaisedException(tstate, err);
}
return NULL;
}
static void
MemoryError_dealloc(PyObject *op)
{
PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op);
_PyObject_GC_UNTRACK(self);
(void)BaseException_clear(op);
/* If this is a subclass of MemoryError, we don't need to
* do anything in the free-list*/
if (!Py_IS_TYPE(self, (PyTypeObject *) PyExc_MemoryError)) {
Py_TYPE(self)->tp_free(op);
return;
}
struct _Py_exc_state *state = get_exc_state();
MEMERRORS_LOCK(state);
if (state->memerrors_numfree < MEMERRORS_SAVE) {
self->dict = (PyObject *) state->memerrors_freelist;
state->memerrors_freelist = self;
state->memerrors_numfree++;
MEMERRORS_UNLOCK(state);
return;
}
MEMERRORS_UNLOCK(state);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static int
preallocate_memerrors(void)
{
/* We create enough MemoryErrors and then decref them, which will fill
up the freelist. */
int i;
PyObject *errors[MEMERRORS_SAVE];
for (i = 0; i < MEMERRORS_SAVE; i++) {
errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
NULL, NULL);
if (!errors[i]) {
return -1;
}
}
for (i = 0; i < MEMERRORS_SAVE; i++) {
Py_DECREF(errors[i]);
}
return 0;
}
static void
free_preallocated_memerrors(struct _Py_exc_state *state)
{
while (state->memerrors_freelist != NULL) {
PyObject *self = (PyObject *) state->memerrors_freelist;
state->memerrors_freelist = (PyBaseExceptionObject *)state->memerrors_freelist->dict;
Py_TYPE(self)->tp_free(self);
}
}
PyTypeObject _PyExc_MemoryError = {
PyVarObject_HEAD_INIT(NULL, 0)
"MemoryError",
sizeof(PyBaseExceptionObject),
0, MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
PyDoc_STR("Out of memory."), BaseException_traverse,
BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
0, 0, 0, offsetof(PyBaseExceptionObject, dict),
BaseException_init, 0, MemoryError_new
};
PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
/*
* BufferError extends Exception
*/
SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
/* Warning category docstrings */
/*
* Warning extends Exception
*/
SimpleExtendsException(PyExc_Exception, Warning,
"Base class for warning categories.");
/*
* UserWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, UserWarning,
"Base class for warnings generated by user code.");
/*
* DeprecationWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, DeprecationWarning,
"Base class for warnings about deprecated features.");
/*
* PendingDeprecationWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
"Base class for warnings about features which will be deprecated\n"
"in the future.");
/*
* SyntaxWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, SyntaxWarning,
"Base class for warnings about dubious syntax.");
/*
* RuntimeWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, RuntimeWarning,
"Base class for warnings about dubious runtime behavior.");
/*
* FutureWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, FutureWarning,
"Base class for warnings about constructs that will change semantically\n"
"in the future.");
/*
* ImportWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, ImportWarning,
"Base class for warnings about probable mistakes in module imports");
/*
* UnicodeWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, UnicodeWarning,
"Base class for warnings about Unicode related problems, mostly\n"
"related to conversion problems.");
/*
* BytesWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, BytesWarning,
"Base class for warnings about bytes and buffer related problems, mostly\n"
"related to conversion from str or comparing to str.");
/*
* EncodingWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, EncodingWarning,
"Base class for warnings about encodings.");
/*
* ResourceWarning extends Warning
*/
SimpleExtendsException(PyExc_Warning, ResourceWarning,
"Base class for warnings about resource usage.");
#ifdef MS_WINDOWS
#include <winsock2.h>
/* The following constants were added to errno.h in VS2010 but have
preferred WSA equivalents. */
#undef EADDRINUSE
#undef EADDRNOTAVAIL
#undef EAFNOSUPPORT
#undef EALREADY
#undef ECONNABORTED
#undef ECONNREFUSED
#undef ECONNRESET
#undef EDESTADDRREQ
#undef EHOSTUNREACH
#undef EINPROGRESS
#undef EISCONN
#undef ELOOP
#undef EMSGSIZE
#undef ENETDOWN
#undef ENETRESET
#undef ENETUNREACH
#undef ENOBUFS
#undef ENOPROTOOPT
#undef ENOTCONN
#undef ENOTSOCK
#undef EOPNOTSUPP
#undef EPROTONOSUPPORT
#undef EPROTOTYPE
#undef EWOULDBLOCK
#if defined(WSAEALREADY) && !defined(EALREADY)
#define EALREADY WSAEALREADY
#endif
#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
#define ECONNABORTED WSAECONNABORTED
#endif
#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
#define ECONNREFUSED WSAECONNREFUSED
#endif
#if defined(WSAECONNRESET) && !defined(ECONNRESET)
#define ECONNRESET WSAECONNRESET
#endif
#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
#define EINPROGRESS WSAEINPROGRESS
#endif
#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
#define ESHUTDOWN WSAESHUTDOWN
#endif
#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
#define EWOULDBLOCK WSAEWOULDBLOCK
#endif
#endif /* MS_WINDOWS */
struct static_exception {
PyTypeObject *exc;
const char *name;
};
static struct static_exception static_exceptions[] = {
#define ITEM(NAME) {&_PyExc_##NAME, #NAME}
// Level 1
ITEM(BaseException),
// Level 2: BaseException subclasses
ITEM(BaseExceptionGroup),
ITEM(Exception),
ITEM(GeneratorExit),
ITEM(KeyboardInterrupt),
ITEM(SystemExit),
// Level 3: Exception(BaseException) subclasses
ITEM(ArithmeticError),
ITEM(AssertionError),
ITEM(AttributeError),
ITEM(BufferError),
ITEM(EOFError),
//ITEM(ExceptionGroup),
ITEM(ImportError),
ITEM(LookupError),
ITEM(MemoryError),
ITEM(NameError),
ITEM(OSError),
ITEM(ReferenceError),
ITEM(RuntimeError),
ITEM(StopAsyncIteration),
ITEM(StopIteration),
ITEM(SyntaxError),
ITEM(SystemError),
ITEM(TypeError),
ITEM(ValueError),
ITEM(Warning),
// Level 4: ArithmeticError(Exception) subclasses
ITEM(FloatingPointError),
ITEM(OverflowError),
ITEM(ZeroDivisionError),
// Level 4: Warning(Exception) subclasses
ITEM(BytesWarning),
ITEM(DeprecationWarning),
ITEM(EncodingWarning),
ITEM(FutureWarning),
ITEM(ImportWarning),
ITEM(PendingDeprecationWarning),
ITEM(ResourceWarning),
ITEM(RuntimeWarning),
ITEM(SyntaxWarning),
ITEM(UnicodeWarning),
ITEM(UserWarning),
// Level 4: OSError(Exception) subclasses
ITEM(BlockingIOError),
ITEM(ChildProcessError),
ITEM(ConnectionError),
ITEM(FileExistsError),
ITEM(FileNotFoundError),
ITEM(InterruptedError),
ITEM(IsADirectoryError),
ITEM(NotADirectoryError),
ITEM(PermissionError),
ITEM(ProcessLookupError),
ITEM(TimeoutError),
// Level 4: Other subclasses
ITEM(IndentationError), // base: SyntaxError(Exception)
{&_PyExc_IncompleteInputError, "_IncompleteInputError"}, // base: SyntaxError(Exception)
ITEM(IndexError), // base: LookupError(Exception)
ITEM(KeyError), // base: LookupError(Exception)
ITEM(ModuleNotFoundError), // base: ImportError(Exception)
ITEM(NotImplementedError), // base: RuntimeError(Exception)
ITEM(PythonFinalizationError), // base: RuntimeError(Exception)
ITEM(RecursionError), // base: RuntimeError(Exception)
ITEM(UnboundLocalError), // base: NameError(Exception)
ITEM(UnicodeError), // base: ValueError(Exception)
// Level 5: ConnectionError(OSError) subclasses
ITEM(BrokenPipeError),
ITEM(ConnectionAbortedError),
ITEM(ConnectionRefusedError),
ITEM(ConnectionResetError),
// Level 5: IndentationError(SyntaxError) subclasses
ITEM(TabError), // base: IndentationError
// Level 5: UnicodeError(ValueError) subclasses
ITEM(UnicodeDecodeError),
ITEM(UnicodeEncodeError),
ITEM(UnicodeTranslateError),
#undef ITEM
};
int
_PyExc_InitTypes(PyInterpreterState *interp)
{
for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) {
PyTypeObject *exc = static_exceptions[i].exc;
if (_PyStaticType_InitBuiltin(interp, exc) < 0) {
return -1;
}
if (exc->tp_new == BaseException_new
&& exc->tp_init == BaseException_init)
{
exc->tp_vectorcall = BaseException_vectorcall;
}
}
return 0;
}
static void
_PyExc_FiniTypes(PyInterpreterState *interp)
{
for (Py_ssize_t i=Py_ARRAY_LENGTH(static_exceptions) - 1; i >= 0; i--) {
PyTypeObject *exc = static_exceptions[i].exc;
_PyStaticType_FiniBuiltin(interp, exc);
}
}
PyStatus
_PyExc_InitGlobalObjects(PyInterpreterState *interp)
{
if (preallocate_memerrors() < 0) {
return _PyStatus_NO_MEMORY();
}
return _PyStatus_OK();
}
PyStatus
_PyExc_InitState(PyInterpreterState *interp)
{
struct _Py_exc_state *state = &interp->exc_state;
#define ADD_ERRNO(TYPE, CODE) \
do { \
PyObject *_code = PyLong_FromLong(CODE); \
assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
if (!_code || PyDict_SetItem(state->errnomap, _code, PyExc_ ## TYPE)) { \
Py_XDECREF(_code); \
return _PyStatus_ERR("errmap insertion problem."); \
} \
Py_DECREF(_code); \
} while (0)
/* Add exceptions to errnomap */
assert(state->errnomap == NULL);
state->errnomap = PyDict_New();
if (!state->errnomap) {
return _PyStatus_NO_MEMORY();
}
ADD_ERRNO(BlockingIOError, EAGAIN);
ADD_ERRNO(BlockingIOError, EALREADY);
ADD_ERRNO(BlockingIOError, EINPROGRESS);
ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
ADD_ERRNO(BrokenPipeError, EPIPE);
#ifdef ESHUTDOWN
ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
#endif
ADD_ERRNO(ChildProcessError, ECHILD);
ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
ADD_ERRNO(ConnectionResetError, ECONNRESET);
ADD_ERRNO(FileExistsError, EEXIST);
ADD_ERRNO(FileNotFoundError, ENOENT);
ADD_ERRNO(IsADirectoryError, EISDIR);
ADD_ERRNO(NotADirectoryError, ENOTDIR);
ADD_ERRNO(InterruptedError, EINTR);
ADD_ERRNO(PermissionError, EACCES);
ADD_ERRNO(PermissionError, EPERM);
#ifdef ENOTCAPABLE
// Extension for WASI capability-based security. Process lacks
// capability to access a resource.
ADD_ERRNO(PermissionError, ENOTCAPABLE);
#endif
ADD_ERRNO(ProcessLookupError, ESRCH);
ADD_ERRNO(TimeoutError, ETIMEDOUT);
#ifdef WSAETIMEDOUT
ADD_ERRNO(TimeoutError, WSAETIMEDOUT);
#endif
return _PyStatus_OK();
#undef ADD_ERRNO
}
/* Add exception types to the builtins module */
int
_PyBuiltins_AddExceptions(PyObject *bltinmod)
{
PyObject *mod_dict = PyModule_GetDict(bltinmod);
if (mod_dict == NULL) {
return -1;
}
for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) {
struct static_exception item = static_exceptions[i];
if (PyDict_SetItemString(mod_dict, item.name, (PyObject*)item.exc)) {
return -1;
}
}
PyObject *PyExc_ExceptionGroup = create_exception_group_class();
if (!PyExc_ExceptionGroup) {
return -1;
}
if (PyDict_SetItemString(mod_dict, "ExceptionGroup", PyExc_ExceptionGroup)) {
return -1;
}
if (PyDict_SetItemString(mod_dict, "EnvironmentError", PyExc_OSError)) {
return -1;
}
if (PyDict_SetItemString(mod_dict, "IOError", PyExc_OSError)) {
return -1;
}
#ifdef MS_WINDOWS
if (PyDict_SetItemString(mod_dict, "WindowsError", PyExc_OSError)) {
return -1;
}
#endif
return 0;
}
void
_PyExc_ClearExceptionGroupType(PyInterpreterState *interp)
{
struct _Py_exc_state *state = &interp->exc_state;
Py_CLEAR(state->PyExc_ExceptionGroup);
}
void
_PyExc_Fini(PyInterpreterState *interp)
{
struct _Py_exc_state *state = &interp->exc_state;
free_preallocated_memerrors(state);
Py_CLEAR(state->errnomap);
_PyExc_FiniTypes(interp);
}
int
_PyException_AddNote(PyObject *exc, PyObject *note)
{
if (!PyExceptionInstance_Check(exc)) {
PyErr_Format(PyExc_TypeError,
"exc must be an exception, not '%s'",
Py_TYPE(exc)->tp_name);
return -1;
}
PyObject *r = BaseException_add_note(exc, note);
int res = r == NULL ? -1 : 0;
Py_XDECREF(r);
return res;
}
/* Boolean type, a subtype of int */
#include "Python.h"
#include "pycore_long.h" // FALSE_TAG TRUE_TAG
#include "pycore_modsupport.h" // _PyArg_NoKwnames()
#include "pycore_object.h" // _Py_FatalRefcountError()
#include "pycore_runtime.h" // _Py_ID()
#include <stddef.h>
/* We define bool_repr to return "False" or "True" */
static PyObject *
bool_repr(PyObject *self)
{
return self == Py_True ? &_Py_ID(True) : &_Py_ID(False);
}
/* Function to return a bool from a C long */
PyObject *PyBool_FromLong(long ok)
{
return ok ? Py_True : Py_False;
}
/* We define bool_new to always return either Py_True or Py_False */
static PyObject *
bool_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *x = Py_False;
long ok;
if (!_PyArg_NoKeywords("bool", kwds))
return NULL;
if (!PyArg_UnpackTuple(args, "bool", 0, 1, &x))
return NULL;
ok = PyObject_IsTrue(x);
if (ok < 0)
return NULL;
return PyBool_FromLong(ok);
}
static PyObject *
bool_vectorcall(PyObject *type, PyObject * const*args,
size_t nargsf, PyObject *kwnames)
{
long ok = 0;
if (!_PyArg_NoKwnames("bool", kwnames)) {
return NULL;
}
Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
if (!_PyArg_CheckPositional("bool", nargs, 0, 1)) {
return NULL;
}
assert(PyType_Check(type));
if (nargs) {
ok = PyObject_IsTrue(args[0]);
if (ok < 0) {
return NULL;
}
}
return PyBool_FromLong(ok);
}
/* Arithmetic operations redefined to return bool if both args are bool. */
static PyObject *
bool_invert(PyObject *v)
{
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"Bitwise inversion '~' on bool is deprecated and will be removed in "
"Python 3.16. This returns the bitwise inversion of the underlying int "
"object and is usually not what you expect from negating "
"a bool. Use the 'not' operator for boolean negation or "
"~int(x) if you really want the bitwise inversion of the "
"underlying int.",
1) < 0) {
return NULL;
}
return PyLong_Type.tp_as_number->nb_invert(v);
}
static PyObject *
bool_and(PyObject *a, PyObject *b)
{
if (!PyBool_Check(a) || !PyBool_Check(b))
return PyLong_Type.tp_as_number->nb_and(a, b);
return PyBool_FromLong((a == Py_True) & (b == Py_True));
}
static PyObject *
bool_or(PyObject *a, PyObject *b)
{
if (!PyBool_Check(a) || !PyBool_Check(b))
return PyLong_Type.tp_as_number->nb_or(a, b);
return PyBool_FromLong((a == Py_True) | (b == Py_True));
}
static PyObject *
bool_xor(PyObject *a, PyObject *b)
{
if (!PyBool_Check(a) || !PyBool_Check(b))
return PyLong_Type.tp_as_number->nb_xor(a, b);
return PyBool_FromLong((a == Py_True) ^ (b == Py_True));
}
/* Doc string */
PyDoc_STRVAR(bool_doc,
"bool(object=False, /)\n\
--\n\
\n\
Returns True when the argument is true, False otherwise.\n\
The builtins True and False are the only two instances of the class bool.\n\
The class bool is a subclass of the class int, and cannot be subclassed.");
/* Arithmetic methods -- only so we can override &, |, ^. */
static PyNumberMethods bool_as_number = {
0, /* nb_add */
0, /* nb_subtract */
0, /* nb_multiply */
0, /* nb_remainder */
0, /* nb_divmod */
0, /* nb_power */
0, /* nb_negative */
0, /* nb_positive */
0, /* nb_absolute */
0, /* nb_bool */
bool_invert, /* nb_invert */
0, /* nb_lshift */
0, /* nb_rshift */
bool_and, /* nb_and */
bool_xor, /* nb_xor */
bool_or, /* nb_or */
0, /* nb_int */
0, /* nb_reserved */
0, /* nb_float */
0, /* nb_inplace_add */
0, /* nb_inplace_subtract */
0, /* nb_inplace_multiply */
0, /* nb_inplace_remainder */
0, /* nb_inplace_power */
0, /* nb_inplace_lshift */
0, /* nb_inplace_rshift */
0, /* nb_inplace_and */
0, /* nb_inplace_xor */
0, /* nb_inplace_or */
0, /* nb_floor_divide */
0, /* nb_true_divide */
0, /* nb_inplace_floor_divide */
0, /* nb_inplace_true_divide */
0, /* nb_index */
};
static void
bool_dealloc(PyObject *boolean)
{
/* This should never get called, but we also don't want to SEGV if
* we accidentally decref Booleans out of existence. Instead,
* since bools are immortal, re-set the reference count.
*/
_Py_SetImmortal(boolean);
}
/* The type object for bool. Note that this cannot be subclassed! */
PyTypeObject PyBool_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"bool",
offsetof(struct _longobject, long_value.ob_digit), /* tp_basicsize */
sizeof(digit), /* tp_itemsize */
bool_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
bool_repr, /* tp_repr */
&bool_as_number, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
bool_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&PyLong_Type, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
bool_new, /* tp_new */
.tp_vectorcall = bool_vectorcall,
};
/* The objects representing bool values False and True */
struct _longobject _Py_FalseStruct = {
PyObject_HEAD_INIT(&PyBool_Type)
{ .lv_tag = _PyLong_FALSE_TAG,
{ 0 }
}
};
struct _longobject _Py_TrueStruct = {
PyObject_HEAD_INIT(&PyBool_Type)
{ .lv_tag = _PyLong_TRUE_TAG,
{ 1 }
}
};
/* File object implementation (what's left of it -- see io.py) */
#include "Python.h"
#include "pycore_call.h" // _PyObject_CallNoArgs()
#include "pycore_runtime.h" // _PyRuntime
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8String()
#ifdef HAVE_UNISTD_H
# include <unistd.h> // isatty()
#endif
#if defined(HAVE_GETC_UNLOCKED) && !defined(_Py_MEMORY_SANITIZER)
/* clang MemorySanitizer doesn't yet understand getc_unlocked. */
# define GETC(f) getc_unlocked(f)
# define FLOCKFILE(f) flockfile(f)
# define FUNLOCKFILE(f) funlockfile(f)
#else
# define GETC(f) getc(f)
# define FLOCKFILE(f)
# define FUNLOCKFILE(f)
#endif
/* Newline flags */
#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
#define NEWLINE_CR 1 /* \r newline seen */
#define NEWLINE_LF 2 /* \n newline seen */
#define NEWLINE_CRLF 4 /* \r\n newline seen */
/* External C interface */
PyObject *
PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding,
const char *errors, const char *newline, int closefd)
{
PyObject *open, *stream;
/* import _io in case we are being used to open io.py */
open = PyImport_ImportModuleAttrString("_io", "open");
if (open == NULL)
return NULL;
stream = PyObject_CallFunction(open, "isisssO", fd, mode,
buffering, encoding, errors,
newline, closefd ? Py_True : Py_False);
Py_DECREF(open);
if (stream == NULL)
return NULL;
/* ignore name attribute because the name attribute of _BufferedIOMixin
and TextIOWrapper is read only */
return stream;
}
PyObject *
PyFile_GetLine(PyObject *f, int n)
{
PyObject *result;
if (f == NULL) {
PyErr_BadInternalCall();
return NULL;
}
if (n <= 0) {
result = PyObject_CallMethodNoArgs(f, &_Py_ID(readline));
}
else {
result = _PyObject_CallMethod(f, &_Py_ID(readline), "i", n);
}
if (result != NULL && !PyBytes_Check(result) &&
!PyUnicode_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%T.readline() must return a str, not %T", f, result);
Py_SETREF(result, NULL);
}
if (n < 0 && result != NULL && PyBytes_Check(result)) {
const char *s = PyBytes_AS_STRING(result);
Py_ssize_t len = PyBytes_GET_SIZE(result);
if (len == 0) {
Py_SETREF(result, NULL);
PyErr_SetString(PyExc_EOFError,
"EOF when reading a line");
}
else if (s[len-1] == '\n') {
(void) _PyBytes_Resize(&result, len-1);
}
}
if (n < 0 && result != NULL && PyUnicode_Check(result)) {
Py_ssize_t len = PyUnicode_GET_LENGTH(result);
if (len == 0) {
Py_SETREF(result, NULL);
PyErr_SetString(PyExc_EOFError,
"EOF when reading a line");
}
else if (PyUnicode_READ_CHAR(result, len-1) == '\n') {
PyObject *v;
v = PyUnicode_Substring(result, 0, len-1);
Py_SETREF(result, v);
}
}
return result;
}
/* Interfaces to write objects/strings to file-like objects */
int
PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
{
PyObject *writer, *value, *result;
if (f == NULL) {
PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
return -1;
}
writer = PyObject_GetAttr(f, &_Py_ID(write));
if (writer == NULL)
return -1;
if (flags & Py_PRINT_RAW) {
value = PyObject_Str(v);
}
else
value = PyObject_Repr(v);
if (value == NULL) {
Py_DECREF(writer);
return -1;
}
result = PyObject_CallOneArg(writer, value);
Py_DECREF(value);
Py_DECREF(writer);
if (result == NULL)
return -1;
Py_DECREF(result);
return 0;
}
int
PyFile_WriteString(const char *s, PyObject *f)
{
if (f == NULL) {
/* Should be caused by a pre-existing error */
if (!PyErr_Occurred())
PyErr_SetString(PyExc_SystemError,
"null file for PyFile_WriteString");
return -1;
}
else if (!PyErr_Occurred()) {
PyObject *v = PyUnicode_FromString(s);
int err;
if (v == NULL)
return -1;
err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
Py_DECREF(v);
return err;
}
else
return -1;
}
/* Try to get a file-descriptor from a Python object. If the object
is an integer, its value is returned. If not, the
object's fileno() method is called if it exists; the method must return
an integer, which is returned as the file descriptor value.
-1 is returned on failure.
*/
int
PyObject_AsFileDescriptor(PyObject *o)
{
int fd;
PyObject *meth;
if (PyLong_Check(o)) {
if (PyBool_Check(o)) {
if (PyErr_WarnEx(PyExc_RuntimeWarning,
"bool is used as a file descriptor", 1))
{
return -1;
}
}
fd = PyLong_AsInt(o);
}
else if (PyObject_GetOptionalAttr(o, &_Py_ID(fileno), &meth) < 0) {
return -1;
}
else if (meth != NULL) {
PyObject *fno = _PyObject_CallNoArgs(meth);
Py_DECREF(meth);
if (fno == NULL)
return -1;
if (PyLong_Check(fno)) {
fd = PyLong_AsInt(fno);
Py_DECREF(fno);
}
else {
PyErr_Format(PyExc_TypeError,
"%T.fileno() must return an int, not %T", o, fno);
Py_DECREF(fno);
return -1;
}
}
else {
PyErr_SetString(PyExc_TypeError,
"argument must be an int, or have a fileno() method.");
return -1;
}
if (fd == -1 && PyErr_Occurred())
return -1;
if (fd < 0) {
PyErr_Format(PyExc_ValueError,
"file descriptor cannot be a negative integer (%i)",
fd);
return -1;
}
return fd;
}
int
_PyLong_FileDescriptor_Converter(PyObject *o, void *ptr)
{
int fd = PyObject_AsFileDescriptor(o);
if (fd == -1) {
return 0;
}
*(int *)ptr = fd;
return 1;
}
char *
_Py_UniversalNewlineFgetsWithSize(char *buf, int n, FILE *stream, PyObject *fobj, size_t* size)
{
char *p = buf;
int c;
if (fobj) {
errno = ENXIO; /* What can you do... */
return NULL;
}
FLOCKFILE(stream);
while (--n > 0 && (c = GETC(stream)) != EOF ) {
if (c == '\r') {
// A \r is translated into a \n, and we skip an adjacent \n, if any.
c = GETC(stream);
if (c != '\n') {
ungetc(c, stream);
c = '\n';
}
}
*p++ = c;
if (c == '\n') {
break;
}
}
FUNLOCKFILE(stream);
*p = '\0';
if (p == buf) {
return NULL;
}
*size = p - buf;
return buf;
}
/*
** Py_UniversalNewlineFgets is an fgets variation that understands
** all of \r, \n and \r\n conventions.
** The stream should be opened in binary mode.
** The fobj parameter exists solely for legacy reasons and must be NULL.
** Note that we need no error handling: fgets() treats error and eof
** identically.
*/
char *
Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) {
size_t size;
return _Py_UniversalNewlineFgetsWithSize(buf, n, stream, fobj, &size);
}
/* **************************** std printer ****************************
* The stdprinter is used during the boot strapping phase as a preliminary
* file like object for sys.stderr.
*/
typedef struct {
PyObject_HEAD
int fd;
} PyStdPrinter_Object;
PyObject *
PyFile_NewStdPrinter(int fd)
{
PyStdPrinter_Object *self;
if (fd != fileno(stdout) && fd != fileno(stderr)) {
/* not enough infrastructure for PyErr_BadInternalCall() */
return NULL;
}
self = PyObject_New(PyStdPrinter_Object,
&PyStdPrinter_Type);
if (self != NULL) {
self->fd = fd;
}
return (PyObject*)self;
}
static PyObject *
stdprinter_write(PyObject *op, PyObject *args)
{
PyStdPrinter_Object *self = (PyStdPrinter_Object*)op;
PyObject *unicode;
PyObject *bytes = NULL;
const char *str;
Py_ssize_t n;
int err;
/* The function can clear the current exception */
assert(!PyErr_Occurred());
if (self->fd < 0) {
/* fd might be invalid on Windows
* I can't raise an exception here. It may lead to an
* unlimited recursion in the case stderr is invalid.
*/
Py_RETURN_NONE;
}
if (!PyArg_ParseTuple(args, "U", &unicode)) {
return NULL;
}
/* Encode Unicode to UTF-8/backslashreplace */
str = PyUnicode_AsUTF8AndSize(unicode, &n);
if (str == NULL) {
PyErr_Clear();
bytes = _PyUnicode_AsUTF8String(unicode, "backslashreplace");
if (bytes == NULL)
return NULL;
str = PyBytes_AS_STRING(bytes);
n = PyBytes_GET_SIZE(bytes);
}
n = _Py_write(self->fd, str, n);
/* save errno, it can be modified indirectly by Py_XDECREF() */
err = errno;
Py_XDECREF(bytes);
if (n == -1) {
if (err == EAGAIN) {
PyErr_Clear();
Py_RETURN_NONE;
}
return NULL;
}
return PyLong_FromSsize_t(n);
}
static PyObject *
stdprinter_fileno(PyObject *op, PyObject *Py_UNUSED(ignored))
{
PyStdPrinter_Object *self = (PyStdPrinter_Object*)op;
return PyLong_FromLong((long) self->fd);
}
static PyObject *
stdprinter_repr(PyObject *op)
{
PyStdPrinter_Object *self = (PyStdPrinter_Object*)op;
return PyUnicode_FromFormat("<stdprinter(fd=%d) object at %p>",
self->fd, self);
}
static PyObject *
stdprinter_noop(PyObject *self, PyObject *Py_UNUSED(ignored))
{
Py_RETURN_NONE;
}
static PyObject *
stdprinter_isatty(PyObject *op, PyObject *Py_UNUSED(ignored))
{
PyStdPrinter_Object *self = (PyStdPrinter_Object*)op;
long res;
if (self->fd < 0) {
Py_RETURN_FALSE;
}
Py_BEGIN_ALLOW_THREADS
res = isatty(self->fd);
Py_END_ALLOW_THREADS
return PyBool_FromLong(res);
}
static PyMethodDef stdprinter_methods[] = {
{"close", stdprinter_noop, METH_NOARGS, ""},
{"flush", stdprinter_noop, METH_NOARGS, ""},
{"fileno", stdprinter_fileno, METH_NOARGS, ""},
{"isatty", stdprinter_isatty, METH_NOARGS, ""},
{"write", stdprinter_write, METH_VARARGS, ""},
{NULL, NULL} /*sentinel */
};
static PyObject *
get_closed(PyObject *self, void *Py_UNUSED(closure))
{
Py_RETURN_FALSE;
}
static PyObject *
get_mode(PyObject *self, void *Py_UNUSED(closure))
{
return PyUnicode_FromString("w");
}
static PyObject *
get_encoding(PyObject *self, void *Py_UNUSED(closure))
{
Py_RETURN_NONE;
}
static PyGetSetDef stdprinter_getsetlist[] = {
{"closed", get_closed, NULL, "True if the file is closed"},
{"encoding", get_encoding, NULL, "Encoding of the file"},
{"mode", get_mode, NULL, "String giving the file mode"},
{0},
};
PyTypeObject PyStdPrinter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"stderrprinter", /* tp_name */
sizeof(PyStdPrinter_Object), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
0, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
stdprinter_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
stdprinter_methods, /* tp_methods */
0, /* tp_members */
stdprinter_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
0, /* tp_new */
PyObject_Free, /* tp_free */
};
/* ************************** open_code hook ***************************
* The open_code hook allows embedders to override the method used to
* open files that are going to be used by the runtime to execute code
*/
int
PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction hook, void *userData) {
if (Py_IsInitialized() &&
PySys_Audit("setopencodehook", NULL) < 0) {
return -1;
}
if (_PyRuntime.open_code_hook) {
if (Py_IsInitialized()) {
PyErr_SetString(PyExc_SystemError,
"failed to change existing open_code hook");
}
return -1;
}
_PyRuntime.open_code_hook = hook;
_PyRuntime.open_code_userdata = userData;
return 0;
}
PyObject *
PyFile_OpenCodeObject(PyObject *path)
{
PyObject *f = NULL;
if (!PyUnicode_Check(path)) {
PyErr_Format(PyExc_TypeError, "'path' must be 'str', not '%.200s'",
Py_TYPE(path)->tp_name);
return NULL;
}
Py_OpenCodeHookFunction hook = _PyRuntime.open_code_hook;
if (hook) {
f = hook(path, _PyRuntime.open_code_userdata);
} else {
PyObject *open = PyImport_ImportModuleAttrString("_io", "open");
if (open) {
f = PyObject_CallFunction(open, "Os", path, "rb");
Py_DECREF(open);
}
}
return f;
}
PyObject *
PyFile_OpenCode(const char *utf8path)
{
PyObject *pathobj = PyUnicode_FromString(utf8path);
PyObject *f;
if (!pathobj) {
return NULL;
}
f = PyFile_OpenCodeObject(pathobj);
Py_DECREF(pathobj);
return f;
}
int
_PyFile_Flush(PyObject *file)
{
PyObject *tmp = PyObject_CallMethodNoArgs(file, &_Py_ID(flush));
if (tmp == NULL) {
return -1;
}
Py_DECREF(tmp);
return 0;
}
/* Ordered Dictionary object implementation.
This implementation is necessarily explicitly equivalent to the pure Python
OrderedDict class in Lib/collections/__init__.py. The strategy there
involves using a doubly-linked-list to capture the order. We keep to that
strategy, using a lower-level linked-list.
About the Linked-List
=====================
For the linked list we use a basic doubly-linked-list. Using a circularly-
linked-list does have some benefits, but they don't apply so much here
since OrderedDict is focused on the ends of the list (for the most part).
Furthermore, there are some features of generic linked-lists that we simply
don't need for OrderedDict. Thus a simple custom implementation meets our
needs. Alternatives to our simple approach include the QCIRCLE_*
macros from BSD's queue.h, and the linux's list.h.
Getting O(1) Node Lookup
------------------------
One invariant of Python's OrderedDict is that it preserves time complexity
of dict's methods, particularly the O(1) operations. Simply adding a
linked-list on top of dict is not sufficient here; operations for nodes in
the middle of the linked-list implicitly require finding the node first.
With a simple linked-list like we're using, that is an O(n) operation.
Consequently, methods like __delitem__() would change from O(1) to O(n),
which is unacceptable.
In order to preserve O(1) performance for node removal (finding nodes), we
must do better than just looping through the linked-list. Here are options
we've considered:
1. use a second dict to map keys to nodes (a la the pure Python version).
2. keep a simple hash table mirroring the order of dict's, mapping each key
to the corresponding node in the linked-list.
3. use a version of shared keys (split dict) that allows non-unicode keys.
4. have the value stored for each key be a (value, node) pair, and adjust
__getitem__(), get(), etc. accordingly.
The approach with the least performance impact (time and space) is #2,
mirroring the key order of dict's dk_entries with an array of node pointers.
While _Py_dict_lookup() does not give us the index into the array,
we make use of pointer arithmetic to get that index. An alternative would
be to refactor _Py_dict_lookup() to provide the index, explicitly exposing
the implementation detail. We could even just use a custom lookup function
for OrderedDict that facilitates our need. However, both approaches are
significantly more complicated than just using pointer arithmetic.
The catch with mirroring the hash table ordering is that we have to keep
the ordering in sync through any dict resizes. However, that order only
matters during node lookup. We can simply defer any potential resizing
until we need to do a lookup.
Linked-List Nodes
-----------------
The current implementation stores a pointer to the associated key only.
One alternative would be to store a pointer to the PyDictKeyEntry instead.
This would save one pointer de-reference per item, which is nice during
calls to values() and items(). However, it adds unnecessary overhead
otherwise, so we stick with just the key.
Linked-List API
---------------
As noted, the linked-list implemented here does not have all the bells and
whistles. However, we recognize that the implementation may need to
change to accommodate performance improvements or extra functionality. To
that end, we use a simple API to interact with the linked-list. Here's a
summary of the methods/macros:
Node info:
* _odictnode_KEY(node)
* _odictnode_VALUE(od, node)
* _odictnode_PREV(node)
* _odictnode_NEXT(node)
Linked-List info:
* _odict_FIRST(od)
* _odict_LAST(od)
* _odict_EMPTY(od)
* _odict_FOREACH(od, node) - used in place of `for (node=...)`
For adding nodes:
* _odict_add_head(od, node)
* _odict_add_tail(od, node)
* _odict_add_new_node(od, key, hash)
For removing nodes:
* _odict_clear_node(od, node, key, hash)
* _odict_clear_nodes(od, clear_each)
Others:
* _odict_find_node_hash(od, key, hash)
* _odict_find_node(od, key)
* _odict_keys_equal(od1, od2)
And here's a look at how the linked-list relates to the OrderedDict API:
============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === ===
method key val prev next mem 1st last empty iter find add rmv clr keq
============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === ===
__del__ ~ X
__delitem__ free ~ node
__eq__ ~ X
__iter__ X X
__new__ X X
__reduce__ X ~ X
__repr__ X X X
__reversed__ X X
__setitem__ key
__sizeof__ size X
clear ~ ~ X
copy X X X
items X X X
keys X X
move_to_end X X X ~ h/t key
pop free key
popitem X X free X X node
setdefault ~ ? ~
values X X
============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === ===
__delitem__ is the only method that directly relies on finding an arbitrary
node in the linked-list. Everything else is iteration or relates to the
ends of the linked-list.
Situation that Endangers Consistency
------------------------------------
Using a raw linked-list for OrderedDict exposes a key situation that can
cause problems. If a node is stored in a variable, there is a chance that
the node may have been deallocated before the variable gets used, thus
potentially leading to a segmentation fault. A key place where this shows
up is during iteration through the linked list (via _odict_FOREACH or
otherwise).
A number of solutions are available to resolve this situation:
* defer looking up the node until as late as possible and certainly after
any code that could possibly result in a deletion;
* if the node is needed both before and after a point where the node might
be removed, do a check before using the node at the "after" location to
see if the node is still valid;
* like the last one, but simply pull the node again to ensure it's right;
* keep the key in the variable instead of the node and then look up the
node using the key at the point where the node is needed (this is what
we do for the iterators).
Another related problem, preserving consistent ordering during iteration,
is described below. That one is not exclusive to using linked-lists.
Challenges from Subclassing dict
================================
OrderedDict subclasses dict, which is an unusual relationship between two
builtin types (other than the base object type). Doing so results in
some complication and deserves further explanation. There are two things
to consider here. First, in what circumstances or with what adjustments
can OrderedDict be used as a drop-in replacement for dict (at the C level)?
Second, how can the OrderedDict implementation leverage the dict
implementation effectively without introducing unnecessary coupling or
inefficiencies?
This second point is reflected here and in the implementation, so the
further focus is on the first point. It is worth noting that for
overridden methods, the dict implementation is deferred to as much as
possible. Furthermore, coupling is limited to as little as is reasonable.
Concrete API Compatibility
--------------------------
Use of the concrete C-API for dict (PyDict_*) with OrderedDict is
problematic. (See http://bugs.python.org/issue10977.) The concrete API
has a number of hard-coded assumptions tied to the dict implementation.
This is, in part, due to performance reasons, which is understandable
given the part dict plays in Python.
Any attempt to replace dict with OrderedDict for any role in the
interpreter (e.g. **kwds) faces a challenge. Such any effort must
recognize that the instances in affected locations currently interact with
the concrete API.
Here are some ways to address this challenge:
1. Change the relevant usage of the concrete API in CPython and add
PyDict_CheckExact() calls to each of the concrete API functions.
2. Adjust the relevant concrete API functions to explicitly accommodate
OrderedDict.
3. As with #1, add the checks, but improve the abstract API with smart fast
paths for dict and OrderedDict, and refactor CPython to use the abstract
API. Improvements to the abstract API would be valuable regardless.
Adding the checks to the concrete API would help make any interpreter
switch to OrderedDict less painful for extension modules. However, this
won't work. The equivalent C API call to `dict.__setitem__(obj, k, v)`
is `PyDict_SetItem(obj, k, v)`. This illustrates how subclasses in C call
the base class's methods, since there is no equivalent of super() in the
C API. Calling into Python for parent class API would work, but some
extension modules already rely on this feature of the concrete API.
For reference, here is a breakdown of some of the dict concrete API:
========================== ============= =======================
concrete API uses abstract API
========================== ============= =======================
PyDict_Check PyMapping_Check
(PyDict_CheckExact) -
(PyDict_New) -
(PyDictProxy_New) -
PyDict_Clear -
PyDict_Contains PySequence_Contains
PyDict_Copy -
PyDict_SetItem PyObject_SetItem
PyDict_SetItemString PyMapping_SetItemString
PyDict_DelItem PyMapping_DelItem
PyDict_DelItemString PyMapping_DelItemString
PyDict_GetItem -
PyDict_GetItemWithError PyObject_GetItem
PyDict_GetItemString PyMapping_GetItemString
PyDict_Items PyMapping_Items
PyDict_Keys PyMapping_Keys
PyDict_Values PyMapping_Values
PyDict_Size PyMapping_Size
PyMapping_Length
PyDict_Next PyIter_Next
_PyDict_Next -
PyDict_Merge -
PyDict_Update -
PyDict_MergeFromSeq2 -
PyDict_ClearFreeList -
- PyMapping_HasKeyString
- PyMapping_HasKey
========================== ============= =======================
The dict Interface Relative to OrderedDict
==========================================
Since OrderedDict subclasses dict, understanding the various methods and
attributes of dict is important for implementing OrderedDict.
Relevant Type Slots
-------------------
================= ================ =================== ================
slot attribute object dict
================= ================ =================== ================
tp_dealloc - object_dealloc dict_dealloc
tp_repr __repr__ object_repr dict_repr
sq_contains __contains__ - dict_contains
mp_length __len__ - dict_length
mp_subscript __getitem__ - dict_subscript
mp_ass_subscript __setitem__ - dict_ass_sub
__delitem__
tp_hash __hash__ Py_HashPointer ..._HashNotImpl
tp_str __str__ object_str -
tp_getattro __getattribute__ ..._GenericGetAttr (repeated)
__getattr__
tp_setattro __setattr__ ..._GenericSetAttr (disabled)
tp_doc __doc__ (literal) dictionary_doc
tp_traverse - - dict_traverse
tp_clear - - dict_tp_clear
tp_richcompare __eq__ object_richcompare dict_richcompare
__ne__
tp_weaklistoffset (__weakref__) - -
tp_iter __iter__ - dict_iter
tp_dictoffset (__dict__) - -
tp_init __init__ object_init dict_init
tp_alloc - PyType_GenericAlloc (repeated)
tp_new __new__ object_new dict_new
tp_free - PyObject_Free PyObject_GC_Del
================= ================ =================== ================
Relevant Methods
----------------
================ =================== ===============
method object dict
================ =================== ===============
__reduce__ object_reduce -
__sizeof__ object_sizeof dict_sizeof
clear - dict_clear
copy - dict_copy
fromkeys - dict_fromkeys
get - dict_get
items - dictitems_new
keys - dictkeys_new
pop - dict_pop
popitem - dict_popitem
setdefault - dict_setdefault
update - dict_update
values - dictvalues_new
================ =================== ===============
Pure Python OrderedDict
=======================
As already noted, compatibility with the pure Python OrderedDict
implementation is a key goal of this C implementation. To further that
goal, here's a summary of how OrderedDict-specific methods are implemented
in collections/__init__.py. Also provided is an indication of which
methods directly mutate or iterate the object, as well as any relationship
with the underlying linked-list.
============= ============== == ================ === === ====
method impl used ll uses inq mut iter
============= ============== == ================ === === ====
__contains__ dict - - X
__delitem__ OrderedDict Y dict.__delitem__ X
__eq__ OrderedDict N OrderedDict ~
dict.__eq__
__iter__
__getitem__ dict - - X
__iter__ OrderedDict Y - X
__init__ OrderedDict N update
__len__ dict - - X
__ne__ MutableMapping - __eq__ ~
__reduce__ OrderedDict N OrderedDict ~
__iter__
__getitem__
__repr__ OrderedDict N __class__ ~
items
__reversed__ OrderedDict Y - X
__setitem__ OrderedDict Y __contains__ X
dict.__setitem__
__sizeof__ OrderedDict Y __len__ ~
__dict__
clear OrderedDict Y dict.clear X
copy OrderedDict N __class__
__init__
fromkeys OrderedDict N __setitem__
get dict - - ~
items MutableMapping - ItemsView X
keys MutableMapping - KeysView X
move_to_end OrderedDict Y - X
pop OrderedDict N __contains__ X
__getitem__
__delitem__
popitem OrderedDict Y dict.pop X
setdefault OrderedDict N __contains__ ~
__getitem__
__setitem__
update MutableMapping - __setitem__ ~
values MutableMapping - ValuesView X
============= ============== == ================ === === ====
__reversed__ and move_to_end are both exclusive to OrderedDict.
C OrderedDict Implementation
============================
================= ================
slot impl
================= ================
tp_dealloc odict_dealloc
tp_repr odict_repr
mp_ass_subscript odict_ass_sub
tp_doc odict_doc
tp_traverse odict_traverse
tp_clear odict_tp_clear
tp_richcompare odict_richcompare
tp_weaklistoffset (offset)
tp_iter odict_iter
tp_dictoffset (offset)
tp_init odict_init
tp_alloc (repeated)
================= ================
================= ================
method impl
================= ================
__reduce__ odict_reduce
__sizeof__ odict_sizeof
clear odict_clear
copy odict_copy
fromkeys odict_fromkeys
items odictitems_new
keys odictkeys_new
pop odict_pop
popitem odict_popitem
setdefault odict_setdefault
update odict_update
values odictvalues_new
================= ================
Inherited unchanged from object/dict:
================ ==========================
method type field
================ ==========================
- tp_free
__contains__ tp_as_sequence.sq_contains
__getattr__ tp_getattro
__getattribute__ tp_getattro
__getitem__ tp_as_mapping.mp_subscript
__hash__ tp_hash
__len__ tp_as_mapping.mp_length
__setattr__ tp_setattro
__str__ tp_str
get -
================ ==========================
Other Challenges
================
Preserving Ordering During Iteration
------------------------------------
During iteration through an OrderedDict, it is possible that items could
get added, removed, or reordered. For a linked-list implementation, as
with some other implementations, that situation may lead to undefined
behavior. The documentation for dict mentions this in the `iter()` section
of http://docs.python.org/3.4/library/stdtypes.html#dictionary-view-objects.
In this implementation we follow dict's lead (as does the pure Python
implementation) for __iter__(), keys(), values(), and items().
For internal iteration (using _odict_FOREACH or not), there is still the
risk that not all nodes that we expect to be seen in the loop actually get
seen. Thus, we are careful in each of those places to ensure that they
are. This comes, of course, at a small price at each location. The
solutions are much the same as those detailed in the `Situation that
Endangers Consistency` section above.
Potential Optimizations
=======================
* Allocate the nodes as a block via od_fast_nodes instead of individually.
- Set node->key to NULL to indicate the node is not-in-use.
- Add _odict_EXISTS()?
- How to maintain consistency across resizes? Existing node pointers
would be invalidated after a resize, which is particularly problematic
for the iterators.
* Use a more stream-lined implementation of update() and, likely indirectly,
__init__().
*/
/* TODO
sooner:
- reentrancy (make sure everything is at a thread-safe state when calling
into Python). I've already checked this multiple times, but want to
make one more pass.
- add unit tests for reentrancy?
later:
- make the dict views support the full set API (the pure Python impl does)
- implement a fuller MutableMapping API in C?
- move the MutableMapping implementation to abstract.c?
- optimize mutablemapping_update
- use PyObject_Malloc (small object allocator) for odict nodes?
- support subclasses better (e.g. in odict_richcompare)
*/
#include "Python.h"
#include "pycore_call.h" // _PyObject_CallNoArgs()
#include "pycore_ceval.h" // _PyEval_GetBuiltin()
#include "pycore_critical_section.h" //_Py_BEGIN_CRITICAL_SECTION
#include "pycore_dict.h" // _Py_dict_lookup()
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
#include "pycore_pyerrors.h" // _PyErr_ChainExceptions1()
#include "pycore_tuple.h" // _PyTuple_Recycle()
#include <stddef.h> // offsetof()
#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#include "clinic/odictobject.c.h"
/*[clinic input]
class OrderedDict "PyODictObject *" "&PyODict_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ca0641cf6143d4af]*/
typedef struct _odictnode _ODictNode;
/* PyODictObject */
struct _odictobject {
PyDictObject od_dict; /* the underlying dict */
_ODictNode *od_first; /* first node in the linked list, if any */
_ODictNode *od_last; /* last node in the linked list, if any */
/* od_fast_nodes, od_fast_nodes_size and od_resize_sentinel are managed
* by _odict_resize().
* Note that we rely on implementation details of dict for both. */
_ODictNode **od_fast_nodes; /* hash table that mirrors the dict table */
Py_ssize_t od_fast_nodes_size;
void *od_resize_sentinel; /* changes if odict should be resized */
size_t od_state; /* incremented whenever the LL changes */
PyObject *od_inst_dict; /* OrderedDict().__dict__ */
PyObject *od_weakreflist; /* holds weakrefs to the odict */
};
#define _PyODictObject_CAST(op) _Py_CAST(PyODictObject*, (op))
/* ----------------------------------------------
* odict keys (a simple doubly-linked list)
*/
struct _odictnode {
PyObject *key;
Py_hash_t hash;
_ODictNode *next;
_ODictNode *prev;
};
#define _odictnode_KEY(node) \
(node->key)
#define _odictnode_HASH(node) \
(node->hash)
/* borrowed reference */
#define _odictnode_VALUE(node, od) \
PyODict_GetItemWithError((PyObject *)od, _odictnode_KEY(node))
#define _odictnode_PREV(node) (node->prev)
#define _odictnode_NEXT(node) (node->next)
#define _odict_FIRST(od) (_PyODictObject_CAST(od)->od_first)
#define _odict_LAST(od) (_PyODictObject_CAST(od)->od_last)
#define _odict_EMPTY(od) (_odict_FIRST(od) == NULL)
#define _odict_FOREACH(od, node) \
for (node = _odict_FIRST(od); node != NULL; node = _odictnode_NEXT(node))
/* Return the index into the hash table, regardless of a valid node. */
static Py_ssize_t
_odict_get_index_raw(PyODictObject *od, PyObject *key, Py_hash_t hash)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
PyObject *value = NULL;
PyDictKeysObject *keys = ((PyDictObject *)od)->ma_keys;
Py_ssize_t ix;
#ifdef Py_GIL_DISABLED
ix = _Py_dict_lookup_threadsafe((PyDictObject *)od, key, hash, &value);
Py_XDECREF(value);
#else
ix = _Py_dict_lookup((PyDictObject *)od, key, hash, &value);
#endif
if (ix == DKIX_EMPTY) {
return keys->dk_nentries; /* index of new entry */
}
if (ix < 0)
return -1;
/* We use pointer arithmetic to get the entry's index into the table. */
return ix;
}
#define ONE ((Py_ssize_t)1)
/* Replace od->od_fast_nodes with a new table matching the size of dict's. */
static int
_odict_resize(PyODictObject *od)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
Py_ssize_t size, i;
_ODictNode **fast_nodes, *node;
/* Initialize a new "fast nodes" table. */
size = ONE << (((PyDictObject *)od)->ma_keys->dk_log2_size);
fast_nodes = PyMem_NEW(_ODictNode *, size);
if (fast_nodes == NULL) {
PyErr_NoMemory();
return -1;
}
for (i = 0; i < size; i++)
fast_nodes[i] = NULL;
/* Copy the current nodes into the table. */
_odict_FOREACH(od, node) {
i = _odict_get_index_raw(od, _odictnode_KEY(node),
_odictnode_HASH(node));
if (i < 0) {
PyMem_Free(fast_nodes);
return -1;
}
fast_nodes[i] = node;
}
/* Replace the old fast nodes table. */
PyMem_Free(od->od_fast_nodes);
od->od_fast_nodes = fast_nodes;
od->od_fast_nodes_size = size;
od->od_resize_sentinel = ((PyDictObject *)od)->ma_keys;
return 0;
}
/* Return the index into the hash table, regardless of a valid node. */
static Py_ssize_t
_odict_get_index(PyODictObject *od, PyObject *key, Py_hash_t hash)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
PyDictKeysObject *keys;
assert(key != NULL);
keys = ((PyDictObject *)od)->ma_keys;
/* Ensure od_fast_nodes and dk_entries are in sync. */
if (od->od_resize_sentinel != keys ||
od->od_fast_nodes_size != (ONE << (keys->dk_log2_size))) {
int resize_res = _odict_resize(od);
if (resize_res < 0)
return -1;
}
return _odict_get_index_raw(od, key, hash);
}
/* Returns NULL if there was some error or the key was not found. */
static _ODictNode *
_odict_find_node_hash(PyODictObject *od, PyObject *key, Py_hash_t hash)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
Py_ssize_t index;
if (_odict_EMPTY(od))
return NULL;
index = _odict_get_index(od, key, hash);
if (index < 0)
return NULL;
assert(od->od_fast_nodes != NULL);
return od->od_fast_nodes[index];
}
static _ODictNode *
_odict_find_node(PyODictObject *od, PyObject *key)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
Py_ssize_t index;
Py_hash_t hash;
if (_odict_EMPTY(od))
return NULL;
hash = PyObject_Hash(key);
if (hash == -1)
return NULL;
index = _odict_get_index(od, key, hash);
if (index < 0)
return NULL;
assert(od->od_fast_nodes != NULL);
return od->od_fast_nodes[index];
}
static void
_odict_add_head(PyODictObject *od, _ODictNode *node)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
_odictnode_PREV(node) = NULL;
_odictnode_NEXT(node) = _odict_FIRST(od);
if (_odict_FIRST(od) == NULL)
_odict_LAST(od) = node;
else
_odictnode_PREV(_odict_FIRST(od)) = node;
_odict_FIRST(od) = node;
od->od_state++;
}
static void
_odict_add_tail(PyODictObject *od, _ODictNode *node)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
_odictnode_PREV(node) = _odict_LAST(od);
_odictnode_NEXT(node) = NULL;
if (_odict_LAST(od) == NULL)
_odict_FIRST(od) = node;
else
_odictnode_NEXT(_odict_LAST(od)) = node;
_odict_LAST(od) = node;
od->od_state++;
}
/* adds the node to the end of the list */
static int
_odict_add_new_node(PyODictObject *od, PyObject *key, Py_hash_t hash)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
Py_ssize_t i;
_ODictNode *node;
Py_INCREF(key);
i = _odict_get_index(od, key, hash);
if (i < 0) {
if (!PyErr_Occurred())
PyErr_SetObject(PyExc_KeyError, key);
Py_DECREF(key);
return -1;
}
assert(od->od_fast_nodes != NULL);
if (od->od_fast_nodes[i] != NULL) {
/* We already have a node for the key so there's no need to add one. */
Py_DECREF(key);
return 0;
}
/* must not be added yet */
node = (_ODictNode *)PyMem_Malloc(sizeof(_ODictNode));
if (node == NULL) {
Py_DECREF(key);
PyErr_NoMemory();
return -1;
}
_odictnode_KEY(node) = key;
_odictnode_HASH(node) = hash;
_odict_add_tail(od, node);
od->od_fast_nodes[i] = node;
return 0;
}
/* Putting the decref after the free causes problems. */
#define _odictnode_DEALLOC(node) \
do { \
Py_DECREF(_odictnode_KEY(node)); \
PyMem_Free((void *)node); \
} while (0)
/* Repeated calls on the same node are no-ops. */
static void
_odict_remove_node(PyODictObject *od, _ODictNode *node)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
if (_odict_FIRST(od) == node)
_odict_FIRST(od) = _odictnode_NEXT(node);
else if (_odictnode_PREV(node) != NULL)
_odictnode_NEXT(_odictnode_PREV(node)) = _odictnode_NEXT(node);
if (_odict_LAST(od) == node)
_odict_LAST(od) = _odictnode_PREV(node);
else if (_odictnode_NEXT(node) != NULL)
_odictnode_PREV(_odictnode_NEXT(node)) = _odictnode_PREV(node);
_odictnode_PREV(node) = NULL;
_odictnode_NEXT(node) = NULL;
od->od_state++;
}
/* If someone calls PyDict_DelItem() directly on an OrderedDict, we'll
get all sorts of problems here. In PyODict_DelItem we make sure to
call _odict_clear_node first.
This matters in the case of colliding keys. Suppose we add 3 keys:
[A, B, C], where the hash of C collides with A and the next possible
index in the hash table is occupied by B. If we remove B then for C
the dict's looknode func will give us the old index of B instead of
the index we got before deleting B. However, the node for C in
od_fast_nodes is still at the old dict index of C. Thus to be sure
things don't get out of sync, we clear the node in od_fast_nodes
*before* calling PyDict_DelItem.
The same must be done for any other OrderedDict operations where
we modify od_fast_nodes.
*/
static int
_odict_clear_node(PyODictObject *od, _ODictNode *node, PyObject *key,
Py_hash_t hash)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
Py_ssize_t i;
assert(key != NULL);
if (_odict_EMPTY(od)) {
/* Let later code decide if this is a KeyError. */
return 0;
}
i = _odict_get_index(od, key, hash);
if (i < 0)
return PyErr_Occurred() ? -1 : 0;
assert(od->od_fast_nodes != NULL);
if (node == NULL)
node = od->od_fast_nodes[i];
assert(node == od->od_fast_nodes[i]);
if (node == NULL) {
/* Let later code decide if this is a KeyError. */
return 0;
}
// Now clear the node.
od->od_fast_nodes[i] = NULL;
_odict_remove_node(od, node);
_odictnode_DEALLOC(node);
return 0;
}
static void
_odict_clear_nodes(PyODictObject *od)
{
_ODictNode *node, *next;
PyMem_Free(od->od_fast_nodes);
od->od_fast_nodes = NULL;
od->od_fast_nodes_size = 0;
od->od_resize_sentinel = NULL;
node = _odict_FIRST(od);
_odict_FIRST(od) = NULL;
_odict_LAST(od) = NULL;
while (node != NULL) {
next = _odictnode_NEXT(node);
_odictnode_DEALLOC(node);
node = next;
}
od->od_state++;
}
/* There isn't any memory management of nodes past this point. */
#undef _odictnode_DEALLOC
static int
_odict_keys_equal(PyODictObject *a, PyODictObject *b)
{
_ODictNode *node_a, *node_b;
// keep operands' state to detect undesired mutations
const size_t state_a = a->od_state;
const size_t state_b = b->od_state;
node_a = _odict_FIRST(a);
node_b = _odict_FIRST(b);
while (1) {
if (node_a == NULL && node_b == NULL) {
/* success: hit the end of each at the same time */
return 1;
}
else if (node_a == NULL || node_b == NULL) {
/* unequal length */
return 0;
}
else {
PyObject *key_a = Py_NewRef(_odictnode_KEY(node_a));
PyObject *key_b = Py_NewRef(_odictnode_KEY(node_b));
int res = PyObject_RichCompareBool(key_a, key_b, Py_EQ);
Py_DECREF(key_a);
Py_DECREF(key_b);
if (res < 0) {
return res;
}
else if (a->od_state != state_a || b->od_state != state_b) {
PyErr_SetString(PyExc_RuntimeError,
"OrderedDict mutated during iteration");
return -1;
}
else if (res == 0) {
// This check comes after the check on the state
// in order for the exception to be set correctly.
return 0;
}
/* otherwise it must match, so move on to the next one */
node_a = _odictnode_NEXT(node_a);
node_b = _odictnode_NEXT(node_b);
}
}
}
/* ----------------------------------------------
* OrderedDict mapping methods
*/
/* mp_ass_subscript: __setitem__() and __delitem__() */
static int
odict_mp_ass_sub(PyObject *od, PyObject *v, PyObject *w)
{
if (w == NULL)
return PyODict_DelItem(od, v);
else
return PyODict_SetItem(od, v, w);
}
/* tp_as_mapping */
static PyMappingMethods odict_as_mapping = {
0, /*mp_length*/
0, /*mp_subscript*/
odict_mp_ass_sub, /*mp_ass_subscript*/
};
/* ----------------------------------------------
* OrderedDict number methods
*/
static int mutablemapping_update_arg(PyObject*, PyObject*);
static PyObject *
odict_or(PyObject *left, PyObject *right)
{
PyTypeObject *type;
PyObject *other;
if (PyODict_Check(left)) {
type = Py_TYPE(left);
other = right;
}
else {
type = Py_TYPE(right);
other = left;
}
if (!PyDict_Check(other)) {
Py_RETURN_NOTIMPLEMENTED;
}
PyObject *new = PyObject_CallOneArg((PyObject*)type, left);
if (!new) {
return NULL;
}
if (mutablemapping_update_arg(new, right) < 0) {
Py_DECREF(new);
return NULL;
}
return new;
}
static PyObject *
odict_inplace_or(PyObject *self, PyObject *other)
{
if (mutablemapping_update_arg(self, other) < 0) {
return NULL;
}
return Py_NewRef(self);
}
/* tp_as_number */
static PyNumberMethods odict_as_number = {
.nb_or = odict_or,
.nb_inplace_or = odict_inplace_or,
};
/* ----------------------------------------------
* OrderedDict methods
*/
/* fromkeys() */
/*[clinic input]
@permit_long_summary
@classmethod
OrderedDict.fromkeys
iterable as seq: object
value: object = None
Create a new ordered dictionary with keys from iterable and values set to value.
[clinic start generated code]*/
static PyObject *
OrderedDict_fromkeys_impl(PyTypeObject *type, PyObject *seq, PyObject *value)
/*[clinic end generated code: output=c10390d452d78d6d input=1277ae0769083848]*/
{
return _PyDict_FromKeys((PyObject *)type, seq, value);
}
/*[clinic input]
@critical_section
OrderedDict.__sizeof__ -> Py_ssize_t
[clinic start generated code]*/
static Py_ssize_t
OrderedDict___sizeof___impl(PyODictObject *self)
/*[clinic end generated code: output=1a8560db8cf83ac5 input=655e989ae24daa6a]*/
{
Py_ssize_t res = _PyDict_SizeOf_LockHeld((PyDictObject *)self);
res += sizeof(_ODictNode *) * self->od_fast_nodes_size; /* od_fast_nodes */
if (!_odict_EMPTY(self)) {
res += sizeof(_ODictNode) * PyODict_SIZE(self); /* linked-list */
}
return res;
}
/*[clinic input]
OrderedDict.__reduce__
self as od: self(type="PyODictObject *")
Return state information for pickling
[clinic start generated code]*/
static PyObject *
OrderedDict___reduce___impl(PyODictObject *od)
/*[clinic end generated code: output=71eeb81f760a6a8e input=b0467c7ec400fe5e]*/
{
PyObject *state, *result = NULL;
PyObject *items_iter, *items, *args = NULL;
/* capture any instance state */
state = _PyObject_GetState((PyObject *)od);
if (state == NULL)
goto Done;
/* build the result */
args = PyTuple_New(0);
if (args == NULL)
goto Done;
items = PyObject_CallMethodNoArgs((PyObject *)od, &_Py_ID(items));
if (items == NULL)
goto Done;
items_iter = PyObject_GetIter(items);
Py_DECREF(items);
if (items_iter == NULL)
goto Done;
result = PyTuple_Pack(5, Py_TYPE(od), args, state, Py_None, items_iter);
Py_DECREF(items_iter);
Done:
Py_XDECREF(state);
Py_XDECREF(args);
return result;
}
/* setdefault(): Skips __missing__() calls. */
static int PyODict_SetItem_LockHeld(PyObject *self, PyObject *key, PyObject *value);
/*[clinic input]
@critical_section
OrderedDict.setdefault
key: object
default: object = None
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
[clinic start generated code]*/
static PyObject *
OrderedDict_setdefault_impl(PyODictObject *self, PyObject *key,
PyObject *default_value)
/*[clinic end generated code: output=97537cb7c28464b6 input=d7b93e92734f99b5]*/
{
PyObject *result = NULL;
if (PyODict_CheckExact(self)) {
result = PyODict_GetItemWithError(self, key); /* borrowed */
if (result == NULL) {
if (PyErr_Occurred())
return NULL;
assert(_odict_find_node(self, key) == NULL);
if (PyODict_SetItem_LockHeld((PyObject *)self, key, default_value) >= 0) {
result = Py_NewRef(default_value);
}
}
else {
Py_INCREF(result);
}
}
else {
int exists = PySequence_Contains((PyObject *)self, key);
if (exists < 0) {
return NULL;
}
else if (exists) {
result = PyObject_GetItem((PyObject *)self, key);
}
else if (PyObject_SetItem((PyObject *)self, key, default_value) >= 0) {
result = Py_NewRef(default_value);
}
}
return result;
}
/* pop() */
static PyObject *
_odict_popkey_hash(PyObject *od, PyObject *key, PyObject *failobj,
Py_hash_t hash)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
PyObject *value = NULL;
_ODictNode *node = _odict_find_node_hash(_PyODictObject_CAST(od), key, hash);
if (node != NULL) {
/* Pop the node first to avoid a possible dict resize (due to
eval loop reentrancy) and complications due to hash collision
resolution. */
int res = _odict_clear_node(_PyODictObject_CAST(od), node, key, hash);
if (res < 0) {
goto done;
}
/* Now delete the value from the dict. */
if (_PyDict_Pop_KnownHash((PyDictObject *)od, key, hash,
&value) == 0) {
value = Py_NewRef(failobj);
}
}
else if (value == NULL && !PyErr_Occurred()) {
/* Apply the fallback value, if necessary. */
if (failobj) {
value = Py_NewRef(failobj);
}
else {
PyErr_SetObject(PyExc_KeyError, key);
}
}
done:
return value;
}
/* Skips __missing__() calls. */
/*[clinic input]
@critical_section
@permit_long_summary
OrderedDict.pop
key: object
default: object = NULL
od.pop(key[,default]) -> v, remove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise,
raise a KeyError.
[clinic start generated code]*/
static PyObject *
OrderedDict_pop_impl(PyODictObject *self, PyObject *key,
PyObject *default_value)
/*[clinic end generated code: output=7a6447d104e7494b input=0742e3c9bf076a72]*/
{
Py_hash_t hash = PyObject_Hash(key);
if (hash == -1)
return NULL;
return _odict_popkey_hash((PyObject *)self, key, default_value, hash);
}
/* popitem() */
/*[clinic input]
@critical_section
OrderedDict.popitem
last: bool = True
Remove and return a (key, value) pair from the dictionary.
Pairs are returned in LIFO order if last is true or FIFO order if false.
[clinic start generated code]*/
static PyObject *
OrderedDict_popitem_impl(PyODictObject *self, int last)
/*[clinic end generated code: output=98e7d986690d49eb input=8aafc7433e0a40e7]*/
{
PyObject *key, *value, *item = NULL;
_ODictNode *node;
/* pull the item */
if (_odict_EMPTY(self)) {
PyErr_SetString(PyExc_KeyError, "dictionary is empty");
return NULL;
}
node = last ? _odict_LAST(self) : _odict_FIRST(self);
key = Py_NewRef(_odictnode_KEY(node));
value = _odict_popkey_hash((PyObject *)self, key, NULL, _odictnode_HASH(node));
if (value == NULL)
return NULL;
item = PyTuple_Pack(2, key, value);
Py_DECREF(key);
Py_DECREF(value);
return item;
}
/* keys() */
/* MutableMapping.keys() does not have a docstring. */
PyDoc_STRVAR(odict_keys__doc__, "");
static PyObject * odictkeys_new(PyObject *od, PyObject *Py_UNUSED(ignored)); /* forward */
static int
_PyODict_SetItem_KnownHash_LockHeld(PyObject *od, PyObject *key, PyObject *value,
Py_hash_t hash); /* forward */
/* values() */
/* MutableMapping.values() does not have a docstring. */
PyDoc_STRVAR(odict_values__doc__, "");
static PyObject * odictvalues_new(PyObject *od, PyObject *Py_UNUSED(ignored)); /* forward */
/* items() */
/* MutableMapping.items() does not have a docstring. */
PyDoc_STRVAR(odict_items__doc__, "");
static PyObject * odictitems_new(PyObject *od, PyObject *Py_UNUSED(ignored)); /* forward */
/* update() */
/* MutableMapping.update() does not have a docstring. */
PyDoc_STRVAR(odict_update__doc__, "");
/* forward */
static PyObject * mutablemapping_update(PyObject *, PyObject *, PyObject *);
#define odict_update mutablemapping_update
/*[clinic input]
@critical_section
OrderedDict.clear
Remove all items from ordered dict.
[clinic start generated code]*/
static PyObject *
OrderedDict_clear_impl(PyODictObject *self)
/*[clinic end generated code: output=a1a76d1322f556c5 input=08b12322e74c535c]*/
{
_PyDict_Clear_LockHeld((PyObject *)self);
_odict_clear_nodes(self);
Py_RETURN_NONE;
}
/* copy() */
/*[clinic input]
@critical_section
OrderedDict.copy
self as od: self
A shallow copy of ordered dict.
[clinic start generated code]*/
static PyObject *
OrderedDict_copy_impl(PyObject *od)
/*[clinic end generated code: output=9cdbe7394aecc576 input=e329951ae617ed48]*/
{
_ODictNode *node;
PyObject *od_copy;
if (PyODict_CheckExact(od))
od_copy = PyODict_New();
else
od_copy = _PyObject_CallNoArgs((PyObject *)Py_TYPE(od));
if (od_copy == NULL)
return NULL;
if (PyODict_CheckExact(od)) {
_odict_FOREACH(od, node) {
PyObject *key = _odictnode_KEY(node);
PyObject *value = _odictnode_VALUE(node, od);
if (value == NULL) {
if (!PyErr_Occurred())
PyErr_SetObject(PyExc_KeyError, key);
goto fail;
}
if (_PyODict_SetItem_KnownHash_LockHeld((PyObject *)od_copy, key, value,
_odictnode_HASH(node)) != 0)
goto fail;
}
}
else {
_odict_FOREACH(od, node) {
int res;
PyObject *value = PyObject_GetItem((PyObject *)od,
_odictnode_KEY(node));
if (value == NULL)
goto fail;
res = PyObject_SetItem((PyObject *)od_copy,
_odictnode_KEY(node), value);
Py_DECREF(value);
if (res != 0)
goto fail;
}
}
return od_copy;
fail:
Py_DECREF(od_copy);
return NULL;
}
/* __reversed__() */
PyDoc_STRVAR(odict_reversed__doc__, "od.__reversed__() <==> reversed(od)");
#define _odict_ITER_REVERSED 1
#define _odict_ITER_KEYS 2
#define _odict_ITER_VALUES 4
#define _odict_ITER_ITEMS (_odict_ITER_KEYS|_odict_ITER_VALUES)
/* forward */
static PyObject * odictiter_new(PyODictObject *, int);
static PyObject *
odict_reversed(PyObject *op, PyObject *Py_UNUSED(ignored))
{
PyODictObject *od = _PyODictObject_CAST(op);
return odictiter_new(od, _odict_ITER_KEYS|_odict_ITER_REVERSED);
}
/* move_to_end() */
/*[clinic input]
@critical_section
OrderedDict.move_to_end
key: object
last: bool = True
Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
[clinic start generated code]*/
static PyObject *
OrderedDict_move_to_end_impl(PyODictObject *self, PyObject *key, int last)
/*[clinic end generated code: output=fafa4c5cc9b92f20 input=09f8bc7053c0f6d4]*/
{
_ODictNode *node;
if (_odict_EMPTY(self)) {
PyErr_SetObject(PyExc_KeyError, key);
return NULL;
}
node = last ? _odict_LAST(self) : _odict_FIRST(self);
if (key != _odictnode_KEY(node)) {
node = _odict_find_node(self, key);
if (node == NULL) {
if (!PyErr_Occurred())
PyErr_SetObject(PyExc_KeyError, key);
return NULL;
}
if (last) {
/* Only move if not already the last one. */
if (node != _odict_LAST(self)) {
_odict_remove_node(self, node);
_odict_add_tail(self, node);
}
}
else {
/* Only move if not already the first one. */
if (node != _odict_FIRST(self)) {
_odict_remove_node(self, node);
_odict_add_head(self, node);
}
}
}
Py_RETURN_NONE;
}
/* tp_methods */
static PyMethodDef odict_methods[] = {
/* overridden dict methods */
ORDEREDDICT_FROMKEYS_METHODDEF
ORDEREDDICT___SIZEOF___METHODDEF
ORDEREDDICT___REDUCE___METHODDEF
ORDEREDDICT_SETDEFAULT_METHODDEF
ORDEREDDICT_POP_METHODDEF
ORDEREDDICT_POPITEM_METHODDEF
{"keys", odictkeys_new, METH_NOARGS,
odict_keys__doc__},
{"values", odictvalues_new, METH_NOARGS,
odict_values__doc__},
{"items", odictitems_new, METH_NOARGS,
odict_items__doc__},
{"update", _PyCFunction_CAST(odict_update), METH_VARARGS | METH_KEYWORDS,
odict_update__doc__},
ORDEREDDICT_CLEAR_METHODDEF
ORDEREDDICT_COPY_METHODDEF
/* new methods */
{"__reversed__", odict_reversed, METH_NOARGS,
odict_reversed__doc__},
ORDEREDDICT_MOVE_TO_END_METHODDEF
{NULL, NULL} /* sentinel */
};
/* ----------------------------------------------
* OrderedDict members
*/
/* tp_getset */
static PyGetSetDef odict_getset[] = {
{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
{NULL}
};
/* ----------------------------------------------
* OrderedDict type slot methods
*/
/* tp_dealloc */
static void
odict_dealloc(PyObject *op)
{
PyODictObject *self = _PyODictObject_CAST(op);
PyObject_GC_UnTrack(self);
Py_XDECREF(self->od_inst_dict);
FT_CLEAR_WEAKREFS(op, self->od_weakreflist);
_odict_clear_nodes(self);
PyDict_Type.tp_dealloc((PyObject *)self);
}
/* tp_repr */
static PyObject *
odict_repr(PyObject *op)
{
PyODictObject *self = _PyODictObject_CAST(op);
int i;
PyObject *result = NULL, *dcopy = NULL;
if (PyODict_SIZE(self) == 0)
return PyUnicode_FromFormat("%s()", _PyType_Name(Py_TYPE(self)));
i = Py_ReprEnter((PyObject *)self);
if (i != 0) {
return i > 0 ? PyUnicode_FromString("...") : NULL;
}
dcopy = PyDict_Copy((PyObject *)self);
if (dcopy == NULL) {
goto Done;
}
result = PyUnicode_FromFormat("%s(%R)",
_PyType_Name(Py_TYPE(self)),
dcopy);
Py_DECREF(dcopy);
Done:
Py_ReprLeave((PyObject *)self);
return result;
}
/* tp_doc */
PyDoc_STRVAR(odict_doc,
"Dictionary that remembers insertion order");
/* tp_traverse */
static int
odict_traverse(PyObject *op, visitproc visit, void *arg)
{
PyODictObject *od = _PyODictObject_CAST(op);
_ODictNode *node;
Py_VISIT(od->od_inst_dict);
_odict_FOREACH(od, node) {
Py_VISIT(_odictnode_KEY(node));
}
return PyDict_Type.tp_traverse((PyObject *)od, visit, arg);
}
/* tp_clear */
static int
odict_tp_clear(PyObject *op)
{
PyODictObject *od = _PyODictObject_CAST(op);
Py_CLEAR(od->od_inst_dict);
// cannot use lock held variant as critical section is not held here
PyDict_Clear(op);
_odict_clear_nodes(od);
return 0;
}
/* tp_richcompare */
static PyObject *
odict_richcompare_lock_held(PyObject *v, PyObject *w, int op)
{
if (!PyODict_Check(v) || !PyDict_Check(w)) {
Py_RETURN_NOTIMPLEMENTED;
}
if (op == Py_EQ || op == Py_NE) {
PyObject *res, *cmp;
int eq;
cmp = PyDict_Type.tp_richcompare(v, w, op);
if (cmp == NULL)
return NULL;
if (!PyODict_Check(w))
return cmp;
if (op == Py_EQ && cmp == Py_False)
return cmp;
if (op == Py_NE && cmp == Py_True)
return cmp;
Py_DECREF(cmp);
/* Try comparing odict keys. */
eq = _odict_keys_equal(_PyODictObject_CAST(v), _PyODictObject_CAST(w));
if (eq < 0)
return NULL;
res = (eq == (op == Py_EQ)) ? Py_True : Py_False;
return Py_NewRef(res);
} else {
Py_RETURN_NOTIMPLEMENTED;
}
}
static PyObject *
odict_richcompare(PyObject *v, PyObject *w, int op)
{
PyObject *res;
Py_BEGIN_CRITICAL_SECTION2(v, w);
res = odict_richcompare_lock_held(v, w, op);
Py_END_CRITICAL_SECTION2();
return res;
}
/* tp_iter */
static PyObject *
odict_iter(PyObject *op)
{
return odictiter_new(_PyODictObject_CAST(op), _odict_ITER_KEYS);
}
/* tp_init */
static int
odict_init(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *res;
Py_ssize_t len = PyObject_Length(args);
if (len == -1)
return -1;
if (len > 1) {
const char *msg = "expected at most 1 argument, got %zd";
PyErr_Format(PyExc_TypeError, msg, len);
return -1;
}
/* __init__() triggering update() is just the way things are! */
res = odict_update(self, args, kwds);
if (res == NULL) {
return -1;
} else {
Py_DECREF(res);
return 0;
}
}
/* PyODict_Type */
PyTypeObject PyODict_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"collections.OrderedDict", /* tp_name */
sizeof(PyODictObject), /* tp_basicsize */
0, /* tp_itemsize */
odict_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
odict_repr, /* tp_repr */
&odict_as_number, /* tp_as_number */
0, /* tp_as_sequence */
&odict_as_mapping, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,/* tp_flags */
odict_doc, /* tp_doc */
odict_traverse, /* tp_traverse */
odict_tp_clear, /* tp_clear */
odict_richcompare, /* tp_richcompare */
offsetof(PyODictObject, od_weakreflist), /* tp_weaklistoffset */
odict_iter, /* tp_iter */
0, /* tp_iternext */
odict_methods, /* tp_methods */
0, /* tp_members */
odict_getset, /* tp_getset */
&PyDict_Type, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(PyODictObject, od_inst_dict), /* tp_dictoffset */
odict_init, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
0, /* tp_new */
0, /* tp_free */
};
/* ----------------------------------------------
* the public OrderedDict API
*/
PyObject *
PyODict_New(void)
{
return PyDict_Type.tp_new(&PyODict_Type, NULL, NULL);
}
static int
_PyODict_SetItem_KnownHash_LockHeld(PyObject *od, PyObject *key, PyObject *value,
Py_hash_t hash)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
int res = _PyDict_SetItem_KnownHash_LockHeld((PyDictObject *)od, key, value, hash);
if (res == 0) {
res = _odict_add_new_node(_PyODictObject_CAST(od), key, hash);
if (res < 0) {
/* Revert setting the value on the dict */
PyObject *exc = PyErr_GetRaisedException();
(void) _PyDict_DelItem_KnownHash(od, key, hash);
_PyErr_ChainExceptions1(exc);
}
}
return res;
}
static int
PyODict_SetItem_LockHeld(PyObject *od, PyObject *key, PyObject *value)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
Py_hash_t hash = PyObject_Hash(key);
if (hash == -1) {
return -1;
}
return _PyODict_SetItem_KnownHash_LockHeld(od, key, value, hash);
}
int
PyODict_SetItem(PyObject *od, PyObject *key, PyObject *value)
{
int res;
Py_BEGIN_CRITICAL_SECTION(od);
res = PyODict_SetItem_LockHeld(od, key, value);
Py_END_CRITICAL_SECTION();
return res;
}
int
PyODict_DelItem_LockHeld(PyObject *od, PyObject *key)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(od);
int res;
Py_hash_t hash = PyObject_Hash(key);
if (hash == -1)
return -1;
res = _odict_clear_node(_PyODictObject_CAST(od), NULL, key, hash);
if (res < 0)
return -1;
return _PyDict_DelItem_KnownHash_LockHeld(od, key, hash);
}
int
PyODict_DelItem(PyObject *od, PyObject *key)
{
int res;
Py_BEGIN_CRITICAL_SECTION(od);
res = PyODict_DelItem_LockHeld(od, key);
Py_END_CRITICAL_SECTION();
return res;
}
/* -------------------------------------------
* The OrderedDict views (keys/values/items)
*/
typedef struct {
PyObject_HEAD
int kind;
PyODictObject *di_odict;
Py_ssize_t di_size;
size_t di_state;
PyObject *di_current;
PyObject *di_result; /* reusable result tuple for iteritems */
} odictiterobject;
static void
odictiter_dealloc(PyObject *op)
{
odictiterobject *di = (odictiterobject*)op;
_PyObject_GC_UNTRACK(di);
Py_XDECREF(di->di_odict);
Py_XDECREF(di->di_current);
if ((di->kind & _odict_ITER_ITEMS) == _odict_ITER_ITEMS) {
Py_DECREF(di->di_result);
}
PyObject_GC_Del(di);
}
static int
odictiter_traverse(PyObject *op, visitproc visit, void *arg)
{
odictiterobject *di = (odictiterobject*)op;
Py_VISIT(di->di_odict);
Py_VISIT(di->di_current); /* A key could be any type, not just str. */
Py_VISIT(di->di_result);
return 0;
}
/* In order to protect against modifications during iteration, we track
* the current key instead of the current node. */
static PyObject *
odictiter_nextkey_lock_held(odictiterobject *di)
{
assert(di->di_odict != NULL);
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(di->di_odict);
PyObject *key = NULL;
_ODictNode *node;
int reversed = di->kind & _odict_ITER_REVERSED;
if (di->di_current == NULL)
goto done; /* We're already done. */
/* Check for unsupported changes. */
if (di->di_odict->od_state != di->di_state) {
PyErr_SetString(PyExc_RuntimeError,
"OrderedDict mutated during iteration");
goto done;
}
if (di->di_size != PyODict_SIZE(di->di_odict)) {
PyErr_SetString(PyExc_RuntimeError,
"OrderedDict changed size during iteration");
di->di_size = -1; /* Make this state sticky */
return NULL;
}
/* Get the key. */
node = _odict_find_node(di->di_odict, di->di_current);
if (node == NULL) {
if (!PyErr_Occurred())
PyErr_SetObject(PyExc_KeyError, di->di_current);
/* Must have been deleted. */
Py_CLEAR(di->di_current);
return NULL;
}
key = di->di_current;
/* Advance to the next key. */
node = reversed ? _odictnode_PREV(node) : _odictnode_NEXT(node);
if (node == NULL) {
/* Reached the end. */
di->di_current = NULL;
}
else {
di->di_current = Py_NewRef(_odictnode_KEY(node));
}
return key;
done:
Py_CLEAR(di->di_odict);
return key;
}
static PyObject *
odictiter_nextkey(odictiterobject *di)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(di);
if (di->di_odict == NULL) {
return NULL;
}
PyObject *res;
Py_BEGIN_CRITICAL_SECTION(di->di_odict);
res = odictiter_nextkey_lock_held(di);
Py_END_CRITICAL_SECTION();
return res;
}
static PyObject *
odictiter_iternext_lock_held(PyObject *op)
{
odictiterobject *di = (odictiterobject*)op;
PyObject *result, *value;
PyObject *key = odictiter_nextkey(di); /* new reference */
if (key == NULL)
return NULL;
/* Handle the keys case. */
if (! (di->kind & _odict_ITER_VALUES)) {
return key;
}
if (PyDict_GetItemRef((PyObject *)di->di_odict, key, &value) != 1) {
if (!PyErr_Occurred())
PyErr_SetObject(PyExc_KeyError, key);
Py_DECREF(key);
goto done;
}
/* Handle the values case. */
if (!(di->kind & _odict_ITER_KEYS)) {
Py_DECREF(key);
return value;
}
/* Handle the items case. */
result = di->di_result;
if (_PyObject_IsUniquelyReferenced(result)) {
/* not in use so we can reuse it
* (the common case during iteration) */
Py_INCREF(result);
Py_DECREF(PyTuple_GET_ITEM(result, 0)); /* borrowed */
Py_DECREF(PyTuple_GET_ITEM(result, 1)); /* borrowed */
// bpo-42536: The GC may have untracked this result tuple. Since we're
// recycling it, make sure it's tracked again:
_PyTuple_Recycle(result);
}
else {
result = PyTuple_New(2);
if (result == NULL) {
Py_DECREF(key);
Py_DECREF(value);
goto done;
}
}
PyTuple_SET_ITEM(result, 0, key); /* steals reference */
PyTuple_SET_ITEM(result, 1, value); /* steals reference */
return result;
done:
Py_CLEAR(di->di_current);
Py_CLEAR(di->di_odict);
return NULL;
}
static PyObject *
odictiter_iternext(PyObject *op)
{
PyObject *res;
Py_BEGIN_CRITICAL_SECTION(op);
res = odictiter_iternext_lock_held(op);
Py_END_CRITICAL_SECTION();
return res;
}
/* No need for tp_clear because odictiterobject is not mutable. */
PyDoc_STRVAR(reduce_doc, "Return state information for pickling");
static PyObject *
odictiter_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
{
odictiterobject *di = (odictiterobject*)op;
/* copy the iterator state */
odictiterobject tmp = *di;
Py_XINCREF(tmp.di_odict);
Py_XINCREF(tmp.di_current);
/* iterate the temporary into a list */
PyObject *list = PySequence_List((PyObject*)&tmp);
Py_XDECREF(tmp.di_odict);
Py_XDECREF(tmp.di_current);
if (list == NULL) {
return NULL;
}
return Py_BuildValue("N(N)", _PyEval_GetBuiltin(&_Py_ID(iter)), list);
}
static PyMethodDef odictiter_methods[] = {
{"__reduce__", odictiter_reduce, METH_NOARGS, reduce_doc},
{NULL, NULL} /* sentinel */
};
PyTypeObject PyODictIter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"odict_iterator", /* tp_name */
sizeof(odictiterobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
odictiter_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
0, /* tp_doc */
odictiter_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
odictiter_iternext, /* tp_iternext */
odictiter_methods, /* tp_methods */
0,
};
static PyObject *
odictiter_new(PyODictObject *od, int kind)
{
odictiterobject *di;
_ODictNode *node;
int reversed = kind & _odict_ITER_REVERSED;
di = PyObject_GC_New(odictiterobject, &PyODictIter_Type);
if (di == NULL)
return NULL;
if ((kind & _odict_ITER_ITEMS) == _odict_ITER_ITEMS) {
di->di_result = PyTuple_Pack(2, Py_None, Py_None);
if (di->di_result == NULL) {
Py_DECREF(di);
return NULL;
}
}
else {
di->di_result = NULL;
}
di->kind = kind;
node = reversed ? _odict_LAST(od) : _odict_FIRST(od);
di->di_current = node ? Py_NewRef(_odictnode_KEY(node)) : NULL;
di->di_size = PyODict_SIZE(od);
di->di_state = od->od_state;
di->di_odict = (PyODictObject*)Py_NewRef(od);
_PyObject_GC_TRACK(di);
return (PyObject *)di;
}
/* keys() */
static PyObject *
odictkeys_iter(PyObject *op)
{
_PyDictViewObject *dv = (_PyDictViewObject*)op;
if (dv->dv_dict == NULL) {
Py_RETURN_NONE;
}
return odictiter_new(_PyODictObject_CAST(dv->dv_dict),
_odict_ITER_KEYS);
}
static PyObject *
odictkeys_reversed(PyObject *op, PyObject *Py_UNUSED(ignored))
{
_PyDictViewObject *dv = (_PyDictViewObject*)op;
if (dv->dv_dict == NULL) {
Py_RETURN_NONE;
}
return odictiter_new(_PyODictObject_CAST(dv->dv_dict),
_odict_ITER_KEYS|_odict_ITER_REVERSED);
}
static PyMethodDef odictkeys_methods[] = {
{"__reversed__", odictkeys_reversed, METH_NOARGS, NULL},
{NULL, NULL} /* sentinel */
};
PyTypeObject PyODictKeys_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"odict_keys", /* tp_name */
0, /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
odictkeys_iter, /* tp_iter */
0, /* tp_iternext */
odictkeys_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&PyDictKeys_Type, /* tp_base */
};
static PyObject *
odictkeys_new(PyObject *od, PyObject *Py_UNUSED(ignored))
{
return _PyDictView_New(od, &PyODictKeys_Type);
}
/* items() */
static PyObject *
odictitems_iter(PyObject *op)
{
_PyDictViewObject *dv = (_PyDictViewObject*)op;
if (dv->dv_dict == NULL) {
Py_RETURN_NONE;
}
return odictiter_new(_PyODictObject_CAST(dv->dv_dict),
_odict_ITER_KEYS|_odict_ITER_VALUES);
}
static PyObject *
odictitems_reversed(PyObject *op, PyObject *Py_UNUSED(ignored))
{
_PyDictViewObject *dv = (_PyDictViewObject*)op;
if (dv->dv_dict == NULL) {
Py_RETURN_NONE;
}
return odictiter_new(_PyODictObject_CAST(dv->dv_dict),
_odict_ITER_KEYS|_odict_ITER_VALUES|_odict_ITER_REVERSED);
}
static PyMethodDef odictitems_methods[] = {
{"__reversed__", odictitems_reversed, METH_NOARGS, NULL},
{NULL, NULL} /* sentinel */
};
PyTypeObject PyODictItems_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"odict_items", /* tp_name */
0, /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
odictitems_iter, /* tp_iter */
0, /* tp_iternext */
odictitems_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&PyDictItems_Type, /* tp_base */
};
static PyObject *
odictitems_new(PyObject *od, PyObject *Py_UNUSED(ignored))
{
return _PyDictView_New(od, &PyODictItems_Type);
}
/* values() */
static PyObject *
odictvalues_iter(PyObject *op)
{
_PyDictViewObject *dv = (_PyDictViewObject*)op;
if (dv->dv_dict == NULL) {
Py_RETURN_NONE;
}
return odictiter_new(_PyODictObject_CAST(dv->dv_dict),
_odict_ITER_VALUES);
}
static PyObject *
odictvalues_reversed(PyObject *op, PyObject *Py_UNUSED(ignored))
{
_PyDictViewObject *dv = (_PyDictViewObject*)op;
if (dv->dv_dict == NULL) {
Py_RETURN_NONE;
}
return odictiter_new(_PyODictObject_CAST(dv->dv_dict),
_odict_ITER_VALUES|_odict_ITER_REVERSED);
}
static PyMethodDef odictvalues_methods[] = {
{"__reversed__", odictvalues_reversed, METH_NOARGS, NULL},
{NULL, NULL} /* sentinel */
};
PyTypeObject PyODictValues_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"odict_values", /* tp_name */
0, /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
odictvalues_iter, /* tp_iter */
0, /* tp_iternext */
odictvalues_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&PyDictValues_Type, /* tp_base */
};
static PyObject *
odictvalues_new(PyObject *od, PyObject *Py_UNUSED(ignored))
{
return _PyDictView_New(od, &PyODictValues_Type);
}
/* ----------------------------------------------
MutableMapping implementations
Mapping:
============ ===========
method uses
============ ===========
__contains__ __getitem__
__eq__ items
__getitem__ +
__iter__ +
__len__ +
__ne__ __eq__
get __getitem__
items ItemsView
keys KeysView
values ValuesView
============ ===========
ItemsView uses __len__, __iter__, and __getitem__.
KeysView uses __len__, __iter__, and __contains__.
ValuesView uses __len__, __iter__, and __getitem__.
MutableMapping:
============ ===========
method uses
============ ===========
__delitem__ +
__setitem__ +
clear popitem
pop __getitem__
__delitem__
popitem __iter__
_getitem__
__delitem__
setdefault __getitem__
__setitem__
update __setitem__
============ ===========
*/
static int
mutablemapping_add_pairs(PyObject *self, PyObject *pairs)
{
PyObject *pair, *iterator, *unexpected;
int res = 0;
iterator = PyObject_GetIter(pairs);
if (iterator == NULL)
return -1;
PyErr_Clear();
while ((pair = PyIter_Next(iterator)) != NULL) {
/* could be more efficient (see UNPACK_SEQUENCE in ceval.c) */
PyObject *key = NULL, *value = NULL;
PyObject *pair_iterator = PyObject_GetIter(pair);
if (pair_iterator == NULL)
goto Done;
key = PyIter_Next(pair_iterator);
if (key == NULL) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_ValueError,
"need more than 0 values to unpack");
goto Done;
}
value = PyIter_Next(pair_iterator);
if (value == NULL) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_ValueError,
"need more than 1 value to unpack");
goto Done;
}
unexpected = PyIter_Next(pair_iterator);
if (unexpected != NULL) {
Py_DECREF(unexpected);
PyErr_SetString(PyExc_ValueError,
"too many values to unpack (expected 2)");
goto Done;
}
else if (PyErr_Occurred())
goto Done;
res = PyObject_SetItem(self, key, value);
Done:
Py_DECREF(pair);
Py_XDECREF(pair_iterator);
Py_XDECREF(key);
Py_XDECREF(value);
if (PyErr_Occurred())
break;
}
Py_DECREF(iterator);
if (res < 0 || PyErr_Occurred() != NULL)
return -1;
else
return 0;
}
static int
mutablemapping_update_arg(PyObject *self, PyObject *arg)
{
int res = 0;
if (PyDict_CheckExact(arg)) {
PyObject *items = PyDict_Items(arg);
if (items == NULL) {
return -1;
}
res = mutablemapping_add_pairs(self, items);
Py_DECREF(items);
return res;
}
PyObject *func;
if (PyObject_GetOptionalAttr(arg, &_Py_ID(keys), &func) < 0) {
return -1;
}
if (func != NULL) {
PyObject *keys = _PyObject_CallNoArgs(func);
Py_DECREF(func);
if (keys == NULL) {
return -1;
}
PyObject *iterator = PyObject_GetIter(keys);
Py_DECREF(keys);
if (iterator == NULL) {
return -1;
}
PyObject *key;
while (res == 0 && (key = PyIter_Next(iterator))) {
PyObject *value = PyObject_GetItem(arg, key);
if (value != NULL) {
res = PyObject_SetItem(self, key, value);
Py_DECREF(value);
}
else {
res = -1;
}
Py_DECREF(key);
}
Py_DECREF(iterator);
if (res != 0 || PyErr_Occurred()) {
return -1;
}
return 0;
}
if (PyObject_GetOptionalAttr(arg, &_Py_ID(items), &func) < 0) {
return -1;
}
if (func != NULL) {
PyObject *items = _PyObject_CallNoArgs(func);
Py_DECREF(func);
if (items == NULL) {
return -1;
}
res = mutablemapping_add_pairs(self, items);
Py_DECREF(items);
return res;
}
res = mutablemapping_add_pairs(self, arg);
return res;
}
static PyObject *
mutablemapping_update(PyObject *self, PyObject *args, PyObject *kwargs)
{
int res;
/* first handle args, if any */
assert(args == NULL || PyTuple_Check(args));
Py_ssize_t len = (args != NULL) ? PyTuple_GET_SIZE(args) : 0;
if (len > 1) {
const char *msg = "update() takes at most 1 positional argument (%zd given)";
PyErr_Format(PyExc_TypeError, msg, len);
return NULL;
}
if (len) {
PyObject *other = PyTuple_GET_ITEM(args, 0); /* borrowed reference */
assert(other != NULL);
Py_INCREF(other);
res = mutablemapping_update_arg(self, other);
Py_DECREF(other);
if (res < 0) {
return NULL;
}
}
/* now handle kwargs */
assert(kwargs == NULL || PyDict_Check(kwargs));
if (kwargs != NULL && PyDict_GET_SIZE(kwargs)) {
PyObject *items = PyDict_Items(kwargs);
if (items == NULL)
return NULL;
res = mutablemapping_add_pairs(self, items);
Py_DECREF(items);
if (res == -1)
return NULL;
}
Py_RETURN_NONE;
}
/* implements the unicode (as opposed to string) version of the
built-in formatters for string, int, float. that is, the versions
of int.__float__, etc., that take and return unicode objects */
#include "Python.h"
#include "pycore_fileutils.h" // _Py_GetLocaleconvNumeric()
#include "pycore_long.h" // _PyLong_FormatWriter()
#include "pycore_unicodeobject.h" // PyUnicode_MAX_CHAR_VALUE()
#include <locale.h>
/* _PyUnicode_InsertThousandsGrouping() helper functions */
typedef struct {
const char *grouping;
char previous;
Py_ssize_t i; /* Where we're currently pointing in grouping. */
} GroupGenerator;
static void
GroupGenerator_init(GroupGenerator *self, const char *grouping)
{
self->grouping = grouping;
self->i = 0;
self->previous = 0;
}
/* Returns the next grouping, or 0 to signify end. */
static Py_ssize_t
GroupGenerator_next(GroupGenerator *self)
{
/* Note that we don't really do much error checking here. If a
grouping string contains just CHAR_MAX, for example, then just
terminate the generator. That shouldn't happen, but at least we
fail gracefully. */
switch (self->grouping[self->i]) {
case 0:
return self->previous;
case CHAR_MAX:
/* Stop the generator. */
return 0;
default: {
char ch = self->grouping[self->i];
self->previous = ch;
self->i++;
return (Py_ssize_t)ch;
}
}
}
/* Fill in some digits, leading zeros, and thousands separator. All
are optional, depending on when we're called. */
static void
InsertThousandsGrouping_fill(_PyUnicodeWriter *writer, Py_ssize_t *buffer_pos,
PyObject *digits, Py_ssize_t *digits_pos,
Py_ssize_t n_chars, Py_ssize_t n_zeros,
PyObject *thousands_sep, Py_ssize_t thousands_sep_len,
Py_UCS4 *maxchar, int forward)
{
if (!writer) {
/* if maxchar > 127, maxchar is already set */
if (*maxchar == 127 && thousands_sep) {
Py_UCS4 maxchar2 = PyUnicode_MAX_CHAR_VALUE(thousands_sep);
*maxchar = Py_MAX(*maxchar, maxchar2);
}
return;
}
if (thousands_sep) {
if (!forward) {
*buffer_pos -= thousands_sep_len;
}
/* Copy the thousands_sep chars into the buffer. */
_PyUnicode_FastCopyCharacters(writer->buffer, *buffer_pos,
thousands_sep, 0,
thousands_sep_len);
if (forward) {
*buffer_pos += thousands_sep_len;
}
}
if (!forward) {
*buffer_pos -= n_chars;
*digits_pos -= n_chars;
}
_PyUnicode_FastCopyCharacters(writer->buffer, *buffer_pos,
digits, *digits_pos,
n_chars);
if (forward) {
*buffer_pos += n_chars;
*digits_pos += n_chars;
}
if (n_zeros) {
if (!forward) {
*buffer_pos -= n_zeros;
}
int kind = PyUnicode_KIND(writer->buffer);
void *data = PyUnicode_DATA(writer->buffer);
_PyUnicode_Fill(kind, data, '0', *buffer_pos, n_zeros);
if (forward) {
*buffer_pos += n_zeros;
}
}
}
/**
* InsertThousandsGrouping:
* @writer: Unicode writer.
* @n_buffer: Number of characters in @buffer.
* @digits: Digits we're reading from. If count is non-NULL, this is unused.
* @d_pos: Start of digits string.
* @n_digits: The number of digits in the string, in which we want
* to put the grouping chars.
* @min_width: The minimum width of the digits in the output string.
* Output will be zero-padded on the left to fill.
* @grouping: see definition in localeconv().
* @thousands_sep: see definition in localeconv().
*
* There are 2 modes: counting and filling. If @writer is NULL,
* we are in counting mode, else filling mode.
* If counting, the required buffer size is returned.
* If filling, we know the buffer will be large enough, so we don't
* need to pass in the buffer size.
* Inserts thousand grouping characters (as defined by grouping and
* thousands_sep) into @writer.
*
* Return value: -1 on error, number of characters otherwise.
**/
static Py_ssize_t
_PyUnicode_InsertThousandsGrouping(
_PyUnicodeWriter *writer,
Py_ssize_t n_buffer,
PyObject *digits,
Py_ssize_t d_pos,
Py_ssize_t n_digits,
Py_ssize_t min_width,
const char *grouping,
PyObject *thousands_sep,
Py_UCS4 *maxchar,
int forward)
{
min_width = Py_MAX(0, min_width);
if (writer) {
assert(digits != NULL);
assert(maxchar == NULL);
}
else {
assert(digits == NULL);
assert(maxchar != NULL);
}
assert(0 <= d_pos);
assert(0 <= n_digits);
assert(grouping != NULL);
Py_ssize_t count = 0;
Py_ssize_t n_zeros;
int loop_broken = 0;
int use_separator = 0; /* First time through, don't append the
separator. They only go between
groups. */
Py_ssize_t buffer_pos;
Py_ssize_t digits_pos;
Py_ssize_t len;
Py_ssize_t n_chars;
Py_ssize_t remaining = n_digits; /* Number of chars remaining to
be looked at */
/* A generator that returns all of the grouping widths, until it
returns 0. */
GroupGenerator groupgen;
GroupGenerator_init(&groupgen, grouping);
const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
/* if digits are not grouped, thousands separator
should be an empty string */
assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
digits_pos = d_pos + (forward ? 0 : n_digits);
if (writer) {
buffer_pos = writer->pos + (forward ? 0 : n_buffer);
assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
}
else {
buffer_pos = forward ? 0 : n_buffer;
}
if (!writer) {
*maxchar = 127;
}
while ((len = GroupGenerator_next(&groupgen)) > 0) {
len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
n_zeros = Py_MAX(0, len - remaining);
n_chars = Py_MAX(0, Py_MIN(remaining, len));
/* Use n_zero zero's and n_chars chars */
/* Count only, don't do anything. */
count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
/* Copy into the writer. */
InsertThousandsGrouping_fill(writer, &buffer_pos,
digits, &digits_pos,
n_chars, n_zeros,
use_separator ? thousands_sep : NULL,
thousands_sep_len, maxchar, forward);
/* Use a separator next time. */
use_separator = 1;
remaining -= n_chars;
min_width -= len;
if (remaining <= 0 && min_width <= 0) {
loop_broken = 1;
break;
}
min_width -= thousands_sep_len;
}
if (!loop_broken) {
/* We left the loop without using a break statement. */
len = Py_MAX(Py_MAX(remaining, min_width), 1);
n_zeros = Py_MAX(0, len - remaining);
n_chars = Py_MAX(0, Py_MIN(remaining, len));
/* Use n_zero zero's and n_chars chars */
count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
/* Copy into the writer. */
InsertThousandsGrouping_fill(writer, &buffer_pos,
digits, &digits_pos,
n_chars, n_zeros,
use_separator ? thousands_sep : NULL,
thousands_sep_len, maxchar, forward);
}
return count;
}
/* Raises an exception about an unknown presentation type for this
* type. */
static void
unknown_presentation_type(Py_UCS4 presentation_type,
const char* type_name)
{
/* %c might be out-of-range, hence the two cases. */
if (presentation_type > 32 && presentation_type < 128)
PyErr_Format(PyExc_ValueError,
"Unknown format code '%c' "
"for object of type '%.200s'",
(char)presentation_type,
type_name);
else
PyErr_Format(PyExc_ValueError,
"Unknown format code '\\x%x' "
"for object of type '%.200s'",
(unsigned int)presentation_type,
type_name);
}
static void
invalid_thousands_separator_type(char specifier, Py_UCS4 presentation_type)
{
assert(specifier == ',' || specifier == '_');
if (presentation_type > 32 && presentation_type < 128)
PyErr_Format(PyExc_ValueError,
"Cannot specify '%c' with '%c'.",
specifier, (char)presentation_type);
else
PyErr_Format(PyExc_ValueError,
"Cannot specify '%c' with '\\x%x'.",
specifier, (unsigned int)presentation_type);
}
static void
invalid_comma_and_underscore(void)
{
PyErr_Format(PyExc_ValueError, "Cannot specify both ',' and '_'.");
}
/*
get_integer consumes 0 or more decimal digit characters from an
input string, updates *result with the corresponding positive
integer, and returns the number of digits consumed.
returns -1 on error.
*/
static int
get_integer(PyObject *str, Py_ssize_t *ppos, Py_ssize_t end,
Py_ssize_t *result)
{
Py_ssize_t accumulator, digitval, pos = *ppos;
int numdigits;
int kind = PyUnicode_KIND(str);
const void *data = PyUnicode_DATA(str);
accumulator = numdigits = 0;
for (; pos < end; pos++, numdigits++) {
digitval = Py_UNICODE_TODECIMAL(PyUnicode_READ(kind, data, pos));
if (digitval < 0)
break;
/*
Detect possible overflow before it happens:
accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if
accumulator > (PY_SSIZE_T_MAX - digitval) / 10.
*/
if (accumulator > (PY_SSIZE_T_MAX - digitval) / 10) {
PyErr_Format(PyExc_ValueError,
"Too many decimal digits in format string");
*ppos = pos;
return -1;
}
accumulator = accumulator * 10 + digitval;
}
*ppos = pos;
*result = accumulator;
return numdigits;
}
/************************************************************************/
/*********** standard format specifier parsing **************************/
/************************************************************************/
/* returns true if this character is a specifier alignment token */
Py_LOCAL_INLINE(int)
is_alignment_token(Py_UCS4 c)
{
switch (c) {
case '<': case '>': case '=': case '^':
return 1;
default:
return 0;
}
}
/* returns true if this character is a sign element */
Py_LOCAL_INLINE(int)
is_sign_element(Py_UCS4 c)
{
switch (c) {
case ' ': case '+': case '-':
return 1;
default:
return 0;
}
}
/* Locale type codes. LT_NO_LOCALE must be zero. */
enum LocaleType {
LT_NO_LOCALE = 0,
LT_DEFAULT_LOCALE = ',',
LT_UNDERSCORE_LOCALE = '_',
LT_UNDER_FOUR_LOCALE,
LT_CURRENT_LOCALE
};
typedef struct {
Py_UCS4 fill_char;
Py_UCS4 align;
int alternate;
int no_neg_0;
Py_UCS4 sign;
Py_ssize_t width;
enum LocaleType thousands_separators;
Py_ssize_t precision;
enum LocaleType frac_thousands_separator;
Py_UCS4 type;
} InternalFormatSpec;
/*
ptr points to the start of the format_spec, end points just past its end.
fills in format with the parsed information.
returns 1 on success, 0 on failure.
if failure, sets the exception
*/
static int
parse_internal_render_format_spec(PyObject *obj,
PyObject *format_spec,
Py_ssize_t start, Py_ssize_t end,
InternalFormatSpec *format,
char default_type,
char default_align)
{
Py_ssize_t pos = start;
int kind = PyUnicode_KIND(format_spec);
const void *data = PyUnicode_DATA(format_spec);
/* end-pos is used throughout this code to specify the length of
the input string */
#define READ_spec(index) PyUnicode_READ(kind, data, index)
Py_ssize_t consumed;
int align_specified = 0;
int fill_char_specified = 0;
format->fill_char = ' ';
format->align = default_align;
format->alternate = 0;
format->no_neg_0 = 0;
format->sign = '\0';
format->width = -1;
format->thousands_separators = LT_NO_LOCALE;
format->frac_thousands_separator = LT_NO_LOCALE;
format->precision = -1;
format->type = default_type;
/* If the second char is an alignment token,
then parse the fill char */
if (end-pos >= 2 && is_alignment_token(READ_spec(pos+1))) {
format->align = READ_spec(pos+1);
format->fill_char = READ_spec(pos);
fill_char_specified = 1;
align_specified = 1;
pos += 2;
}
else if (end-pos >= 1 && is_alignment_token(READ_spec(pos))) {
format->align = READ_spec(pos);
align_specified = 1;
++pos;
}
/* Parse the various sign options */
if (end-pos >= 1 && is_sign_element(READ_spec(pos))) {
format->sign = READ_spec(pos);
++pos;
}
/* If the next character is z, request coercion of negative 0.
Applies only to floats. */
if (end-pos >= 1 && READ_spec(pos) == 'z') {
format->no_neg_0 = 1;
++pos;
}
/* If the next character is #, we're in alternate mode. This only
applies to integers. */
if (end-pos >= 1 && READ_spec(pos) == '#') {
format->alternate = 1;
++pos;
}
/* The special case for 0-padding (backwards compat) */
if (!fill_char_specified && end-pos >= 1 && READ_spec(pos) == '0') {
format->fill_char = '0';
if (!align_specified && default_align == '>') {
format->align = '=';
}
++pos;
}
consumed = get_integer(format_spec, &pos, end, &format->width);
if (consumed == -1)
/* Overflow error. Exception already set. */
return 0;
/* If consumed is 0, we didn't consume any characters for the
width. In that case, reset the width to -1, because
get_integer() will have set it to zero. -1 is how we record
that the width wasn't specified. */
if (consumed == 0)
format->width = -1;
/* Comma signifies add thousands separators */
if (end-pos && READ_spec(pos) == ',') {
format->thousands_separators = LT_DEFAULT_LOCALE;
++pos;
}
/* Underscore signifies add thousands separators */
if (end-pos && READ_spec(pos) == '_') {
if (format->thousands_separators != LT_NO_LOCALE) {
invalid_comma_and_underscore();
return 0;
}
format->thousands_separators = LT_UNDERSCORE_LOCALE;
++pos;
}
if (end-pos && READ_spec(pos) == ',') {
if (format->thousands_separators == LT_UNDERSCORE_LOCALE) {
invalid_comma_and_underscore();
return 0;
}
}
/* Parse field precision */
if (end-pos && READ_spec(pos) == '.') {
++pos;
consumed = get_integer(format_spec, &pos, end, &format->precision);
if (consumed == -1)
/* Overflow error. Exception already set. */
return 0;
if (end-pos && READ_spec(pos) == ',') {
if (consumed == 0) {
format->precision = -1;
}
format->frac_thousands_separator = LT_DEFAULT_LOCALE;
++pos;
++consumed;
}
if (end-pos && READ_spec(pos) == '_') {
if (format->frac_thousands_separator != LT_NO_LOCALE) {
invalid_comma_and_underscore();
return 0;
}
if (consumed == 0) {
format->precision = -1;
}
format->frac_thousands_separator = LT_UNDERSCORE_LOCALE;
++pos;
++consumed;
}
if (end-pos && READ_spec(pos) == ',') {
if (format->frac_thousands_separator == LT_UNDERSCORE_LOCALE) {
invalid_comma_and_underscore();
return 0;
}
}
/* Not having a precision or underscore/comma after a dot
is an error. */
if (consumed == 0) {
PyErr_Format(PyExc_ValueError,
"Format specifier missing precision");
return 0;
}
}
/* Finally, parse the type field. */
if (end-pos > 1) {
/* More than one char remains, so this is an invalid format
specifier. */
/* Create a temporary object that contains the format spec we're
operating on. It's format_spec[start:end] (in Python syntax). */
PyObject* actual_format_spec = PyUnicode_FromKindAndData(kind,
(char*)data + kind*start,
end-start);
if (actual_format_spec != NULL) {
PyErr_Format(PyExc_ValueError,
"Invalid format specifier '%U' for object of type '%.200s'",
actual_format_spec, Py_TYPE(obj)->tp_name);
Py_DECREF(actual_format_spec);
}
return 0;
}
if (end-pos == 1) {
format->type = READ_spec(pos);
++pos;
}
/* Do as much validating as we can, just by looking at the format
specifier. Do not take into account what type of formatting
we're doing (int, float, string). */
if (format->thousands_separators) {
switch (format->type) {
case 'd':
case 'e':
case 'f':
case 'g':
case 'E':
case 'G':
case '%':
case 'F':
case '\0':
/* These are allowed. See PEP 378.*/
break;
case 'b':
case 'o':
case 'x':
case 'X':
/* Underscores are allowed in bin/oct/hex. See PEP 515. */
if (format->thousands_separators == LT_UNDERSCORE_LOCALE) {
/* Every four digits, not every three, in bin/oct/hex. */
format->thousands_separators = LT_UNDER_FOUR_LOCALE;
break;
}
_Py_FALLTHROUGH;
default:
invalid_thousands_separator_type(format->thousands_separators, format->type);
return 0;
}
}
if (format->type == 'n'
&& format->frac_thousands_separator != LT_NO_LOCALE)
{
invalid_thousands_separator_type(format->frac_thousands_separator,
format->type);
return 0;
}
assert (format->align <= 127);
assert (format->sign <= 127);
return 1;
}
/* Calculate the padding needed. */
static void
calc_padding(Py_ssize_t nchars, Py_ssize_t width, Py_UCS4 align,
Py_ssize_t *n_lpadding, Py_ssize_t *n_rpadding,
Py_ssize_t *n_total)
{
if (width >= 0) {
if (nchars > width)
*n_total = nchars;
else
*n_total = width;
}
else {
/* not specified, use all of the chars and no more */
*n_total = nchars;
}
/* Figure out how much leading space we need, based on the
aligning */
if (align == '>')
*n_lpadding = *n_total - nchars;
else if (align == '^')
*n_lpadding = (*n_total - nchars) / 2;
else if (align == '<' || align == '=')
*n_lpadding = 0;
else {
/* We should never have an unspecified alignment. */
Py_UNREACHABLE();
}
*n_rpadding = *n_total - nchars - *n_lpadding;
}
/* Do the padding, and return a pointer to where the caller-supplied
content goes. */
static int
fill_padding(_PyUnicodeWriter *writer,
Py_ssize_t nchars,
Py_UCS4 fill_char, Py_ssize_t n_lpadding,
Py_ssize_t n_rpadding)
{
Py_ssize_t pos;
/* Pad on left. */
if (n_lpadding) {
pos = writer->pos;
_PyUnicode_FastFill(writer->buffer, pos, n_lpadding, fill_char);
}
/* Pad on right. */
if (n_rpadding) {
pos = writer->pos + nchars + n_lpadding;
_PyUnicode_FastFill(writer->buffer, pos, n_rpadding, fill_char);
}
/* Pointer to the user content. */
writer->pos += n_lpadding;
return 0;
}
/************************************************************************/
/*********** common routines for numeric formatting *********************/
/************************************************************************/
/* Locale info needed for formatting integers and the part of floats
before and including the decimal. Note that locales only support
8-bit chars, not unicode. */
typedef struct {
PyObject *decimal_point;
PyObject *thousands_sep;
PyObject *frac_thousands_sep;
const char *grouping;
char *grouping_buffer;
} LocaleInfo;
#define LocaleInfo_STATIC_INIT {0, 0, 0, 0}
/* describes the layout for an integer, see the comment in
calc_number_widths() for details */
typedef struct {
Py_ssize_t n_lpadding;
Py_ssize_t n_prefix;
Py_ssize_t n_spadding;
Py_ssize_t n_rpadding;
char sign;
Py_ssize_t n_sign; /* number of digits needed for sign (0/1) */
Py_ssize_t n_grouped_digits; /* Space taken up by the digits, including
any grouping chars. */
Py_ssize_t n_decimal; /* 0 if only an integer */
Py_ssize_t n_remainder; /* Digits in decimal and/or exponent part,
excluding the decimal itself, if
present. */
Py_ssize_t n_frac;
Py_ssize_t n_grouped_frac_digits;
/* These 2 are not the widths of fields, but are needed by
STRINGLIB_GROUPING. */
Py_ssize_t n_digits; /* The number of digits before a decimal
or exponent. */
Py_ssize_t n_min_width; /* The min_width we used when we computed
the n_grouped_digits width. */
} NumberFieldWidths;
/* Given a number of the form:
digits[remainder]
where ptr points to the start and end points to the end, find where
the integer part ends. This could be a decimal, an exponent, both,
or neither.
If a decimal point is present, set *has_decimal and increment
remainder beyond it.
Results are undefined (but shouldn't crash) for improperly
formatted strings.
*/
static void
parse_number(PyObject *s, Py_ssize_t pos, Py_ssize_t end,
Py_ssize_t *n_remainder, Py_ssize_t *n_frac, int *has_decimal)
{
Py_ssize_t frac;
int kind = PyUnicode_KIND(s);
const void *data = PyUnicode_DATA(s);
while (pos<end && Py_ISDIGIT(PyUnicode_READ(kind, data, pos))) {
++pos;
}
frac = pos;
/* Does remainder start with a decimal point? */
*has_decimal = pos<end && PyUnicode_READ(kind, data, frac) == '.';
/* Skip the decimal point. */
if (*has_decimal) {
frac++;
pos++;
}
while (pos<end && Py_ISDIGIT(PyUnicode_READ(kind, data, pos))) {
++pos;
}
*n_frac = pos - frac;
*n_remainder = end - pos;
}
/* not all fields of format are used. for example, precision is
unused. should this take discrete params in order to be more clear
about what it does? or is passing a single format parameter easier
and more efficient enough to justify a little obfuscation?
Return -1 on error. */
static Py_ssize_t
calc_number_widths(NumberFieldWidths *spec, Py_ssize_t n_prefix,
Py_UCS4 sign_char, Py_ssize_t n_start,
Py_ssize_t n_end, Py_ssize_t n_remainder, Py_ssize_t n_frac,
int has_decimal, const LocaleInfo *locale,
const InternalFormatSpec *format, Py_UCS4 *maxchar)
{
Py_ssize_t n_non_digit_non_padding;
Py_ssize_t n_padding;
spec->n_digits = n_end - n_start - n_frac - n_remainder - (has_decimal?1:0);
spec->n_lpadding = 0;
spec->n_prefix = n_prefix;
spec->n_decimal = has_decimal ? PyUnicode_GET_LENGTH(locale->decimal_point) : 0;
spec->n_remainder = n_remainder;
spec->n_frac = n_frac;
spec->n_spadding = 0;
spec->n_rpadding = 0;
spec->sign = '\0';
spec->n_sign = 0;
/* the output will look like:
| |
| <lpadding> <sign> <prefix> <spadding> <grouped_digits> <decimal> <remainder> <rpadding> |
| |
sign is computed from format->sign and the actual
sign of the number
prefix is given (it's for the '0x' prefix)
digits is already known
the total width is either given, or computed from the
actual digits
only one of lpadding, spadding, and rpadding can be non-zero,
and it's calculated from the width and other fields
*/
/* compute the various parts we're going to write */
switch (format->sign) {
case '+':
/* always put a + or - */
spec->n_sign = 1;
spec->sign = (sign_char == '-' ? '-' : '+');
break;
case ' ':
spec->n_sign = 1;
spec->sign = (sign_char == '-' ? '-' : ' ');
break;
default:
/* Not specified, or the default (-) */
if (sign_char == '-') {
spec->n_sign = 1;
spec->sign = '-';
}
}
if (spec->n_frac == 0) {
spec->n_grouped_frac_digits = 0;
}
else {
Py_UCS4 grouping_maxchar;
spec->n_grouped_frac_digits = _PyUnicode_InsertThousandsGrouping(
NULL, 0,
NULL, 0, spec->n_frac,
spec->n_frac,
locale->grouping, locale->frac_thousands_sep, &grouping_maxchar, 1);
if (spec->n_grouped_frac_digits == -1) {
return -1;
}
*maxchar = Py_MAX(*maxchar, grouping_maxchar);
}
/* The number of chars used for non-digits and non-padding. */
n_non_digit_non_padding = spec->n_sign + spec->n_prefix + spec->n_decimal +
+ spec->n_frac + spec->n_remainder;
/* min_width can go negative, that's okay. format->width == -1 means
we don't care. */
if (format->fill_char == '0' && format->align == '=')
spec->n_min_width = (format->width - n_non_digit_non_padding
+ spec->n_frac - spec->n_grouped_frac_digits);
else
spec->n_min_width = 0;
if (spec->n_digits == 0)
/* This case only occurs when using 'c' formatting, we need
to special case it because the grouping code always wants
to have at least one character. */
spec->n_grouped_digits = 0;
else {
Py_UCS4 grouping_maxchar;
spec->n_grouped_digits = _PyUnicode_InsertThousandsGrouping(
NULL, 0,
NULL, 0, spec->n_digits,
spec->n_min_width,
locale->grouping, locale->thousands_sep, &grouping_maxchar, 0);
if (spec->n_grouped_digits == -1) {
return -1;
}
*maxchar = Py_MAX(*maxchar, grouping_maxchar);
}
/* Given the desired width and the total of digit and non-digit
space we consume, see if we need any padding. format->width can
be negative (meaning no padding), but this code still works in
that case. */
n_padding = format->width -
(n_non_digit_non_padding + spec->n_grouped_digits
+ spec->n_grouped_frac_digits - spec->n_frac);
if (n_padding > 0) {
/* Some padding is needed. Determine if it's left, space, or right. */
switch (format->align) {
case '<':
spec->n_rpadding = n_padding;
break;
case '^':
spec->n_lpadding = n_padding / 2;
spec->n_rpadding = n_padding - spec->n_lpadding;
break;
case '=':
spec->n_spadding = n_padding;
break;
case '>':
spec->n_lpadding = n_padding;
break;
default:
/* Shouldn't get here */
Py_UNREACHABLE();
}
}
if (spec->n_lpadding || spec->n_spadding || spec->n_rpadding)
*maxchar = Py_MAX(*maxchar, format->fill_char);
if (spec->n_decimal)
*maxchar = Py_MAX(*maxchar, PyUnicode_MAX_CHAR_VALUE(locale->decimal_point));
return spec->n_lpadding + spec->n_sign + spec->n_prefix +
spec->n_spadding + spec->n_grouped_digits + spec->n_decimal +
spec->n_grouped_frac_digits + spec->n_remainder + spec->n_rpadding;
}
/* Fill in the digit parts of a number's string representation,
as determined in calc_number_widths().
Return -1 on error, or 0 on success. */
static int
fill_number(_PyUnicodeWriter *writer, const NumberFieldWidths *spec,
PyObject *digits, Py_ssize_t d_start,
PyObject *prefix, Py_ssize_t p_start,
Py_UCS4 fill_char,
LocaleInfo *locale, int toupper)
{
/* Used to keep track of digits, decimal, and remainder. */
Py_ssize_t d_pos = d_start;
const int kind = writer->kind;
const void *data = writer->data;
Py_ssize_t r;
if (spec->n_lpadding) {
_PyUnicode_FastFill(writer->buffer,
writer->pos, spec->n_lpadding, fill_char);
writer->pos += spec->n_lpadding;
}
if (spec->n_sign == 1) {
PyUnicode_WRITE(kind, data, writer->pos, spec->sign);
writer->pos++;
}
if (spec->n_prefix) {
_PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
prefix, p_start,
spec->n_prefix);
if (toupper) {
Py_ssize_t t;
for (t = 0; t < spec->n_prefix; t++) {
Py_UCS4 c = PyUnicode_READ(kind, data, writer->pos + t);
c = Py_TOUPPER(c);
assert (c <= 127);
PyUnicode_WRITE(kind, data, writer->pos + t, c);
}
}
writer->pos += spec->n_prefix;
}
if (spec->n_spadding) {
_PyUnicode_FastFill(writer->buffer,
writer->pos, spec->n_spadding, fill_char);
writer->pos += spec->n_spadding;
}
/* Only for type 'c' special case, it has no digits. */
if (spec->n_digits != 0) {
/* Fill the digits with InsertThousandsGrouping. */
r = _PyUnicode_InsertThousandsGrouping(
writer, spec->n_grouped_digits,
digits, d_pos, spec->n_digits,
spec->n_min_width,
locale->grouping, locale->thousands_sep, NULL, 0);
if (r == -1)
return -1;
assert(r == spec->n_grouped_digits);
d_pos += spec->n_digits;
}
if (toupper) {
Py_ssize_t t;
for (t = 0; t < spec->n_grouped_digits; t++) {
Py_UCS4 c = PyUnicode_READ(kind, data, writer->pos + t);
c = Py_TOUPPER(c);
if (c > 127) {
PyErr_SetString(PyExc_SystemError, "non-ascii grouped digit");
return -1;
}
PyUnicode_WRITE(kind, data, writer->pos + t, c);
}
}
writer->pos += spec->n_grouped_digits;
if (spec->n_decimal) {
_PyUnicode_FastCopyCharacters(
writer->buffer, writer->pos,
locale->decimal_point, 0, spec->n_decimal);
writer->pos += spec->n_decimal;
d_pos += 1;
}
if (spec->n_frac) {
r = _PyUnicode_InsertThousandsGrouping(
writer, spec->n_grouped_frac_digits,
digits, d_pos, spec->n_frac, spec->n_frac,
locale->grouping, locale->frac_thousands_sep, NULL, 1);
if (r == -1) {
return -1;
}
assert(r == spec->n_grouped_frac_digits);
d_pos += spec->n_frac;
writer->pos += spec->n_grouped_frac_digits;
}
if (spec->n_remainder) {
_PyUnicode_FastCopyCharacters(
writer->buffer, writer->pos,
digits, d_pos, spec->n_remainder);
writer->pos += spec->n_remainder;
/* d_pos += spec->n_remainder; */
}
if (spec->n_rpadding) {
_PyUnicode_FastFill(writer->buffer,
writer->pos, spec->n_rpadding,
fill_char);
writer->pos += spec->n_rpadding;
}
return 0;
}
static const char no_grouping[1] = {CHAR_MAX};
/* Find the decimal point character(s?), thousands_separator(s?), and
grouping description, either for the current locale if type is
LT_CURRENT_LOCALE, a hard-coded locale if LT_DEFAULT_LOCALE or
LT_UNDERSCORE_LOCALE/LT_UNDER_FOUR_LOCALE, or none if LT_NO_LOCALE. */
static int
get_locale_info(enum LocaleType type, enum LocaleType frac_type,
LocaleInfo *locale_info)
{
switch (type) {
case LT_CURRENT_LOCALE: {
struct lconv *lc = localeconv();
if (_Py_GetLocaleconvNumeric(lc,
&locale_info->decimal_point,
&locale_info->thousands_sep) < 0) {
return -1;
}
/* localeconv() grouping can become a dangling pointer or point
to a different string if another thread calls localeconv() during
the string formatting. Copy the string to avoid this risk. */
locale_info->grouping_buffer = _PyMem_Strdup(lc->grouping);
if (locale_info->grouping_buffer == NULL) {
PyErr_NoMemory();
return -1;
}
locale_info->grouping = locale_info->grouping_buffer;
break;
}
case LT_DEFAULT_LOCALE:
case LT_UNDERSCORE_LOCALE:
case LT_UNDER_FOUR_LOCALE:
locale_info->decimal_point = PyUnicode_FromOrdinal('.');
locale_info->thousands_sep = PyUnicode_FromOrdinal(
type == LT_DEFAULT_LOCALE ? ',' : '_');
if (!locale_info->decimal_point || !locale_info->thousands_sep)
return -1;
if (type != LT_UNDER_FOUR_LOCALE)
locale_info->grouping = "\3"; /* Group every 3 characters. The
(implicit) trailing 0 means repeat
infinitely. */
else
locale_info->grouping = "\4"; /* Bin/oct/hex group every four. */
break;
case LT_NO_LOCALE:
locale_info->decimal_point = PyUnicode_FromOrdinal('.');
locale_info->thousands_sep = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
if (!locale_info->decimal_point || !locale_info->thousands_sep)
return -1;
locale_info->grouping = no_grouping;
break;
}
if (frac_type != LT_NO_LOCALE) {
locale_info->frac_thousands_sep = PyUnicode_FromOrdinal(
frac_type == LT_DEFAULT_LOCALE ? ',' : '_');
if (!locale_info->frac_thousands_sep) {
return -1;
}
if (locale_info->grouping == no_grouping) {
locale_info->grouping = "\3";
}
}
else {
locale_info->frac_thousands_sep = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
}
return 0;
}
static void
free_locale_info(LocaleInfo *locale_info)
{
Py_XDECREF(locale_info->decimal_point);
Py_XDECREF(locale_info->thousands_sep);
Py_XDECREF(locale_info->frac_thousands_sep);
PyMem_Free(locale_info->grouping_buffer);
}
/************************************************************************/
/*********** string formatting ******************************************/
/************************************************************************/
static int
format_string_internal(PyObject *value, const InternalFormatSpec *format,
_PyUnicodeWriter *writer)
{
Py_ssize_t lpad;
Py_ssize_t rpad;
Py_ssize_t total;
Py_ssize_t len;
int result = -1;
Py_UCS4 maxchar;
len = PyUnicode_GET_LENGTH(value);
/* sign is not allowed on strings */
if (format->sign != '\0') {
if (format->sign == ' ') {
PyErr_SetString(PyExc_ValueError,
"Space not allowed in string format specifier");
}
else {
PyErr_SetString(PyExc_ValueError,
"Sign not allowed in string format specifier");
}
goto done;
}
/* negative 0 coercion is not allowed on strings */
if (format->no_neg_0) {
PyErr_SetString(PyExc_ValueError,
"Negative zero coercion (z) not allowed in string format "
"specifier");
goto done;
}
/* alternate is not allowed on strings */
if (format->alternate) {
PyErr_SetString(PyExc_ValueError,
"Alternate form (#) not allowed in string format "
"specifier");
goto done;
}
/* '=' alignment not allowed on strings */
if (format->align == '=') {
PyErr_SetString(PyExc_ValueError,
"'=' alignment not allowed "
"in string format specifier");
goto done;
}
if ((format->width == -1 || format->width <= len)
&& (format->precision == -1 || format->precision >= len)) {
/* Fast path */
return _PyUnicodeWriter_WriteStr(writer, value);
}
/* if precision is specified, output no more that format.precision
characters */
if (format->precision >= 0 && len >= format->precision) {
len = format->precision;
}
calc_padding(len, format->width, format->align, &lpad, &rpad, &total);
maxchar = writer->maxchar;
if (lpad != 0 || rpad != 0)
maxchar = Py_MAX(maxchar, format->fill_char);
if (PyUnicode_MAX_CHAR_VALUE(value) > maxchar) {
Py_UCS4 valmaxchar = _PyUnicode_FindMaxChar(value, 0, len);
maxchar = Py_MAX(maxchar, valmaxchar);
}
/* allocate the resulting string */
if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1)
goto done;
/* Write into that space. First the padding. */
result = fill_padding(writer, len, format->fill_char, lpad, rpad);
if (result == -1)
goto done;
/* Then the source string. */
if (len) {
_PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
value, 0, len);
}
writer->pos += (len + rpad);
result = 0;
done:
return result;
}
/************************************************************************/
/*********** long formatting ********************************************/
/************************************************************************/
static int
format_long_internal(PyObject *value, const InternalFormatSpec *format,
_PyUnicodeWriter *writer)
{
int result = -1;
Py_UCS4 maxchar = 127;
PyObject *tmp = NULL;
Py_ssize_t inumeric_chars;
Py_UCS4 sign_char = '\0';
Py_ssize_t n_digits; /* count of digits need from the computed
string */
Py_ssize_t n_remainder = 0; /* Used only for 'c' formatting, which
produces non-digits */
Py_ssize_t n_prefix = 0; /* Count of prefix chars, (e.g., '0x') */
Py_ssize_t n_total;
Py_ssize_t prefix = 0;
NumberFieldWidths spec;
long x;
/* Locale settings, either from the actual locale or
from a hard-code pseudo-locale */
LocaleInfo locale = LocaleInfo_STATIC_INIT;
/* no precision allowed on integers */
if (format->precision != -1) {
PyErr_SetString(PyExc_ValueError,
"Precision not allowed in integer format specifier");
goto done;
}
/* no negative zero coercion on integers */
if (format->no_neg_0) {
PyErr_SetString(PyExc_ValueError,
"Negative zero coercion (z) not allowed in integer"
" format specifier");
goto done;
}
/* special case for character formatting */
if (format->type == 'c') {
/* error to specify a sign */
if (format->sign != '\0') {
PyErr_SetString(PyExc_ValueError,
"Sign not allowed with integer"
" format specifier 'c'");
goto done;
}
/* error to request alternate format */
if (format->alternate) {
PyErr_SetString(PyExc_ValueError,
"Alternate form (#) not allowed with integer"
" format specifier 'c'");
goto done;
}
/* taken from unicodeobject.c formatchar() */
/* Integer input truncated to a character */
x = PyLong_AsLong(value);
if (x == -1 && PyErr_Occurred())
goto done;
if (x < 0 || x > 0x10ffff) {
PyErr_SetString(PyExc_OverflowError,
"%c arg not in range(0x110000)");
goto done;
}
tmp = PyUnicode_FromOrdinal(x);
inumeric_chars = 0;
n_digits = 1;
maxchar = Py_MAX(maxchar, (Py_UCS4)x);
/* As a sort-of hack, we tell calc_number_widths that we only
have "remainder" characters. calc_number_widths thinks
these are characters that don't get formatted, only copied
into the output string. We do this for 'c' formatting,
because the characters are likely to be non-digits. */
n_remainder = 1;
}
else {
int base;
int leading_chars_to_skip = 0; /* Number of characters added by
PyNumber_ToBase that we want to
skip over. */
/* Compute the base and how many characters will be added by
PyNumber_ToBase */
switch (format->type) {
case 'b':
base = 2;
leading_chars_to_skip = 2; /* 0b */
break;
case 'o':
base = 8;
leading_chars_to_skip = 2; /* 0o */
break;
case 'x':
case 'X':
base = 16;
leading_chars_to_skip = 2; /* 0x */
break;
default: /* shouldn't be needed, but stops a compiler warning */
case 'd':
case 'n':
base = 10;
break;
}
if (format->sign != '+' && format->sign != ' '
&& format->width == -1
&& format->type != 'X' && format->type != 'n'
&& !format->thousands_separators
&& PyLong_CheckExact(value))
{
/* Fast path */
return _PyLong_FormatWriter(writer, value, base, format->alternate);
}
/* The number of prefix chars is the same as the leading
chars to skip */
if (format->alternate)
n_prefix = leading_chars_to_skip;
/* Do the hard part, converting to a string in a given base */
tmp = _PyLong_Format(value, base);
if (tmp == NULL)
goto done;
inumeric_chars = 0;
n_digits = PyUnicode_GET_LENGTH(tmp);
prefix = inumeric_chars;
/* Is a sign character present in the output? If so, remember it
and skip it */
if (PyUnicode_READ_CHAR(tmp, inumeric_chars) == '-') {
sign_char = '-';
++prefix;
++leading_chars_to_skip;
}
/* Skip over the leading chars (0x, 0b, etc.) */
n_digits -= leading_chars_to_skip;
inumeric_chars += leading_chars_to_skip;
}
/* Determine the grouping, separator, and decimal point, if any. */
if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
format->thousands_separators, 0,
&locale) == -1)
goto done;
/* Calculate how much memory we'll need. */
n_total = calc_number_widths(&spec, n_prefix, sign_char, inumeric_chars,
inumeric_chars + n_digits, n_remainder, 0, 0,
&locale, format, &maxchar);
if (n_total == -1) {
goto done;
}
/* Allocate the memory. */
if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1)
goto done;
/* Populate the memory. */
result = fill_number(writer, &spec,
tmp, inumeric_chars,
tmp, prefix, format->fill_char,
&locale, format->type == 'X');
done:
Py_XDECREF(tmp);
free_locale_info(&locale);
return result;
}
/************************************************************************/
/*********** float formatting *******************************************/
/************************************************************************/
/* much of this is taken from unicodeobject.c */
static int
format_float_internal(PyObject *value,
const InternalFormatSpec *format,
_PyUnicodeWriter *writer)
{
char *buf = NULL; /* buffer returned from PyOS_double_to_string */
Py_ssize_t n_digits;
Py_ssize_t n_remainder;
Py_ssize_t n_frac;
Py_ssize_t n_total;
int has_decimal;
double val;
int precision, default_precision = 6;
Py_UCS4 type = format->type;
int add_pct = 0;
Py_ssize_t index;
NumberFieldWidths spec;
int flags = 0;
int result = -1;
Py_UCS4 maxchar = 127;
Py_UCS4 sign_char = '\0';
int float_type; /* Used to see if we have a nan, inf, or regular float. */
PyObject *unicode_tmp = NULL;
/* Locale settings, either from the actual locale or
from a hard-code pseudo-locale */
LocaleInfo locale = LocaleInfo_STATIC_INIT;
if (format->precision > INT_MAX) {
PyErr_SetString(PyExc_ValueError, "precision too big");
goto done;
}
precision = (int)format->precision;
if (format->alternate)
flags |= Py_DTSF_ALT;
if (format->no_neg_0)
flags |= Py_DTSF_NO_NEG_0;
if (type == '\0') {
/* Omitted type specifier. Behaves in the same way as repr(x)
and str(x) if no precision is given, else like 'g', but with
at least one digit after the decimal point. */
flags |= Py_DTSF_ADD_DOT_0;
type = 'r';
default_precision = 0;
}
if (type == 'n')
/* 'n' is the same as 'g', except for the locale used to
format the result. We take care of that later. */
type = 'g';
val = PyFloat_AsDouble(value);
if (val == -1.0 && PyErr_Occurred())
goto done;
if (type == '%') {
type = 'f';
val *= 100;
add_pct = 1;
}
if (precision < 0)
precision = default_precision;
else if (type == 'r')
type = 'g';
/* Cast "type", because if we're in unicode we need to pass an
8-bit char. This is safe, because we've restricted what "type"
can be. */
buf = PyOS_double_to_string(val, (char)type, precision, flags,
&float_type);
if (buf == NULL)
goto done;
n_digits = strlen(buf);
if (add_pct) {
/* We know that buf has a trailing zero (since we just called
strlen() on it), and we don't use that fact any more. So we
can just write over the trailing zero. */
buf[n_digits] = '%';
n_digits += 1;
}
if (format->sign != '+' && format->sign != ' '
&& format->width == -1
&& format->type != 'n'
&& !format->thousands_separators
&& !format->frac_thousands_separator)
{
/* Fast path */
result = _PyUnicodeWriter_WriteASCIIString(writer, buf, n_digits);
PyMem_Free(buf);
return result;
}
/* Since there is no unicode version of PyOS_double_to_string,
just use the 8 bit version and then convert to unicode. */
unicode_tmp = _PyUnicode_FromASCII(buf, n_digits);
PyMem_Free(buf);
if (unicode_tmp == NULL)
goto done;
/* Is a sign character present in the output? If so, remember it
and skip it */
index = 0;
if (PyUnicode_READ_CHAR(unicode_tmp, index) == '-') {
sign_char = '-';
++index;
--n_digits;
}
/* Determine if we have any "remainder" (after the digits, might include
decimal or exponent or both (or neither)) */
parse_number(unicode_tmp, index, index + n_digits,
&n_remainder, &n_frac, &has_decimal);
/* Determine the grouping, separator, and decimal point, if any. */
if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
format->thousands_separators,
format->frac_thousands_separator,
&locale) == -1)
goto done;
/* Calculate how much memory we'll need. */
n_total = calc_number_widths(&spec, 0, sign_char, index,
index + n_digits, n_remainder, n_frac,
has_decimal, &locale, format, &maxchar);
if (n_total == -1) {
goto done;
}
/* Allocate the memory. */
if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1)
goto done;
/* Populate the memory. */
result = fill_number(writer, &spec,
unicode_tmp, index,
NULL, 0, format->fill_char,
&locale, 0);
done:
Py_XDECREF(unicode_tmp);
free_locale_info(&locale);
return result;
}
/************************************************************************/
/*********** complex formatting *****************************************/
/************************************************************************/
static int
format_complex_internal(PyObject *value,
const InternalFormatSpec *format,
_PyUnicodeWriter *writer)
{
double re;
double im;
char *re_buf = NULL; /* buffer returned from PyOS_double_to_string */
char *im_buf = NULL; /* buffer returned from PyOS_double_to_string */
InternalFormatSpec tmp_format = *format;
Py_ssize_t n_re_digits;
Py_ssize_t n_im_digits;
Py_ssize_t n_re_remainder;
Py_ssize_t n_im_remainder;
Py_ssize_t n_re_frac;
Py_ssize_t n_im_frac;
Py_ssize_t n_re_total;
Py_ssize_t n_im_total;
int re_has_decimal;
int im_has_decimal;
int precision, default_precision = 6;
Py_UCS4 type = format->type;
Py_ssize_t i_re;
Py_ssize_t i_im;
NumberFieldWidths re_spec;
NumberFieldWidths im_spec;
int flags = 0;
int result = -1;
Py_UCS4 maxchar = 127;
int rkind;
void *rdata;
Py_UCS4 re_sign_char = '\0';
Py_UCS4 im_sign_char = '\0';
int re_float_type; /* Used to see if we have a nan, inf, or regular float. */
int im_float_type;
int add_parens = 0;
int skip_re = 0;
Py_ssize_t lpad;
Py_ssize_t rpad;
Py_ssize_t total;
PyObject *re_unicode_tmp = NULL;
PyObject *im_unicode_tmp = NULL;
/* Locale settings, either from the actual locale or
from a hard-code pseudo-locale */
LocaleInfo locale = LocaleInfo_STATIC_INIT;
if (format->precision > INT_MAX) {
PyErr_SetString(PyExc_ValueError, "precision too big");
goto done;
}
precision = (int)format->precision;
/* Zero padding is not allowed. */
if (format->fill_char == '0') {
PyErr_SetString(PyExc_ValueError,
"Zero padding is not allowed in complex format "
"specifier");
goto done;
}
/* Neither is '=' alignment . */
if (format->align == '=') {
PyErr_SetString(PyExc_ValueError,
"'=' alignment flag is not allowed in complex format "
"specifier");
goto done;
}
re = PyComplex_RealAsDouble(value);
if (re == -1.0 && PyErr_Occurred())
goto done;
im = PyComplex_ImagAsDouble(value);
if (im == -1.0 && PyErr_Occurred())
goto done;
if (format->alternate)
flags |= Py_DTSF_ALT;
if (format->no_neg_0)
flags |= Py_DTSF_NO_NEG_0;
if (type == '\0') {
/* Omitted type specifier. Should be like str(self). */
type = 'r';
default_precision = 0;
if (re == 0.0 && copysign(1.0, re) == 1.0)
skip_re = 1;
else
add_parens = 1;
}
if (type == 'n')
/* 'n' is the same as 'g', except for the locale used to
format the result. We take care of that later. */
type = 'g';
if (precision < 0)
precision = default_precision;
else if (type == 'r')
type = 'g';
/* Cast "type", because if we're in unicode we need to pass an
8-bit char. This is safe, because we've restricted what "type"
can be. */
re_buf = PyOS_double_to_string(re, (char)type, precision, flags,
&re_float_type);
if (re_buf == NULL)
goto done;
im_buf = PyOS_double_to_string(im, (char)type, precision, flags,
&im_float_type);
if (im_buf == NULL)
goto done;
n_re_digits = strlen(re_buf);
n_im_digits = strlen(im_buf);
/* Since there is no unicode version of PyOS_double_to_string,
just use the 8 bit version and then convert to unicode. */
re_unicode_tmp = _PyUnicode_FromASCII(re_buf, n_re_digits);
if (re_unicode_tmp == NULL)
goto done;
i_re = 0;
im_unicode_tmp = _PyUnicode_FromASCII(im_buf, n_im_digits);
if (im_unicode_tmp == NULL)
goto done;
i_im = 0;
/* Is a sign character present in the output? If so, remember it
and skip it */
if (PyUnicode_READ_CHAR(re_unicode_tmp, i_re) == '-') {
re_sign_char = '-';
++i_re;
--n_re_digits;
}
if (PyUnicode_READ_CHAR(im_unicode_tmp, i_im) == '-') {
im_sign_char = '-';
++i_im;
--n_im_digits;
}
/* Determine if we have any "remainder" (after the digits, might include
decimal or exponent or both (or neither)) */
parse_number(re_unicode_tmp, i_re, i_re + n_re_digits,
&n_re_remainder, &n_re_frac, &re_has_decimal);
parse_number(im_unicode_tmp, i_im, i_im + n_im_digits,
&n_im_remainder, &n_im_frac, &im_has_decimal);
/* Determine the grouping, separator, and decimal point, if any. */
if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
format->thousands_separators,
format->frac_thousands_separator,
&locale) == -1)
goto done;
/* Turn off any padding. We'll do it later after we've composed
the numbers without padding. */
tmp_format.fill_char = '\0';
tmp_format.align = '<';
tmp_format.width = -1;
/* Calculate how much memory we'll need. */
n_re_total = calc_number_widths(&re_spec, 0, re_sign_char,
i_re, i_re + n_re_digits, n_re_remainder,
n_re_frac, re_has_decimal, &locale,
&tmp_format, &maxchar);
if (n_re_total == -1) {
goto done;
}
/* Same formatting, but always include a sign, unless the real part is
* going to be omitted, in which case we use whatever sign convention was
* requested by the original format. */
if (!skip_re)
tmp_format.sign = '+';
n_im_total = calc_number_widths(&im_spec, 0, im_sign_char,
i_im, i_im + n_im_digits, n_im_remainder,
n_im_frac, im_has_decimal, &locale,
&tmp_format, &maxchar);
if (n_im_total == -1) {
goto done;
}
if (skip_re)
n_re_total = 0;
/* Add 1 for the 'j', and optionally 2 for parens. */
calc_padding(n_re_total + n_im_total + 1 + add_parens * 2,
format->width, format->align, &lpad, &rpad, &total);
if (lpad || rpad)
maxchar = Py_MAX(maxchar, format->fill_char);
if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1)
goto done;
rkind = writer->kind;
rdata = writer->data;
/* Populate the memory. First, the padding. */
result = fill_padding(writer,
n_re_total + n_im_total + 1 + add_parens * 2,
format->fill_char, lpad, rpad);
if (result == -1)
goto done;
if (add_parens) {
PyUnicode_WRITE(rkind, rdata, writer->pos, '(');
writer->pos++;
}
if (!skip_re) {
result = fill_number(writer, &re_spec,
re_unicode_tmp, i_re,
NULL, 0,
0,
&locale, 0);
if (result == -1)
goto done;
}
result = fill_number(writer, &im_spec,
im_unicode_tmp, i_im,
NULL, 0,
0,
&locale, 0);
if (result == -1)
goto done;
PyUnicode_WRITE(rkind, rdata, writer->pos, 'j');
writer->pos++;
if (add_parens) {
PyUnicode_WRITE(rkind, rdata, writer->pos, ')');
writer->pos++;
}
writer->pos += rpad;
done:
PyMem_Free(re_buf);
PyMem_Free(im_buf);
Py_XDECREF(re_unicode_tmp);
Py_XDECREF(im_unicode_tmp);
free_locale_info(&locale);
return result;
}
/************************************************************************/
/*********** built in formatters ****************************************/
/************************************************************************/
static int
format_obj(PyObject *obj, _PyUnicodeWriter *writer)
{
PyObject *str;
int err;
str = PyObject_Str(obj);
if (str == NULL)
return -1;
err = _PyUnicodeWriter_WriteStr(writer, str);
Py_DECREF(str);
return err;
}
int
_PyUnicode_FormatAdvancedWriter(_PyUnicodeWriter *writer,
PyObject *obj,
PyObject *format_spec,
Py_ssize_t start, Py_ssize_t end)
{
InternalFormatSpec format;
assert(PyUnicode_Check(obj));
/* check for the special case of zero length format spec, make
it equivalent to str(obj) */
if (start == end) {
if (PyUnicode_CheckExact(obj))
return _PyUnicodeWriter_WriteStr(writer, obj);
else
return format_obj(obj, writer);
}
/* parse the format_spec */
if (!parse_internal_render_format_spec(obj, format_spec, start, end,
&format, 's', '<'))
return -1;
/* type conversion? */
switch (format.type) {
case 's':
/* no type conversion needed, already a string. do the formatting */
return format_string_internal(obj, &format, writer);
default:
/* unknown */
unknown_presentation_type(format.type, Py_TYPE(obj)->tp_name);
return -1;
}
}
int
_PyLong_FormatAdvancedWriter(_PyUnicodeWriter *writer,
PyObject *obj,
PyObject *format_spec,
Py_ssize_t start, Py_ssize_t end)
{
PyObject *tmp = NULL;
InternalFormatSpec format;
int result = -1;
/* check for the special case of zero length format spec, make
it equivalent to str(obj) */
if (start == end) {
if (PyLong_CheckExact(obj))
return _PyLong_FormatWriter(writer, obj, 10, 0);
else
return format_obj(obj, writer);
}
/* parse the format_spec */
if (!parse_internal_render_format_spec(obj, format_spec, start, end,
&format, 'd', '>'))
goto done;
/* type conversion? */
switch (format.type) {
case 'b':
case 'c':
case 'd':
case 'o':
case 'x':
case 'X':
case 'n':
/* no type conversion needed, already an int. do the formatting */
result = format_long_internal(obj, &format, writer);
break;
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
case '%':
/* convert to float */
tmp = PyNumber_Float(obj);
if (tmp == NULL)
goto done;
result = format_float_internal(tmp, &format, writer);
break;
default:
/* unknown */
unknown_presentation_type(format.type, Py_TYPE(obj)->tp_name);
goto done;
}
done:
Py_XDECREF(tmp);
return result;
}
int
_PyFloat_FormatAdvancedWriter(_PyUnicodeWriter *writer,
PyObject *obj,
PyObject *format_spec,
Py_ssize_t start, Py_ssize_t end)
{
InternalFormatSpec format;
/* check for the special case of zero length format spec, make
it equivalent to str(obj) */
if (start == end)
return format_obj(obj, writer);
/* parse the format_spec */
if (!parse_internal_render_format_spec(obj, format_spec, start, end,
&format, '\0', '>'))
return -1;
/* type conversion? */
switch (format.type) {
case '\0': /* No format code: like 'g', but with at least one decimal. */
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
case 'n':
case '%':
/* no conversion, already a float. do the formatting */
return format_float_internal(obj, &format, writer);
default:
/* unknown */
unknown_presentation_type(format.type, Py_TYPE(obj)->tp_name);
return -1;
}
}
int
_PyComplex_FormatAdvancedWriter(_PyUnicodeWriter *writer,
PyObject *obj,
PyObject *format_spec,
Py_ssize_t start, Py_ssize_t end)
{
InternalFormatSpec format;
/* check for the special case of zero length format spec, make
it equivalent to str(obj) */
if (start == end)
return format_obj(obj, writer);
/* parse the format_spec */
if (!parse_internal_render_format_spec(obj, format_spec, start, end,
&format, '\0', '>'))
return -1;
/* type conversion? */
switch (format.type) {
case '\0': /* No format code: like 'g', but with at least one decimal. */
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
case 'n':
/* no conversion, already a complex. do the formatting */
return format_complex_internal(obj, &format, writer);
default:
/* unknown */
unknown_presentation_type(format.type, Py_TYPE(obj)->tp_name);
return -1;
}
}
/* enumerate object */
#include "Python.h"
#include "pycore_call.h" // _PyObject_CallNoArgs()
#include "pycore_long.h" // _PyLong_GetOne()
#include "pycore_modsupport.h" // _PyArg_NoKwnames()
#include "pycore_object.h" // _PyObject_GC_TRACK()
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString
#include "pycore_tuple.h" // _PyTuple_Recycle()
#include "clinic/enumobject.c.h"
/*[clinic input]
class enumerate "enumobject *" "&PyEnum_Type"
class reversed "reversedobject *" "&PyReversed_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d2dfdf1a88c88975]*/
typedef struct {
PyObject_HEAD
Py_ssize_t en_index; /* current index of enumeration */
PyObject* en_sit; /* secondary iterator of enumeration */
PyObject* en_result; /* result tuple */
PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */
PyObject* one; /* borrowed reference */
} enumobject;
#define _enumobject_CAST(op) ((enumobject *)(op))
/*[clinic input]
@classmethod
enumerate.__new__ as enum_new
iterable: object
an object supporting iteration
start: object = 0
Return an enumerate object.
The enumerate object yields pairs containing a count (from start, which
defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
[clinic start generated code]*/
static PyObject *
enum_new_impl(PyTypeObject *type, PyObject *iterable, PyObject *start)
/*[clinic end generated code: output=e95e6e439f812c10 input=782e4911efcb8acf]*/
{
enumobject *en;
en = (enumobject *)type->tp_alloc(type, 0);
if (en == NULL)
return NULL;
if (start != NULL) {
start = PyNumber_Index(start);
if (start == NULL) {
Py_DECREF(en);
return NULL;
}
assert(PyLong_Check(start));
en->en_index = PyLong_AsSsize_t(start);
if (en->en_index == -1 && PyErr_Occurred()) {
PyErr_Clear();
en->en_index = PY_SSIZE_T_MAX;
en->en_longindex = start;
} else {
en->en_longindex = NULL;
Py_DECREF(start);
}
} else {
en->en_index = 0;
en->en_longindex = NULL;
}
en->en_sit = PyObject_GetIter(iterable);
if (en->en_sit == NULL) {
Py_DECREF(en);
return NULL;
}
en->en_result = PyTuple_Pack(2, Py_None, Py_None);
if (en->en_result == NULL) {
Py_DECREF(en);
return NULL;
}
en->one = _PyLong_GetOne(); /* borrowed reference */
return (PyObject *)en;
}
static int check_keyword(PyObject *kwnames, int index,
const char *name)
{
PyObject *kw = PyTuple_GET_ITEM(kwnames, index);
if (!_PyUnicode_EqualToASCIIString(kw, name)) {
PyErr_Format(PyExc_TypeError,
"'%S' is an invalid keyword argument for enumerate()", kw);
return 0;
}
return 1;
}
// TODO: Use AC when bpo-43447 is supported
static PyObject *
enumerate_vectorcall(PyObject *type, PyObject *const *args,
size_t nargsf, PyObject *kwnames)
{
PyTypeObject *tp = _PyType_CAST(type);
Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
Py_ssize_t nkwargs = 0;
if (kwnames != NULL) {
nkwargs = PyTuple_GET_SIZE(kwnames);
}
// Manually implement enumerate(iterable, start=...)
if (nargs + nkwargs == 2) {
if (nkwargs == 1) {
if (!check_keyword(kwnames, 0, "start")) {
return NULL;
}
} else if (nkwargs == 2) {
PyObject *kw0 = PyTuple_GET_ITEM(kwnames, 0);
if (_PyUnicode_EqualToASCIIString(kw0, "start")) {
if (!check_keyword(kwnames, 1, "iterable")) {
return NULL;
}
return enum_new_impl(tp, args[1], args[0]);
}
if (!check_keyword(kwnames, 0, "iterable") ||
!check_keyword(kwnames, 1, "start")) {
return NULL;
}
}
return enum_new_impl(tp, args[0], args[1]);
}
if (nargs + nkwargs == 1) {
if (nkwargs == 1 && !check_keyword(kwnames, 0, "iterable")) {
return NULL;
}
return enum_new_impl(tp, args[0], NULL);
}
if (nargs == 0) {
PyErr_SetString(PyExc_TypeError,
"enumerate() missing required argument 'iterable'");
return NULL;
}
PyErr_Format(PyExc_TypeError,
"enumerate() takes at most 2 arguments (%d given)", nargs + nkwargs);
return NULL;
}
static void
enum_dealloc(PyObject *op)
{
enumobject *en = _enumobject_CAST(op);
PyObject_GC_UnTrack(en);
Py_XDECREF(en->en_sit);
Py_XDECREF(en->en_result);
Py_XDECREF(en->en_longindex);
Py_TYPE(en)->tp_free(en);
}
static int
enum_traverse(PyObject *op, visitproc visit, void *arg)
{
enumobject *en = _enumobject_CAST(op);
Py_VISIT(en->en_sit);
Py_VISIT(en->en_result);
Py_VISIT(en->en_longindex);
return 0;
}
// increment en_longindex with lock held, return the next index to be used
// or NULL on error
static inline PyObject *
increment_longindex_lock_held(enumobject *en)
{
PyObject *next_index = en->en_longindex;
if (next_index == NULL) {
next_index = PyLong_FromSsize_t(PY_SSIZE_T_MAX);
if (next_index == NULL) {
return NULL;
}
}
assert(next_index != NULL);
PyObject *stepped_up = PyNumber_Add(next_index, en->one);
if (stepped_up == NULL) {
return NULL;
}
en->en_longindex = stepped_up;
return next_index;
}
static PyObject *
enum_next_long(enumobject *en, PyObject* next_item)
{
PyObject *result = en->en_result;
PyObject *next_index;
PyObject *old_index;
PyObject *old_item;
Py_BEGIN_CRITICAL_SECTION(en);
next_index = increment_longindex_lock_held(en);
Py_END_CRITICAL_SECTION();
if (next_index == NULL) {
Py_DECREF(next_item);
return NULL;
}
if (_PyObject_IsUniquelyReferenced(result)) {
Py_INCREF(result);
old_index = PyTuple_GET_ITEM(result, 0);
old_item = PyTuple_GET_ITEM(result, 1);
PyTuple_SET_ITEM(result, 0, next_index);
PyTuple_SET_ITEM(result, 1, next_item);
Py_DECREF(old_index);
Py_DECREF(old_item);
// bpo-42536: The GC may have untracked this result tuple. Since we're
// recycling it, make sure it's tracked again:
_PyTuple_Recycle(result);
return result;
}
result = PyTuple_New(2);
if (result == NULL) {
Py_DECREF(next_index);
Py_DECREF(next_item);
return NULL;
}
PyTuple_SET_ITEM(result, 0, next_index);
PyTuple_SET_ITEM(result, 1, next_item);
return result;
}
static PyObject *
enum_next(PyObject *op)
{
enumobject *en = _enumobject_CAST(op);
PyObject *next_index;
PyObject *next_item;
PyObject *result = en->en_result;
PyObject *it = en->en_sit;
PyObject *old_index;
PyObject *old_item;
next_item = (*Py_TYPE(it)->tp_iternext)(it);
if (next_item == NULL)
return NULL;
Py_ssize_t en_index = FT_ATOMIC_LOAD_SSIZE_RELAXED(en->en_index);
if (en_index == PY_SSIZE_T_MAX)
return enum_next_long(en, next_item);
next_index = PyLong_FromSsize_t(en_index);
if (next_index == NULL) {
Py_DECREF(next_item);
return NULL;
}
FT_ATOMIC_STORE_SSIZE_RELAXED(en->en_index, en_index + 1);
if (_PyObject_IsUniquelyReferenced(result)) {
Py_INCREF(result);
old_index = PyTuple_GET_ITEM(result, 0);
old_item = PyTuple_GET_ITEM(result, 1);
PyTuple_SET_ITEM(result, 0, next_index);
PyTuple_SET_ITEM(result, 1, next_item);
Py_DECREF(old_index);
Py_DECREF(old_item);
// bpo-42536: The GC may have untracked this result tuple. Since we're
// recycling it, make sure it's tracked again:
_PyTuple_Recycle(result);
return result;
}
result = PyTuple_New(2);
if (result == NULL) {
Py_DECREF(next_index);
Py_DECREF(next_item);
return NULL;
}
PyTuple_SET_ITEM(result, 0, next_index);
PyTuple_SET_ITEM(result, 1, next_item);
return result;
}
static PyObject *
enum_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
{
enumobject *en = _enumobject_CAST(op);
PyObject *result;
Py_BEGIN_CRITICAL_SECTION(en);
if (en->en_longindex != NULL)
result = Py_BuildValue("O(OO)", Py_TYPE(en), en->en_sit, en->en_longindex);
else
result = Py_BuildValue("O(On)", Py_TYPE(en), en->en_sit, en->en_index);
Py_END_CRITICAL_SECTION();
return result;
}
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
static PyMethodDef enum_methods[] = {
{"__reduce__", enum_reduce, METH_NOARGS, reduce_doc},
{"__class_getitem__", Py_GenericAlias,
METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
{NULL, NULL} /* sentinel */
};
PyTypeObject PyEnum_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"enumerate", /* tp_name */
sizeof(enumobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
enum_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE, /* tp_flags */
enum_new__doc__, /* tp_doc */
enum_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
enum_next, /* tp_iternext */
enum_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
enum_new, /* tp_new */
PyObject_GC_Del, /* tp_free */
.tp_vectorcall = enumerate_vectorcall
};
/* Reversed Object ***************************************************************/
typedef struct {
PyObject_HEAD
Py_ssize_t index;
PyObject* seq;
} reversedobject;
#define _reversedobject_CAST(op) ((reversedobject *)(op))
/*[clinic input]
@classmethod
reversed.__new__ as reversed_new
object as seq: object
/
Return a reverse iterator over the values of the given sequence.
[clinic start generated code]*/
static PyObject *
reversed_new_impl(PyTypeObject *type, PyObject *seq)
/*[clinic end generated code: output=f7854cc1df26f570 input=4781869729e3ba50]*/
{
Py_ssize_t n;
PyObject *reversed_meth;
reversedobject *ro;
reversed_meth = _PyObject_LookupSpecial(seq, &_Py_ID(__reversed__));
if (reversed_meth == Py_None) {
Py_DECREF(reversed_meth);
PyErr_Format(PyExc_TypeError,
"'%.200s' object is not reversible",
Py_TYPE(seq)->tp_name);
return NULL;
}
if (reversed_meth != NULL) {
PyObject *res = _PyObject_CallNoArgs(reversed_meth);
Py_DECREF(reversed_meth);
return res;
}
else if (PyErr_Occurred())
return NULL;
if (!PySequence_Check(seq)) {
PyErr_Format(PyExc_TypeError,
"'%.200s' object is not reversible",
Py_TYPE(seq)->tp_name);
return NULL;
}
n = PySequence_Size(seq);
if (n == -1)
return NULL;
ro = (reversedobject *)type->tp_alloc(type, 0);
if (ro == NULL)
return NULL;
ro->index = n-1;
ro->seq = Py_NewRef(seq);
return (PyObject *)ro;
}
static PyObject *
reversed_vectorcall(PyObject *type, PyObject * const*args,
size_t nargsf, PyObject *kwnames)
{
if (!_PyArg_NoKwnames("reversed", kwnames)) {
return NULL;
}
Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
if (!_PyArg_CheckPositional("reversed", nargs, 1, 1)) {
return NULL;
}
return reversed_new_impl(_PyType_CAST(type), args[0]);
}
static void
reversed_dealloc(PyObject *op)
{
reversedobject *ro = _reversedobject_CAST(op);
PyObject_GC_UnTrack(ro);
Py_XDECREF(ro->seq);
Py_TYPE(ro)->tp_free(ro);
}
static int
reversed_traverse(PyObject *op, visitproc visit, void *arg)
{
reversedobject *ro = _reversedobject_CAST(op);
Py_VISIT(ro->seq);
return 0;
}
static PyObject *
reversed_next(PyObject *op)
{
reversedobject *ro = _reversedobject_CAST(op);
PyObject *item;
Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(ro->index);
if (index >= 0) {
item = PySequence_GetItem(ro->seq, index);
if (item != NULL) {
FT_ATOMIC_STORE_SSIZE_RELAXED(ro->index, index - 1);
return item;
}
if (PyErr_ExceptionMatches(PyExc_IndexError) ||
PyErr_ExceptionMatches(PyExc_StopIteration))
PyErr_Clear();
}
FT_ATOMIC_STORE_SSIZE_RELAXED(ro->index, -1);
#ifndef Py_GIL_DISABLED
Py_CLEAR(ro->seq);
#endif
return NULL;
}
static PyObject *
reversed_len(PyObject *op, PyObject *Py_UNUSED(ignored))
{
reversedobject *ro = _reversedobject_CAST(op);
Py_ssize_t position, seqsize;
Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(ro->index);
if (index == -1)
return PyLong_FromLong(0);
assert(ro->seq != NULL);
seqsize = PySequence_Size(ro->seq);
if (seqsize == -1)
return NULL;
position = index + 1;
return PyLong_FromSsize_t((seqsize < position) ? 0 : position);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyObject *
reversed_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
{
reversedobject *ro = _reversedobject_CAST(op);
Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(ro->index);
if (index != -1) {
return Py_BuildValue("O(O)n", Py_TYPE(ro), ro->seq, ro->index);
}
else {
return Py_BuildValue("O(())", Py_TYPE(ro));
}
}
static PyObject *
reversed_setstate(PyObject *op, PyObject *state)
{
reversedobject *ro = _reversedobject_CAST(op);
Py_ssize_t index = PyLong_AsSsize_t(state);
if (index == -1 && PyErr_Occurred())
return NULL;
Py_ssize_t ro_index = FT_ATOMIC_LOAD_SSIZE_RELAXED(ro->index);
// if the iterator is exhausted we do not set the state
// this is for backwards compatibility reasons. in practice this situation
// will not occur, see gh-120971
if (ro_index != -1) {
Py_ssize_t n = PySequence_Size(ro->seq);
if (n < 0)
return NULL;
if (index < -1)
index = -1;
else if (index > n-1)
index = n-1;
FT_ATOMIC_STORE_SSIZE_RELAXED(ro->index, index);
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
static PyMethodDef reversediter_methods[] = {
{"__length_hint__", reversed_len, METH_NOARGS, length_hint_doc},
{"__reduce__", reversed_reduce, METH_NOARGS, reduce_doc},
{"__setstate__", reversed_setstate, METH_O, setstate_doc},
{NULL, NULL} /* sentinel */
};
PyTypeObject PyReversed_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"reversed", /* tp_name */
sizeof(reversedobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
reversed_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE, /* tp_flags */
reversed_new__doc__, /* tp_doc */
reversed_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
reversed_next, /* tp_iternext */
reversediter_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
reversed_new, /* tp_new */
PyObject_GC_Del, /* tp_free */
.tp_vectorcall = reversed_vectorcall,
};
/* Function object implementation */
#include "Python.h"
#include "pycore_code.h" // _PyCode_VerifyStateless()
#include "pycore_dict.h" // _Py_INCREF_DICT()
#include "pycore_function.h" // _PyFunction_Vectorcall
#include "pycore_long.h" // _PyLong_GetOne()
#include "pycore_modsupport.h" // _PyArg_NoKeywords()
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
#include "pycore_pyerrors.h" // _PyErr_Occurred()
#include "pycore_setobject.h" // _PySet_NextEntry()
#include "pycore_stats.h"
#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#include "pycore_optimizer.h" // _PyJit_Tracer_InvalidateDependency
static const char *
func_event_name(PyFunction_WatchEvent event) {
switch (event) {
#define CASE(op) \
case PyFunction_EVENT_##op: \
return "PyFunction_EVENT_" #op;
PY_FOREACH_FUNC_EVENT(CASE)
#undef CASE
}
Py_UNREACHABLE();
}
static void
notify_func_watchers(PyInterpreterState *interp, PyFunction_WatchEvent event,
PyFunctionObject *func, PyObject *new_value)
{
uint8_t bits = interp->active_func_watchers;
int i = 0;
while (bits) {
assert(i < FUNC_MAX_WATCHERS);
if (bits & 1) {
PyFunction_WatchCallback cb = interp->func_watchers[i];
// callback must be non-null if the watcher bit is set
assert(cb != NULL);
if (cb(event, func, new_value) < 0) {
PyErr_FormatUnraisable(
"Exception ignored in %s watcher callback for function %U at %p",
func_event_name(event), func->func_qualname, func);
}
}
i++;
bits >>= 1;
}
}
static inline void
handle_func_event(PyFunction_WatchEvent event, PyFunctionObject *func,
PyObject *new_value)
{
assert(Py_REFCNT(func) > 0);
PyInterpreterState *interp = _PyInterpreterState_GET();
assert(interp->_initialized);
if (interp->active_func_watchers) {
notify_func_watchers(interp, event, func, new_value);
}
switch (event) {
case PyFunction_EVENT_MODIFY_CODE:
case PyFunction_EVENT_MODIFY_DEFAULTS:
case PyFunction_EVENT_MODIFY_KWDEFAULTS:
case PyFunction_EVENT_MODIFY_QUALNAME:
RARE_EVENT_INTERP_INC(interp, func_modification);
break;
default:
break;
}
}
int
PyFunction_AddWatcher(PyFunction_WatchCallback callback)
{
PyInterpreterState *interp = _PyInterpreterState_GET();
assert(interp->_initialized);
for (int i = 0; i < FUNC_MAX_WATCHERS; i++) {
if (interp->func_watchers[i] == NULL) {
interp->func_watchers[i] = callback;
interp->active_func_watchers |= (1 << i);
return i;
}
}
PyErr_SetString(PyExc_RuntimeError, "no more func watcher IDs available");
return -1;
}
int
PyFunction_ClearWatcher(int watcher_id)
{
PyInterpreterState *interp = _PyInterpreterState_GET();
if (watcher_id < 0 || watcher_id >= FUNC_MAX_WATCHERS) {
PyErr_Format(PyExc_ValueError, "invalid func watcher ID %d",
watcher_id);
return -1;
}
if (!interp->func_watchers[watcher_id]) {
PyErr_Format(PyExc_ValueError, "no func watcher set for ID %d",
watcher_id);
return -1;
}
interp->func_watchers[watcher_id] = NULL;
interp->active_func_watchers &= ~(1 << watcher_id);
return 0;
}
PyFunctionObject *
_PyFunction_FromConstructor(PyFrameConstructor *constr)
{
PyObject *module;
if (PyDict_GetItemRef(constr->fc_globals, &_Py_ID(__name__), &module) < 0) {
return NULL;
}
PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
if (op == NULL) {
Py_XDECREF(module);
return NULL;
}
_Py_INCREF_DICT(constr->fc_globals);
op->func_globals = constr->fc_globals;
_Py_INCREF_BUILTINS(constr->fc_builtins);
op->func_builtins = constr->fc_builtins;
op->func_name = Py_NewRef(constr->fc_name);
op->func_qualname = Py_NewRef(constr->fc_qualname);
_Py_INCREF_CODE((PyCodeObject *)constr->fc_code);
op->func_code = constr->fc_code;
op->func_defaults = Py_XNewRef(constr->fc_defaults);
op->func_kwdefaults = Py_XNewRef(constr->fc_kwdefaults);
op->func_closure = Py_XNewRef(constr->fc_closure);
op->func_doc = Py_NewRef(Py_None);
op->func_dict = NULL;
op->func_weakreflist = NULL;
op->func_module = module;
op->func_annotations = NULL;
op->func_annotate = NULL;
op->func_typeparams = NULL;
op->vectorcall = _PyFunction_Vectorcall;
op->func_version = FUNC_VERSION_UNSET;
// NOTE: functions created via FrameConstructor do not use deferred
// reference counting because they are typically not part of cycles
// nor accessed by multiple threads.
_PyObject_GC_TRACK(op);
handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
return op;
}
PyObject *
PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
{
assert(globals != NULL);
assert(PyDict_Check(globals));
_Py_INCREF_DICT(globals);
PyCodeObject *code_obj = (PyCodeObject *)code;
_Py_INCREF_CODE(code_obj);
assert(code_obj->co_name != NULL);
PyObject *name = Py_NewRef(code_obj->co_name);
if (!qualname) {
qualname = code_obj->co_qualname;
}
assert(qualname != NULL);
Py_INCREF(qualname);
PyObject *consts = code_obj->co_consts;
assert(PyTuple_Check(consts));
PyObject *doc;
if (code_obj->co_flags & CO_HAS_DOCSTRING) {
assert(PyTuple_Size(consts) >= 1);
doc = PyTuple_GetItem(consts, 0);
if (!PyUnicode_Check(doc)) {
doc = Py_None;
}
}
else {
doc = Py_None;
}
Py_INCREF(doc);
// __module__: Use globals['__name__'] if it exists, or NULL.
PyObject *module;
PyObject *builtins = NULL;
if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &module) < 0) {
goto error;
}
builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
if (builtins == NULL) {
goto error;
}
PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
if (op == NULL) {
goto error;
}
/* Note: No failures from this point on, since func_dealloc() does not
expect a partially-created object. */
op->func_globals = globals;
op->func_builtins = builtins;
op->func_name = name;
op->func_qualname = qualname;
op->func_code = (PyObject*)code_obj;
op->func_defaults = NULL; // No default positional arguments
op->func_kwdefaults = NULL; // No default keyword arguments
op->func_closure = NULL;
op->func_doc = doc;
op->func_dict = NULL;
op->func_weakreflist = NULL;
op->func_module = module;
op->func_annotations = NULL;
op->func_annotate = NULL;
op->func_typeparams = NULL;
op->vectorcall = _PyFunction_Vectorcall;
op->func_version = FUNC_VERSION_UNSET;
if (((code_obj->co_flags & CO_NESTED) == 0) ||
(code_obj->co_flags & CO_METHOD)) {
// Use deferred reference counting for top-level functions, but not
// nested functions because they are more likely to capture variables,
// which makes prompt deallocation more important.
//
// Nested methods (functions defined in class scope) are also deferred,
// since they will likely be cleaned up by GC anyway.
_PyObject_SetDeferredRefcount((PyObject *)op);
}
_PyObject_GC_TRACK(op);
handle_func_event(PyFunction_EVENT_CREATE, op, NULL);
return (PyObject *)op;
error:
Py_DECREF(globals);
Py_DECREF(code_obj);
Py_DECREF(name);
Py_DECREF(qualname);
Py_DECREF(doc);
Py_XDECREF(module);
Py_XDECREF(builtins);
return NULL;
}
/*
(This is purely internal documentation. There are no public APIs here.)
Function (and code) versions
----------------------------
The Tier 1 specializer generates CALL variants that can be invalidated
by changes to critical function attributes:
- __code__
- __defaults__
- __kwdefaults__
- __closure__
For this purpose function objects have a 32-bit func_version member
that the specializer writes to the specialized instruction's inline
cache and which is checked by a guard on the specialized instructions.
The MAKE_FUNCTION bytecode sets func_version from the code object's
co_version field. The latter is initialized from a counter in the
interpreter state (interp->func_state.next_version) and never changes.
When this counter overflows, it remains zero and the specializer loses
the ability to specialize calls to new functions.
The func_version is reset to zero when any of the critical attributes
is modified; after this point the specializer will no longer specialize
calls to this function, and the guard will always fail.
The function and code version cache
-----------------------------------
The Tier 2 optimizer now has a problem, since it needs to find the
function and code objects given only the version number from the inline
cache. Our solution is to maintain a cache mapping version numbers to
function and code objects. To limit the cache size we could hash
the version number, but for now we simply use it modulo the table size.
There are some corner cases (e.g. generator expressions) where we will
be unable to find the function object in the cache but we can still
find the code object. For this reason the cache stores both the
function object and the code object.
The cache doesn't contain strong references; cache entries are
invalidated whenever the function or code object is deallocated.
Invariants
----------
These should hold at any time except when one of the cache-mutating
functions is running.
- For any slot s at index i:
- s->func == NULL or s->func->func_version % FUNC_VERSION_CACHE_SIZE == i
- s->code == NULL or s->code->co_version % FUNC_VERSION_CACHE_SIZE == i
if s->func != NULL, then s->func->func_code == s->code
*/
#ifndef Py_GIL_DISABLED
static inline struct _func_version_cache_item *
get_cache_item(PyInterpreterState *interp, uint32_t version)
{
return interp->func_state.func_version_cache +
(version % FUNC_VERSION_CACHE_SIZE);
}
#endif
void
_PyFunction_SetVersion(PyFunctionObject *func, uint32_t version)
{
assert(func->func_version == FUNC_VERSION_UNSET);
assert(version >= FUNC_VERSION_FIRST_VALID);
// This should only be called from MAKE_FUNCTION. No code is specialized
// based on the version, so we do not need to stop the world to set it.
func->func_version = version;
#ifndef Py_GIL_DISABLED
PyInterpreterState *interp = _PyInterpreterState_GET();
struct _func_version_cache_item *slot = get_cache_item(interp, version);
slot->func = func;
slot->code = func->func_code;
#endif
}
static void
func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
{
if (func->func_version < FUNC_VERSION_FIRST_VALID) {
// Version was never set or has already been cleared.
return;
}
#ifndef Py_GIL_DISABLED
struct _func_version_cache_item *slot =
get_cache_item(interp, func->func_version);
if (slot->func == func) {
slot->func = NULL;
// Leave slot->code alone, there may be use for it.
}
#endif
func->func_version = FUNC_VERSION_CLEARED;
}
// Called when any of the critical function attributes are changed
static void
_PyFunction_ClearVersion(PyFunctionObject *func)
{
if (func->func_version < FUNC_VERSION_FIRST_VALID) {
// Version was never set or has already been cleared.
return;
}
PyInterpreterState *interp = _PyInterpreterState_GET();
_PyEval_StopTheWorld(interp);
func_clear_version(interp, func);
_PyEval_StartTheWorld(interp);
}
void
_PyFunction_ClearCodeByVersion(uint32_t version)
{
#ifndef Py_GIL_DISABLED
PyInterpreterState *interp = _PyInterpreterState_GET();
struct _func_version_cache_item *slot = get_cache_item(interp, version);
if (slot->code) {
assert(PyCode_Check(slot->code));
PyCodeObject *code = (PyCodeObject *)slot->code;
if (code->co_version == version) {
slot->code = NULL;
slot->func = NULL;
}
}
#endif
}
PyFunctionObject *
_PyFunction_LookupByVersion(uint32_t version, PyObject **p_code)
{
#ifdef Py_GIL_DISABLED
return NULL;
#else
PyInterpreterState *interp = _PyInterpreterState_GET();
struct _func_version_cache_item *slot = get_cache_item(interp, version);
if (slot->code) {
assert(PyCode_Check(slot->code));
PyCodeObject *code = (PyCodeObject *)slot->code;
if (code->co_version == version) {
*p_code = slot->code;
}
}
else {
*p_code = NULL;
}
if (slot->func && slot->func->func_version == version) {
assert(slot->func->func_code == slot->code);
return slot->func;
}
return NULL;
#endif
}
uint32_t
_PyFunction_GetVersionForCurrentState(PyFunctionObject *func)
{
return func->func_version;
}
PyObject *
PyFunction_New(PyObject *code, PyObject *globals)
{
return PyFunction_NewWithQualName(code, globals, NULL);
}
PyObject *
PyFunction_GetCode(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_code;
}
PyObject *
PyFunction_GetGlobals(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_globals;
}
PyObject *
PyFunction_GetModule(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_module;
}
PyObject *
PyFunction_GetDefaults(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_defaults;
}
int
PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return -1;
}
if (defaults == Py_None)
defaults = NULL;
else if (defaults && PyTuple_Check(defaults)) {
Py_INCREF(defaults);
}
else {
PyErr_SetString(PyExc_SystemError, "non-tuple default args");
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS,
(PyFunctionObject *) op, defaults);
_PyFunction_ClearVersion((PyFunctionObject *)op);
Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults);
return 0;
}
void
PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
{
assert(func != NULL);
_PyFunction_ClearVersion(func);
func->vectorcall = vectorcall;
}
PyObject *
PyFunction_GetKwDefaults(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_kwdefaults;
}
int
PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return -1;
}
if (defaults == Py_None)
defaults = NULL;
else if (defaults && PyDict_Check(defaults)) {
Py_INCREF(defaults);
}
else {
PyErr_SetString(PyExc_SystemError,
"non-dict keyword only default args");
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS,
(PyFunctionObject *) op, defaults);
_PyFunction_ClearVersion((PyFunctionObject *)op);
Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults);
return 0;
}
PyObject *
PyFunction_GetClosure(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return ((PyFunctionObject *) op) -> func_closure;
}
int
PyFunction_SetClosure(PyObject *op, PyObject *closure)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return -1;
}
if (closure == Py_None)
closure = NULL;
else if (PyTuple_Check(closure)) {
Py_INCREF(closure);
}
else {
PyErr_Format(PyExc_SystemError,
"expected tuple for closure, got '%.100s'",
Py_TYPE(closure)->tp_name);
return -1;
}
_PyFunction_ClearVersion((PyFunctionObject *)op);
Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure);
return 0;
}
static PyObject *
func_get_annotation_dict(PyFunctionObject *op)
{
if (op->func_annotations == NULL) {
if (op->func_annotate == NULL || !PyCallable_Check(op->func_annotate)) {
Py_RETURN_NONE;
}
PyObject *one = _PyLong_GetOne();
PyObject *ann_dict = _PyObject_CallOneArg(op->func_annotate, one);
if (ann_dict == NULL) {
return NULL;
}
if (!PyDict_Check(ann_dict)) {
PyErr_Format(PyExc_TypeError,
"__annotate__() must return a dict, not %T",
ann_dict);
Py_DECREF(ann_dict);
return NULL;
}
Py_XSETREF(op->func_annotations, ann_dict);
return ann_dict;
}
if (PyTuple_CheckExact(op->func_annotations)) {
PyObject *ann_tuple = op->func_annotations;
PyObject *ann_dict = PyDict_New();
if (ann_dict == NULL) {
return NULL;
}
assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0);
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) {
int err = PyDict_SetItem(ann_dict,
PyTuple_GET_ITEM(ann_tuple, i),
PyTuple_GET_ITEM(ann_tuple, i + 1));
if (err < 0) {
Py_DECREF(ann_dict);
return NULL;
}
}
Py_SETREF(op->func_annotations, ann_dict);
}
assert(PyDict_Check(op->func_annotations));
return op->func_annotations;
}
PyObject *
PyFunction_GetAnnotations(PyObject *op)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return NULL;
}
return func_get_annotation_dict((PyFunctionObject *)op);
}
int
PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
{
if (!PyFunction_Check(op)) {
PyErr_BadInternalCall();
return -1;
}
if (annotations == Py_None)
annotations = NULL;
else if (annotations && PyDict_Check(annotations)) {
Py_INCREF(annotations);
}
else {
PyErr_SetString(PyExc_SystemError,
"non-dict annotations");
return -1;
}
PyFunctionObject *func = (PyFunctionObject *)op;
Py_XSETREF(func->func_annotations, annotations);
Py_CLEAR(func->func_annotate);
return 0;
}
/* Methods */
#define OFF(x) offsetof(PyFunctionObject, x)
static PyMemberDef func_memberlist[] = {
{"__closure__", _Py_T_OBJECT, OFF(func_closure), Py_READONLY},
{"__doc__", _Py_T_OBJECT, OFF(func_doc), 0},
{"__globals__", _Py_T_OBJECT, OFF(func_globals), Py_READONLY},
{"__module__", _Py_T_OBJECT, OFF(func_module), 0},
{"__builtins__", _Py_T_OBJECT, OFF(func_builtins), Py_READONLY},
{NULL} /* Sentinel */
};
/*[clinic input]
class function "PyFunctionObject *" "&PyFunction_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/
#include "clinic/funcobject.c.h"
static PyObject *
func_get_code(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) {
return NULL;
}
return Py_NewRef(op->func_code);
}
static int
func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
/* Not legal to del f.func_code or to set it to anything
* other than a code object. */
if (value == NULL || !PyCode_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__code__ must be set to a code object");
return -1;
}
if (PySys_Audit("object.__setattr__", "OsO",
op, "__code__", value) < 0) {
return -1;
}
int nfree = ((PyCodeObject *)value)->co_nfreevars;
Py_ssize_t nclosure = (op->func_closure == NULL ? 0 :
PyTuple_GET_SIZE(op->func_closure));
if (nclosure != nfree) {
PyErr_Format(PyExc_ValueError,
"%U() requires a code object with %zd free vars,"
" not %zd",
op->func_name,
nclosure, nfree);
return -1;
}
PyObject *func_code = PyFunction_GET_CODE(op);
int old_flags = ((PyCodeObject *)func_code)->co_flags;
int new_flags = ((PyCodeObject *)value)->co_flags;
int mask = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR;
if ((old_flags & mask) != (new_flags & mask)) {
if (PyErr_Warn(PyExc_DeprecationWarning,
"Assigning a code object of non-matching type is deprecated "
"(e.g., from a generator to a plain function)") < 0)
{
return -1;
}
}
handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
_PyFunction_ClearVersion(op);
Py_XSETREF(op->func_code, Py_NewRef(value));
return 0;
}
static PyObject *
func_get_name(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
return Py_NewRef(op->func_name);
}
static int
func_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
/* Not legal to del f.func_name or to set it to anything
* other than a string object. */
if (value == NULL || !PyUnicode_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__name__ must be set to a string object");
return -1;
}
Py_XSETREF(op->func_name, Py_NewRef(value));
return 0;
}
static PyObject *
func_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
return Py_NewRef(op->func_qualname);
}
static int
func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
/* Not legal to del f.__qualname__ or to set it to anything
* other than a string object. */
if (value == NULL || !PyUnicode_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__qualname__ must be set to a string object");
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, (PyFunctionObject *) op, value);
Py_XSETREF(op->func_qualname, Py_NewRef(value));
return 0;
}
static PyObject *
func_get_defaults(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) {
return NULL;
}
if (op->func_defaults == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(op->func_defaults);
}
static int
func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
/* Legal to del f.func_defaults.
* Can only set func_defaults to NULL or a tuple. */
PyFunctionObject *op = _PyFunction_CAST(self);
if (value == Py_None)
value = NULL;
if (value != NULL && !PyTuple_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__defaults__ must be set to a tuple object");
return -1;
}
if (value) {
if (PySys_Audit("object.__setattr__", "OsO",
op, "__defaults__", value) < 0) {
return -1;
}
} else if (PySys_Audit("object.__delattr__", "Os",
op, "__defaults__") < 0) {
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
_PyFunction_ClearVersion(op);
Py_XSETREF(op->func_defaults, Py_XNewRef(value));
return 0;
}
static PyObject *
func_get_kwdefaults(PyObject *self, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (PySys_Audit("object.__getattr__", "Os",
op, "__kwdefaults__") < 0) {
return NULL;
}
if (op->func_kwdefaults == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(op->func_kwdefaults);
}
static int
func_set_kwdefaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
{
PyFunctionObject *op = _PyFunction_CAST(self);
if (value == Py_None)
value = NULL;
/* Legal to del f.func_kwdefaults.
* Can only set func_kwdefaults to NULL or a dict. */
if (value != NULL && !PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__kwdefaults__ must be set to a dict object");
return -1;
}
if (value) {
if (PySys_Audit("object.__setattr__", "OsO",
op, "__kwdefaults__", value) < 0) {
return -1;
}
} else if (PySys_Audit("object.__delattr__", "Os",
op, "__kwdefaults__") < 0) {
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, op, value);
_PyFunction_ClearVersion(op);
Py_XSETREF(op->func_kwdefaults, Py_XNewRef(value));
return 0;
}
/*[clinic input]
@critical_section
@getter
function.__annotate__
Get the code object for a function.
[clinic start generated code]*/
static PyObject *
function___annotate___get_impl(PyFunctionObject *self)
/*[clinic end generated code: output=5ec7219ff2bda9e6 input=7f3db11e3c3329f3]*/
{
if (self->func_annotate == NULL) {
Py_RETURN_NONE;
}
return Py_NewRef(self->func_annotate);
}
/*[clinic input]
@critical_section
@setter
function.__annotate__
[clinic start generated code]*/
static int
function___annotate___set_impl(PyFunctionObject *self, PyObject *value)
/*[clinic end generated code: output=05b7dfc07ada66cd input=eb6225e358d97448]*/
{
if (value == NULL) {
PyErr_SetString(PyExc_TypeError,
"__annotate__ cannot be deleted");
return -1;
}
if (Py_IsNone(value)) {
Py_XSETREF(self->func_annotate, value);
return 0;
}
else if (PyCallable_Check(value)) {
Py_XSETREF(self->func_annotate, Py_XNewRef(value));
Py_CLEAR(self->func_annotations);
return 0;
}
else {
PyErr_SetString(PyExc_TypeError,
"__annotate__ must be callable or None");
return -1;
}
}
/*[clinic input]
@critical_section
@getter
function.__annotations__
Dict of annotations in a function object.
[clinic start generated code]*/
static PyObject *
function___annotations___get_impl(PyFunctionObject *self)
/*[clinic end generated code: output=a4cf4c884c934cbb input=92643d7186c1ad0c]*/
{
PyObject *d = NULL;
if (self->func_annotations == NULL &&
(self->func_annotate == NULL || !PyCallable_Check(self->func_annotate))) {
self->func_annotations = PyDict_New();
if (self->func_annotations == NULL)
return NULL;
}
d = func_get_annotation_dict(self);
return Py_XNewRef(d);
}
/*[clinic input]
@critical_section
@setter
function.__annotations__
[clinic start generated code]*/
static int
function___annotations___set_impl(PyFunctionObject *self, PyObject *value)
/*[clinic end generated code: output=a61795d4a95eede4 input=5302641f686f0463]*/
{
if (value == Py_None)
value = NULL;
/* Legal to del f.func_annotations.
* Can only set func_annotations to NULL (through C api)
* or a dict. */
if (value != NULL && !PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__annotations__ must be set to a dict object");
return -1;
}
Py_XSETREF(self->func_annotations, Py_XNewRef(value));
Py_CLEAR(self->func_annotate);
return 0;
}
/*[clinic input]
@critical_section
@getter
function.__type_params__
Get the declared type parameters for a function.
[clinic start generated code]*/
static PyObject *
function___type_params___get_impl(PyFunctionObject *self)
/*[clinic end generated code: output=eb844d7ffca517a8 input=0864721484293724]*/
{
if (self->func_typeparams == NULL) {
return PyTuple_New(0);
}
assert(PyTuple_Check(self->func_typeparams));
return Py_NewRef(self->func_typeparams);
}
/*[clinic input]
@critical_section
@setter
function.__type_params__
[clinic start generated code]*/
static int
function___type_params___set_impl(PyFunctionObject *self, PyObject *value)
/*[clinic end generated code: output=038b4cda220e56fb input=3862fbd4db2b70e8]*/
{
/* Not legal to del f.__type_params__ or to set it to anything
* other than a tuple object. */
if (value == NULL || !PyTuple_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__type_params__ must be set to a tuple");
return -1;
}
Py_XSETREF(self->func_typeparams, Py_NewRef(value));
return 0;
}
PyObject *
_Py_set_function_type_params(PyThreadState *Py_UNUSED(ignored), PyObject *func,
PyObject *type_params)
{
assert(PyFunction_Check(func));
assert(PyTuple_Check(type_params));
PyFunctionObject *f = (PyFunctionObject *)func;
Py_XSETREF(f->func_typeparams, Py_NewRef(type_params));
return Py_NewRef(func);
}
static PyGetSetDef func_getsetlist[] = {
{"__code__", func_get_code, func_set_code},
{"__defaults__", func_get_defaults, func_set_defaults},
{"__kwdefaults__", func_get_kwdefaults, func_set_kwdefaults},
FUNCTION___ANNOTATIONS___GETSETDEF
FUNCTION___ANNOTATE___GETSETDEF
{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
{"__name__", func_get_name, func_set_name},
{"__qualname__", func_get_qualname, func_set_qualname},
FUNCTION___TYPE_PARAMS___GETSETDEF
{NULL} /* Sentinel */
};
/* function.__new__() maintains the following invariants for closures.
The closure must correspond to the free variables of the code object.
if len(code.co_freevars) == 0:
closure = NULL
else:
len(closure) == len(code.co_freevars)
for every elt in closure, type(elt) == cell
*/
/*[clinic input]
@classmethod
function.__new__ as func_new
code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
a code object
globals: object(subclass_of="&PyDict_Type")
the globals dictionary
name: object = None
a string that overrides the name from the code object
argdefs as defaults: object = None
a tuple that specifies the default argument values
closure: object = None
a tuple that supplies the bindings for free variables
kwdefaults: object = None
a dictionary that specifies the default keyword argument values
Create a function object.
[clinic start generated code]*/
static PyObject *
func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals,
PyObject *name, PyObject *defaults, PyObject *closure,
PyObject *kwdefaults)
/*[clinic end generated code: output=de72f4c22ac57144 input=20c9c9f04ad2d3f2]*/
{
PyFunctionObject *newfunc;
Py_ssize_t nclosure;
if (name != Py_None && !PyUnicode_Check(name)) {
PyErr_SetString(PyExc_TypeError,
"arg 3 (name) must be None or string");
return NULL;
}
if (defaults != Py_None && !PyTuple_Check(defaults)) {
PyErr_SetString(PyExc_TypeError,
"arg 4 (defaults) must be None or tuple");
return NULL;
}
if (!PyTuple_Check(closure)) {
if (code->co_nfreevars && closure == Py_None) {
PyErr_SetString(PyExc_TypeError,
"arg 5 (closure) must be tuple");
return NULL;
}
else if (closure != Py_None) {
PyErr_SetString(PyExc_TypeError,
"arg 5 (closure) must be None or tuple");
return NULL;
}
}
if (kwdefaults != Py_None && !PyDict_Check(kwdefaults)) {
PyErr_SetString(PyExc_TypeError,
"arg 6 (kwdefaults) must be None or dict");
return NULL;
}
/* check that the closure is well-formed */
nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
if (code->co_nfreevars != nclosure)
return PyErr_Format(PyExc_ValueError,
"%U requires closure of length %zd, not %zd",
code->co_name, code->co_nfreevars, nclosure);
if (nclosure) {
Py_ssize_t i;
for (i = 0; i < nclosure; i++) {
PyObject *o = PyTuple_GET_ITEM(closure, i);
if (!PyCell_Check(o)) {
return PyErr_Format(PyExc_TypeError,
"arg 5 (closure) expected cell, found %s",
Py_TYPE(o)->tp_name);
}
}
}
if (PySys_Audit("function.__new__", "O", code) < 0) {
return NULL;
}
newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
globals);
if (newfunc == NULL) {
return NULL;
}
if (name != Py_None) {
Py_SETREF(newfunc->func_name, Py_NewRef(name));
}
if (defaults != Py_None) {
newfunc->func_defaults = Py_NewRef(defaults);
}
if (closure != Py_None) {
newfunc->func_closure = Py_NewRef(closure);
}
if (kwdefaults != Py_None) {
newfunc->func_kwdefaults = Py_NewRef(kwdefaults);
}
return (PyObject *)newfunc;
}
static int
func_clear(PyObject *self)
{
PyFunctionObject *op = _PyFunction_CAST(self);
func_clear_version(_PyInterpreterState_GET(), op);
PyObject *globals = op->func_globals;
op->func_globals = NULL;
if (globals != NULL) {
_Py_DECREF_DICT(globals);
}
PyObject *builtins = op->func_builtins;
op->func_builtins = NULL;
if (builtins != NULL) {
_Py_DECREF_BUILTINS(builtins);
}
Py_CLEAR(op->func_module);
Py_CLEAR(op->func_defaults);
Py_CLEAR(op->func_kwdefaults);
Py_CLEAR(op->func_doc);
Py_CLEAR(op->func_dict);
Py_CLEAR(op->func_closure);
Py_CLEAR(op->func_annotations);
Py_CLEAR(op->func_annotate);
Py_CLEAR(op->func_typeparams);
// Don't Py_CLEAR(op->func_code), since code is always required
// to be non-NULL. Similarly, name and qualname shouldn't be NULL.
// However, name and qualname could be str subclasses, so they
// could have reference cycles. The solution is to replace them
// with a genuinely immutable string.
Py_SETREF(op->func_name, &_Py_STR(empty));
Py_SETREF(op->func_qualname, &_Py_STR(empty));
return 0;
}
static void
func_dealloc(PyObject *self)
{
PyFunctionObject *op = _PyFunction_CAST(self);
_PyObject_ResurrectStart(self);
handle_func_event(PyFunction_EVENT_DESTROY, op, NULL);
if (_PyObject_ResurrectEnd(self)) {
return;
}
#if _Py_TIER2
_Py_Executors_InvalidateDependency(_PyInterpreterState_GET(), self, 1);
_PyJit_Tracer_InvalidateDependency(_PyThreadState_GET(), self);
#endif
_PyObject_GC_UNTRACK(op);
FT_CLEAR_WEAKREFS(self, op->func_weakreflist);
(void)func_clear((PyObject*)op);
// These aren't cleared by func_clear().
_Py_DECREF_CODE((PyCodeObject *)op->func_code);
Py_DECREF(op->func_name);
Py_DECREF(op->func_qualname);
PyObject_GC_Del(op);
}
static PyObject*
func_repr(PyObject *self)
{
PyFunctionObject *op = _PyFunction_CAST(self);
return PyUnicode_FromFormat("<function %U at %p>",
op->func_qualname, op);
}
static int
func_traverse(PyObject *self, visitproc visit, void *arg)
{
PyFunctionObject *f = _PyFunction_CAST(self);
Py_VISIT(f->func_code);
Py_VISIT(f->func_globals);
Py_VISIT(f->func_builtins);
Py_VISIT(f->func_module);
Py_VISIT(f->func_defaults);
Py_VISIT(f->func_kwdefaults);
Py_VISIT(f->func_doc);
Py_VISIT(f->func_name);
Py_VISIT(f->func_dict);
Py_VISIT(f->func_closure);
Py_VISIT(f->func_annotations);
Py_VISIT(f->func_annotate);
Py_VISIT(f->func_typeparams);
Py_VISIT(f->func_qualname);
return 0;
}
/* Bind a function to an object */
static PyObject *
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
{
if (obj == Py_None || obj == NULL) {
return Py_NewRef(func);
}
return PyMethod_New(func, obj);
}
PyTypeObject PyFunction_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"function",
sizeof(PyFunctionObject),
0,
func_dealloc, /* tp_dealloc */
offsetof(PyFunctionObject, vectorcall), /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
func_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
PyVectorcall_Call, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_HAVE_VECTORCALL |
Py_TPFLAGS_METHOD_DESCRIPTOR, /* tp_flags */
func_new__doc__, /* tp_doc */
func_traverse, /* tp_traverse */
func_clear, /* tp_clear */
0, /* tp_richcompare */
offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
func_memberlist, /* tp_members */
func_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
func_descr_get, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
func_new, /* tp_new */
};
int
_PyFunction_VerifyStateless(PyThreadState *tstate, PyObject *func)
{
assert(!PyErr_Occurred());
assert(PyFunction_Check(func));
// Check the globals.
PyObject *globalsns = PyFunction_GET_GLOBALS(func);
if (globalsns != NULL && !PyDict_Check(globalsns)) {
_PyErr_Format(tstate, PyExc_TypeError,
"unsupported globals %R", globalsns);
return -1;
}
// Check the builtins.
PyObject *builtinsns = _PyFunction_GET_BUILTINS(func);
if (builtinsns != NULL && !PyDict_Check(builtinsns)) {
_PyErr_Format(tstate, PyExc_TypeError,
"unsupported builtins %R", builtinsns);
return -1;
}
// Disallow __defaults__.
PyObject *defaults = PyFunction_GET_DEFAULTS(func);
if (defaults != NULL) {
assert(PyTuple_Check(defaults)); // per PyFunction_New()
if (PyTuple_GET_SIZE(defaults) > 0) {
_PyErr_SetString(tstate, PyExc_ValueError,
"defaults not supported");
return -1;
}
}
// Disallow __kwdefaults__.
PyObject *kwdefaults = PyFunction_GET_KW_DEFAULTS(func);
if (kwdefaults != NULL) {
assert(PyDict_Check(kwdefaults)); // per PyFunction_New()
if (PyDict_Size(kwdefaults) > 0) {
_PyErr_SetString(tstate, PyExc_ValueError,
"keyword defaults not supported");
return -1;
}
}
// Disallow __closure__.
PyObject *closure = PyFunction_GET_CLOSURE(func);
if (closure != NULL) {
assert(PyTuple_Check(closure)); // per PyFunction_New()
if (PyTuple_GET_SIZE(closure) > 0) {
_PyErr_SetString(tstate, PyExc_ValueError, "closures not supported");
return -1;
}
}
// Check the code.
PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
if (_PyCode_VerifyStateless(tstate, co, NULL, globalsns, builtinsns) < 0) {
return -1;
}
return 0;
}
static int
functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name)
{
PyObject *value;
int res = PyObject_GetOptionalAttr(wrapped, name, &value);
if (value != NULL) {
res = PyObject_SetAttr(wrapper, name, value);
Py_DECREF(value);
}
return res;
}
// Similar to functools.wraps(wrapper, wrapped)
static int
functools_wraps(PyObject *wrapper, PyObject *wrapped)
{
#define COPY_ATTR(ATTR) \
do { \
if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \
return -1; \
} \
} while (0) \
COPY_ATTR(__module__);
COPY_ATTR(__name__);
COPY_ATTR(__qualname__);
COPY_ATTR(__doc__);
return 0;
#undef COPY_ATTR
}
// Used for wrapping __annotations__ and __annotate__ on classmethod
// and staticmethod objects.
static PyObject *
descriptor_get_wrapped_attribute(PyObject *wrapped, PyObject *obj, PyObject *name)
{
PyObject *dict = PyObject_GenericGetDict(obj, NULL);
if (dict == NULL) {
return NULL;
}
PyObject *res;
if (PyDict_GetItemRef(dict, name, &res) < 0) {
Py_DECREF(dict);
return NULL;
}
if (res != NULL) {
Py_DECREF(dict);
return res;
}
res = PyObject_GetAttr(wrapped, name);
if (res == NULL) {
Py_DECREF(dict);
return NULL;
}
if (PyDict_SetItem(dict, name, res) < 0) {
Py_DECREF(dict);
Py_DECREF(res);
return NULL;
}
Py_DECREF(dict);
return res;
}
static int
descriptor_set_wrapped_attribute(PyObject *oobj, PyObject *name, PyObject *value,
char *type_name)
{
PyObject *dict = PyObject_GenericGetDict(oobj, NULL);
if (dict == NULL) {
return -1;
}
if (value == NULL) {
if (PyDict_DelItem(dict, name) < 0) {
if (PyErr_ExceptionMatches(PyExc_KeyError)) {
PyErr_Clear();
PyErr_Format(PyExc_AttributeError,
"'%.200s' object has no attribute '%U'",
type_name, name);
Py_DECREF(dict);
return -1;
}
else {
Py_DECREF(dict);
return -1;
}
}
Py_DECREF(dict);
return 0;
}
else {
Py_DECREF(dict);
return PyDict_SetItem(dict, name, value);
}
}
/* Class method object */
/* A class method receives the class as implicit first argument,
just like an instance method receives the instance.
To declare a class method, use this idiom:
class C:
@classmethod
def f(cls, arg1, arg2, argN):
...
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()); the instance is ignored except for its class.
If a class method is called for a derived class, the derived class
object is passed as the implied first argument.
Class methods are different than C++ or Java static methods.
If you want those, see static methods below.
*/
typedef struct {
PyObject_HEAD
PyObject *cm_callable;
PyObject *cm_dict;
} classmethod;
#define _PyClassMethod_CAST(cm) \
(assert(PyObject_TypeCheck((cm), &PyClassMethod_Type)), \
_Py_CAST(classmethod*, cm))
static void
cm_dealloc(PyObject *self)
{
classmethod *cm = _PyClassMethod_CAST(self);
_PyObject_GC_UNTRACK((PyObject *)cm);
Py_XDECREF(cm->cm_callable);
Py_XDECREF(cm->cm_dict);
Py_TYPE(cm)->tp_free((PyObject *)cm);
}
static int
cm_traverse(PyObject *self, visitproc visit, void *arg)
{
classmethod *cm = _PyClassMethod_CAST(self);
Py_VISIT(cm->cm_callable);
Py_VISIT(cm->cm_dict);
return 0;
}
static int
cm_clear(PyObject *self)
{
classmethod *cm = _PyClassMethod_CAST(self);
Py_CLEAR(cm->cm_callable);
Py_CLEAR(cm->cm_dict);
return 0;
}
static PyObject *
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
classmethod *cm = (classmethod *)self;
if (cm->cm_callable == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"uninitialized classmethod object");
return NULL;
}
if (type == NULL)
type = (PyObject *)(Py_TYPE(obj));
return PyMethod_New(cm->cm_callable, type);
}
static int
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
{
classmethod *cm = (classmethod *)self;
PyObject *callable;
if (!_PyArg_NoKeywords("classmethod", kwds))
return -1;
if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
return -1;
Py_XSETREF(cm->cm_callable, Py_NewRef(callable));
if (functools_wraps((PyObject *)cm, cm->cm_callable) < 0) {
return -1;
}
return 0;
}
static PyMemberDef cm_memberlist[] = {
{"__func__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
{"__wrapped__", _Py_T_OBJECT, offsetof(classmethod, cm_callable), Py_READONLY},
{NULL} /* Sentinel */
};
static PyObject *
cm_get___isabstractmethod__(PyObject *self, void *closure)
{
classmethod *cm = _PyClassMethod_CAST(self);
int res = _PyObject_IsAbstract(cm->cm_callable);
if (res == -1) {
return NULL;
}
else if (res) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject *
cm_get___annotations__(PyObject *self, void *closure)
{
classmethod *cm = _PyClassMethod_CAST(self);
return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotations__));
}
static int
cm_set___annotations__(PyObject *self, PyObject *value, void *closure)
{
return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "classmethod");
}
static PyObject *
cm_get___annotate__(PyObject *self, void *closure)
{
classmethod *cm = _PyClassMethod_CAST(self);
return descriptor_get_wrapped_attribute(cm->cm_callable, self, &_Py_ID(__annotate__));
}
static int
cm_set___annotate__(PyObject *self, PyObject *value, void *closure)
{
return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "classmethod");
}
static PyGetSetDef cm_getsetlist[] = {
{"__isabstractmethod__", cm_get___isabstractmethod__, NULL, NULL, NULL},
{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
{"__annotations__", cm_get___annotations__, cm_set___annotations__, NULL, NULL},
{"__annotate__", cm_get___annotate__, cm_set___annotate__, NULL, NULL},
{NULL} /* Sentinel */
};
static PyMethodDef cm_methodlist[] = {
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
{NULL} /* Sentinel */
};
static PyObject*
cm_repr(PyObject *self)
{
classmethod *cm = _PyClassMethod_CAST(self);
return PyUnicode_FromFormat("<classmethod(%R)>", cm->cm_callable);
}
PyDoc_STRVAR(classmethod_doc,
"classmethod(function, /)\n\
--\n\
\n\
Convert a function to be a class method.\n\
\n\
A class method receives the class as implicit first argument,\n\
just like an instance method receives the instance.\n\
To declare a class method, use this idiom:\n\
\n\
class C:\n\
@classmethod\n\
def f(cls, arg1, arg2, argN):\n\
...\n\
\n\
It can be called either on the class (e.g. C.f()) or on an instance\n\
(e.g. C().f()). The instance is ignored except for its class.\n\
If a class method is called for a derived class, the derived class\n\
object is passed as the implied first argument.\n\
\n\
Class methods are different than C++ or Java static methods.\n\
If you want those, see the staticmethod builtin.");
PyTypeObject PyClassMethod_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"classmethod",
sizeof(classmethod),
0,
cm_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
cm_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
classmethod_doc, /* tp_doc */
cm_traverse, /* tp_traverse */
cm_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
cm_methodlist, /* tp_methods */
cm_memberlist, /* tp_members */
cm_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
cm_descr_get, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(classmethod, cm_dict), /* tp_dictoffset */
cm_init, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
PyType_GenericNew, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
PyObject *
PyClassMethod_New(PyObject *callable)
{
classmethod *cm = (classmethod *)
PyType_GenericAlloc(&PyClassMethod_Type, 0);
if (cm != NULL) {
cm->cm_callable = Py_NewRef(callable);
}
return (PyObject *)cm;
}
/* Static method object */
/* A static method does not receive an implicit first argument.
To declare a static method, use this idiom:
class C:
@staticmethod
def f(arg1, arg2, argN):
...
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()). Both the class and the instance are ignored, and
neither is passed implicitly as the first argument to the method.
Static methods in Python are similar to those found in Java or C++.
For a more advanced concept, see class methods above.
*/
typedef struct {
PyObject_HEAD
PyObject *sm_callable;
PyObject *sm_dict;
} staticmethod;
#define _PyStaticMethod_CAST(cm) \
(assert(PyObject_TypeCheck((cm), &PyStaticMethod_Type)), \
_Py_CAST(staticmethod*, cm))
static void
sm_dealloc(PyObject *self)
{
staticmethod *sm = _PyStaticMethod_CAST(self);
_PyObject_GC_UNTRACK((PyObject *)sm);
Py_XDECREF(sm->sm_callable);
Py_XDECREF(sm->sm_dict);
Py_TYPE(sm)->tp_free((PyObject *)sm);
}
static int
sm_traverse(PyObject *self, visitproc visit, void *arg)
{
staticmethod *sm = _PyStaticMethod_CAST(self);
Py_VISIT(sm->sm_callable);
Py_VISIT(sm->sm_dict);
return 0;
}
static int
sm_clear(PyObject *self)
{
staticmethod *sm = _PyStaticMethod_CAST(self);
Py_CLEAR(sm->sm_callable);
Py_CLEAR(sm->sm_dict);
return 0;
}
static PyObject *
sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
staticmethod *sm = (staticmethod *)self;
if (sm->sm_callable == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"uninitialized staticmethod object");
return NULL;
}
return Py_NewRef(sm->sm_callable);
}
static int
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
{
staticmethod *sm = (staticmethod *)self;
PyObject *callable;
if (!_PyArg_NoKeywords("staticmethod", kwds))
return -1;
if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
return -1;
Py_XSETREF(sm->sm_callable, Py_NewRef(callable));
if (functools_wraps((PyObject *)sm, sm->sm_callable) < 0) {
return -1;
}
return 0;
}
static PyObject*
sm_call(PyObject *callable, PyObject *args, PyObject *kwargs)
{
staticmethod *sm = (staticmethod *)callable;
return PyObject_Call(sm->sm_callable, args, kwargs);
}
static PyMemberDef sm_memberlist[] = {
{"__func__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
{"__wrapped__", _Py_T_OBJECT, offsetof(staticmethod, sm_callable), Py_READONLY},
{NULL} /* Sentinel */
};
static PyObject *
sm_get___isabstractmethod__(PyObject *self, void *closure)
{
staticmethod *sm = _PyStaticMethod_CAST(self);
int res = _PyObject_IsAbstract(sm->sm_callable);
if (res == -1) {
return NULL;
}
else if (res) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject *
sm_get___annotations__(PyObject *self, void *closure)
{
staticmethod *sm = _PyStaticMethod_CAST(self);
return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotations__));
}
static int
sm_set___annotations__(PyObject *self, PyObject *value, void *closure)
{
return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotations__), value, "staticmethod");
}
static PyObject *
sm_get___annotate__(PyObject *self, void *closure)
{
staticmethod *sm = _PyStaticMethod_CAST(self);
return descriptor_get_wrapped_attribute(sm->sm_callable, self, &_Py_ID(__annotate__));
}
static int
sm_set___annotate__(PyObject *self, PyObject *value, void *closure)
{
return descriptor_set_wrapped_attribute(self, &_Py_ID(__annotate__), value, "staticmethod");
}
static PyGetSetDef sm_getsetlist[] = {
{"__isabstractmethod__", sm_get___isabstractmethod__, NULL, NULL, NULL},
{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL},
{"__annotations__", sm_get___annotations__, sm_set___annotations__, NULL, NULL},
{"__annotate__", sm_get___annotate__, sm_set___annotate__, NULL, NULL},
{NULL} /* Sentinel */
};
static PyMethodDef sm_methodlist[] = {
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, NULL},
{NULL} /* Sentinel */
};
static PyObject*
sm_repr(PyObject *self)
{
staticmethod *sm = _PyStaticMethod_CAST(self);
return PyUnicode_FromFormat("<staticmethod(%R)>", sm->sm_callable);
}
PyDoc_STRVAR(staticmethod_doc,
"staticmethod(function, /)\n\
--\n\
\n\
Convert a function to be a static method.\n\
\n\
A static method does not receive an implicit first argument.\n\
To declare a static method, use this idiom:\n\
\n\
class C:\n\
@staticmethod\n\
def f(arg1, arg2, argN):\n\
...\n\
\n\
It can be called either on the class (e.g. C.f()) or on an instance\n\
(e.g. C().f()). Both the class and the instance are ignored, and\n\
neither is passed implicitly as the first argument to the method.\n\
\n\
Static methods in Python are similar to those found in Java or C++.\n\
For a more advanced concept, see the classmethod builtin.");
PyTypeObject PyStaticMethod_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"staticmethod",
sizeof(staticmethod),
0,
sm_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
sm_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
sm_call, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
staticmethod_doc, /* tp_doc */
sm_traverse, /* tp_traverse */
sm_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
sm_methodlist, /* tp_methods */
sm_memberlist, /* tp_members */
sm_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
sm_descr_get, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(staticmethod, sm_dict), /* tp_dictoffset */
sm_init, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
PyType_GenericNew, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
PyObject *
PyStaticMethod_New(PyObject *callable)
{
staticmethod *sm = (staticmethod *)
PyType_GenericAlloc(&PyStaticMethod_Type, 0);
if (sm != NULL) {
sm->sm_callable = Py_NewRef(callable);
}
return (PyObject *)sm;
}
/* PyByteArray (bytearray) implementation */
#include "Python.h"
#include "pycore_abstract.h" // _PyIndex_Check()
#include "pycore_bytes_methods.h"
#include "pycore_bytesobject.h"
#include "pycore_ceval.h" // _PyEval_GetBuiltin()
#include "pycore_critical_section.h"
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
#include "pycore_strhex.h" // _Py_strhex_with_sep()
#include "pycore_long.h" // _PyLong_FromUnsignedChar()
#include "pycore_pyatomic_ft_wrappers.h"
#include "bytesobject.h"
/*[clinic input]
class bytearray "PyByteArrayObject *" "&PyByteArray_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/
/* Max number of bytes a bytearray can contain */
#define PyByteArray_SIZE_MAX ((Py_ssize_t)(PY_SSIZE_T_MAX - _PyBytesObject_SIZE))
/* Helpers */
static int
_getbytevalue(PyObject* arg, int *value)
{
int overflow;
long face_value = PyLong_AsLongAndOverflow(arg, &overflow);
if (face_value == -1 && PyErr_Occurred()) {
*value = -1;
return 0;
}
if (face_value < 0 || face_value >= 256) {
/* this includes an overflow in converting to C long */
PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)");
*value = -1;
return 0;
}
*value = face_value;
return 1;
}
static void
bytearray_reinit_from_bytes(PyByteArrayObject *self, Py_ssize_t size,
Py_ssize_t alloc) {
self->ob_bytes = self->ob_start = PyBytes_AS_STRING(self->ob_bytes_object);
Py_SET_SIZE(self, size);
FT_ATOMIC_STORE_SSIZE_RELAXED(self->ob_alloc, alloc);
}
static int
bytearray_getbuffer_lock_held(PyObject *self, Py_buffer *view, int flags)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
PyByteArrayObject *obj = _PyByteArray_CAST(self);
if (view == NULL) {
PyErr_SetString(PyExc_BufferError,
"bytearray_getbuffer: view==NULL argument is obsolete");
return -1;
}
void *ptr = (void *) PyByteArray_AS_STRING(obj);
if (PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags) < 0) {
return -1;
}
obj->ob_exports++;
return 0;
}
static int
bytearray_getbuffer(PyObject *self, Py_buffer *view, int flags)
{
int ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = bytearray_getbuffer_lock_held(self, view, flags);
Py_END_CRITICAL_SECTION();
return ret;
}
static void
bytearray_releasebuffer(PyObject *self, Py_buffer *view)
{
Py_BEGIN_CRITICAL_SECTION(self);
PyByteArrayObject *obj = _PyByteArray_CAST(self);
obj->ob_exports--;
assert(obj->ob_exports >= 0);
Py_END_CRITICAL_SECTION();
}
typedef PyObject* (*_ba_bytes_op)(const char *buf, Py_ssize_t len,
PyObject *sub, Py_ssize_t start,
Py_ssize_t end);
static PyObject *
_bytearray_with_buffer(PyByteArrayObject *self, _ba_bytes_op op, PyObject *sub,
Py_ssize_t start, Py_ssize_t end)
{
PyObject *res;
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
/* Increase exports to prevent bytearray storage from changing during op. */
self->ob_exports++;
res = op(PyByteArray_AS_STRING(self), Py_SIZE(self), sub, start, end);
self->ob_exports--;
return res;
}
static int
_canresize(PyByteArrayObject *self)
{
if (self->ob_exports > 0) {
PyErr_SetString(PyExc_BufferError,
"Existing exports of data: object cannot be re-sized");
return 0;
}
return 1;
}
#include "clinic/bytearrayobject.c.h"
/* Direct API functions */
PyObject *
PyByteArray_FromObject(PyObject *input)
{
return PyObject_CallOneArg((PyObject *)&PyByteArray_Type, input);
}
static PyObject *
_PyByteArray_FromBufferObject(PyObject *obj)
{
PyObject *result;
Py_buffer view;
if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) {
return NULL;
}
result = PyByteArray_FromStringAndSize(NULL, view.len);
if (result != NULL &&
PyBuffer_ToContiguous(PyByteArray_AS_STRING(result),
&view, view.len, 'C') < 0)
{
Py_CLEAR(result);
}
PyBuffer_Release(&view);
return result;
}
PyObject *
PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size)
{
PyByteArrayObject *new;
if (size < 0) {
PyErr_SetString(PyExc_SystemError,
"Negative size passed to PyByteArray_FromStringAndSize");
return NULL;
}
new = PyObject_New(PyByteArrayObject, &PyByteArray_Type);
if (new == NULL) {
return NULL;
}
/* Fill values used in bytearray_dealloc.
In an optimized build the memory isn't zeroed and ob_exports would be
uninitialized when when PyBytes_FromStringAndSize errored leading to
intermittent test failures. */
new->ob_exports = 0;
/* Optimization: size=0 bytearray should not allocate space
PyBytes_FromStringAndSize returns the empty bytes global when size=0 so
no allocation occurs. */
new->ob_bytes_object = PyBytes_FromStringAndSize(NULL, size);
if (new->ob_bytes_object == NULL) {
Py_DECREF(new);
return NULL;
}
bytearray_reinit_from_bytes(new, size, size);
if (bytes != NULL && size > 0) {
memcpy(new->ob_bytes, bytes, size);
}
return (PyObject *)new;
}
Py_ssize_t
PyByteArray_Size(PyObject *self)
{
assert(self != NULL);
assert(PyByteArray_Check(self));
return PyByteArray_GET_SIZE(self);
}
char *
PyByteArray_AsString(PyObject *self)
{
assert(self != NULL);
assert(PyByteArray_Check(self));
return PyByteArray_AS_STRING(self);
}
static int
bytearray_resize_lock_held(PyObject *self, Py_ssize_t requested_size)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
PyByteArrayObject *obj = ((PyByteArrayObject *)self);
/* All computations are done unsigned to avoid integer overflows
(see issue #22335). */
size_t alloc = (size_t) obj->ob_alloc;
size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes);
size_t size = (size_t) requested_size;
assert(self != NULL);
assert(PyByteArray_Check(self));
assert(logical_offset <= alloc);
if (requested_size < 0) {
PyErr_Format(PyExc_ValueError,
"Can only resize to positive sizes, got %zd", requested_size);
return -1;
}
if (requested_size == Py_SIZE(self)) {
return 0;
}
if (!_canresize(obj)) {
return -1;
}
if (size + logical_offset <= alloc) {
/* Current buffer is large enough to host the requested size,
decide on a strategy. */
if (size < alloc / 2) {
/* Major downsize; resize down to exact size */
alloc = size;
}
else {
/* Minor downsize; quick exit */
Py_SET_SIZE(self, size);
/* Add mid-buffer null; end provided by bytes. */
PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */
return 0;
}
}
else {
/* Need growing, decide on a strategy */
if (size <= alloc * 1.125) {
/* Moderate upsize; overallocate similar to list_resize() */
alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
}
else {
/* Major upsize; resize up to exact size */
alloc = size;
}
}
if (alloc > PyByteArray_SIZE_MAX) {
PyErr_NoMemory();
return -1;
}
/* Re-align data to the start of the allocation. */
if (logical_offset > 0) {
/* optimization tradeoff: This is faster than a new allocation when
the number of bytes being removed in a resize is small; for large
size changes it may be better to just make a new bytes object as
_PyBytes_Resize will do a malloc + memcpy internally. */
memmove(obj->ob_bytes, obj->ob_start,
Py_MIN(requested_size, Py_SIZE(self)));
}
int ret = _PyBytes_Resize(&obj->ob_bytes_object, alloc);
if (ret == -1) {
obj->ob_bytes_object = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
size = alloc = 0;
}
bytearray_reinit_from_bytes(obj, size, alloc);
if (alloc != size) {
/* Add mid-buffer null; end provided by bytes. */
obj->ob_bytes[size] = '\0';
}
return ret;
}
int
PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
{
int ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = bytearray_resize_lock_held(self, requested_size);
Py_END_CRITICAL_SECTION();
return ret;
}
PyObject *
PyByteArray_Concat(PyObject *a, PyObject *b)
{
Py_buffer va, vb;
PyByteArrayObject *result = NULL;
va.len = -1;
vb.len = -1;
if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 ||
PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) {
PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name);
goto done;
}
if (va.len > PyByteArray_SIZE_MAX - vb.len) {
PyErr_NoMemory();
goto done;
}
result = (PyByteArrayObject *) \
PyByteArray_FromStringAndSize(NULL, va.len + vb.len);
// result->ob_bytes is NULL if result is an empty bytearray:
// if va.len + vb.len equals zero.
if (result != NULL && result->ob_bytes != NULL) {
memcpy(result->ob_bytes, va.buf, va.len);
memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
}
done:
if (va.len != -1)
PyBuffer_Release(&va);
if (vb.len != -1)
PyBuffer_Release(&vb);
return (PyObject *)result;
}
/* Functions stuffed into the type object */
static Py_ssize_t
bytearray_length(PyObject *op)
{
return PyByteArray_GET_SIZE(op);
}
static PyObject *
bytearray_iconcat_lock_held(PyObject *op, PyObject *other)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
PyByteArrayObject *self = _PyByteArray_CAST(op);
Py_buffer vo;
if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) {
PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s",
Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name);
return NULL;
}
Py_ssize_t size = Py_SIZE(self);
if (size > PyByteArray_SIZE_MAX - vo.len) {
PyBuffer_Release(&vo);
return PyErr_NoMemory();
}
if (bytearray_resize_lock_held((PyObject *)self, size + vo.len) < 0) {
PyBuffer_Release(&vo);
return NULL;
}
memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
PyBuffer_Release(&vo);
return Py_NewRef(self);
}
static PyObject *
bytearray_iconcat(PyObject *op, PyObject *other)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(op);
ret = bytearray_iconcat_lock_held(op, other);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_repeat_lock_held(PyObject *op, Py_ssize_t count)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
PyByteArrayObject *self = _PyByteArray_CAST(op);
if (count < 0) {
count = 0;
}
const Py_ssize_t mysize = Py_SIZE(self);
if (count > 0 && mysize > PyByteArray_SIZE_MAX / count) {
return PyErr_NoMemory();
}
Py_ssize_t size = mysize * count;
PyByteArrayObject* result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size);
const char* buf = PyByteArray_AS_STRING(self);
if (result != NULL && size != 0) {
_PyBytes_Repeat(result->ob_bytes, size, buf, mysize);
}
return (PyObject *)result;
}
static PyObject *
bytearray_repeat(PyObject *op, Py_ssize_t count)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(op);
ret = bytearray_repeat_lock_held(op, count);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_irepeat_lock_held(PyObject *op, Py_ssize_t count)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
PyByteArrayObject *self = _PyByteArray_CAST(op);
if (count < 0) {
count = 0;
}
else if (count == 1) {
return Py_NewRef(self);
}
const Py_ssize_t mysize = Py_SIZE(self);
if (count > 0 && mysize > PyByteArray_SIZE_MAX / count) {
return PyErr_NoMemory();
}
const Py_ssize_t size = mysize * count;
if (bytearray_resize_lock_held((PyObject *)self, size) < 0) {
return NULL;
}
char* buf = PyByteArray_AS_STRING(self);
_PyBytes_Repeat(buf, size, buf, mysize);
return Py_NewRef(self);
}
static PyObject *
bytearray_irepeat(PyObject *op, Py_ssize_t count)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(op);
ret = bytearray_irepeat_lock_held(op, count);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_getitem_lock_held(PyObject *op, Py_ssize_t i)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
PyByteArrayObject *self = _PyByteArray_CAST(op);
if (i < 0 || i >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return NULL;
}
return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i]));
}
static PyObject *
bytearray_getitem(PyObject *op, Py_ssize_t i)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(op);
ret = bytearray_getitem_lock_held(op, i);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_subscript_lock_held(PyObject *op, PyObject *index)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
PyByteArrayObject *self = _PyByteArray_CAST(op);
if (_PyIndex_Check(index)) {
Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return NULL;
if (i < 0)
i += PyByteArray_GET_SIZE(self);
if (i < 0 || i >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return NULL;
}
return _PyLong_FromUnsignedChar((unsigned char)(self->ob_start[i]));
}
else if (PySlice_Check(index)) {
Py_ssize_t start, stop, step, slicelength, i;
size_t cur;
if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
return NULL;
}
slicelength = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self),
&start, &stop, step);
if (slicelength <= 0)
return PyByteArray_FromStringAndSize("", 0);
else if (step == 1) {
return PyByteArray_FromStringAndSize(
PyByteArray_AS_STRING(self) + start, slicelength);
}
else {
char *source_buf = PyByteArray_AS_STRING(self);
char *result_buf;
PyObject *result;
result = PyByteArray_FromStringAndSize(NULL, slicelength);
if (result == NULL)
return NULL;
result_buf = PyByteArray_AS_STRING(result);
for (cur = start, i = 0; i < slicelength;
cur += step, i++) {
result_buf[i] = source_buf[cur];
}
return result;
}
}
else {
PyErr_Format(PyExc_TypeError,
"bytearray indices must be integers or slices, not %.200s",
Py_TYPE(index)->tp_name);
return NULL;
}
}
static PyObject *
bytearray_subscript(PyObject *op, PyObject *index)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(op);
ret = bytearray_subscript_lock_held(op, index);
Py_END_CRITICAL_SECTION();
return ret;
}
static int
bytearray_setslice_linear(PyByteArrayObject *self,
Py_ssize_t lo, Py_ssize_t hi,
char *bytes, Py_ssize_t bytes_len)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
Py_ssize_t avail = hi - lo;
char *buf = PyByteArray_AS_STRING(self);
Py_ssize_t growth = bytes_len - avail;
int res = 0;
assert(avail >= 0);
if (growth < 0) {
if (!_canresize(self))
return -1;
if (lo == 0) {
/* Shrink the buffer by advancing its logical start */
self->ob_start -= growth;
/*
0 lo hi old_size
| |<----avail----->|<-----tail------>|
| |<-bytes_len->|<-----tail------>|
0 new_lo new_hi new_size
*/
}
else {
/*
0 lo hi old_size
| |<----avail----->|<-----tomove------>|
| |<-bytes_len->|<-----tomove------>|
0 lo new_hi new_size
*/
memmove(buf + lo + bytes_len, buf + hi,
Py_SIZE(self) - hi);
}
if (bytearray_resize_lock_held((PyObject *)self,
Py_SIZE(self) + growth) < 0) {
/* Issue #19578: Handling the memory allocation failure here is
tricky here because the bytearray object has already been
modified. Depending on growth and lo, the behaviour is
different.
If growth < 0 and lo != 0, the operation is completed, but a
MemoryError is still raised and the memory block is not
shrunk. Otherwise, the bytearray is restored in its previous
state and a MemoryError is raised. */
if (lo == 0) {
self->ob_start += growth;
return -1;
}
/* memmove() removed bytes, the bytearray object cannot be
restored in its previous state. */
Py_SET_SIZE(self, Py_SIZE(self) + growth);
res = -1;
}
buf = PyByteArray_AS_STRING(self);
}
else if (growth > 0) {
if (Py_SIZE(self) > PyByteArray_SIZE_MAX - growth) {
PyErr_NoMemory();
return -1;
}
if (bytearray_resize_lock_held((PyObject *)self,
Py_SIZE(self) + growth) < 0) {
return -1;
}
buf = PyByteArray_AS_STRING(self);
/* Make the place for the additional bytes */
/*
0 lo hi old_size
| |<-avail->|<-----tomove------>|
| |<---bytes_len-->|<-----tomove------>|
0 lo new_hi new_size
*/
memmove(buf + lo + bytes_len, buf + hi,
Py_SIZE(self) - lo - bytes_len);
}
if (bytes_len > 0)
memcpy(buf + lo, bytes, bytes_len);
return res;
}
static int
bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,
PyObject *values)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
Py_ssize_t needed;
void *bytes;
Py_buffer vbytes;
int res = 0;
vbytes.len = -1;
if (values == (PyObject *)self) {
/* Make a copy and call this function recursively */
int err;
values = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(values),
PyByteArray_GET_SIZE(values));
if (values == NULL)
return -1;
err = bytearray_setslice(self, lo, hi, values);
Py_DECREF(values);
return err;
}
if (values == NULL) {
/* del b[lo:hi] */
bytes = NULL;
needed = 0;
}
else {
if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) {
PyErr_Format(PyExc_TypeError,
"can't set bytearray slice from %.100s",
Py_TYPE(values)->tp_name);
return -1;
}
needed = vbytes.len;
bytes = vbytes.buf;
}
if (lo < 0)
lo = 0;
if (hi < lo)
hi = lo;
if (hi > Py_SIZE(self))
hi = Py_SIZE(self);
res = bytearray_setslice_linear(self, lo, hi, bytes, needed);
if (vbytes.len != -1)
PyBuffer_Release(&vbytes);
return res;
}
static int
bytearray_setitem_lock_held(PyObject *op, Py_ssize_t i, PyObject *value)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
PyByteArrayObject *self = _PyByteArray_CAST(op);
// GH-91153: We need to do this *before* the size check, in case value has a
// nasty __index__ method that changes the size of the bytearray:
int ival = -1;
if (value && !_getbytevalue(value, &ival)) {
return -1;
}
if (i < 0) {
i += Py_SIZE(self);
}
if (i < 0 || i >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return -1;
}
if (value == NULL) {
return bytearray_setslice(self, i, i+1, NULL);
}
assert(0 <= ival && ival < 256);
PyByteArray_AS_STRING(self)[i] = ival;
return 0;
}
static int
bytearray_setitem(PyObject *op, Py_ssize_t i, PyObject *value)
{
int ret;
Py_BEGIN_CRITICAL_SECTION(op);
ret = bytearray_setitem_lock_held(op, i, value);
Py_END_CRITICAL_SECTION();
return ret;
}
static int
bytearray_ass_subscript_lock_held(PyObject *op, PyObject *index, PyObject *values)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
PyByteArrayObject *self = _PyByteArray_CAST(op);
Py_ssize_t start, stop, step, slicelen;
// Do not store a reference to the internal buffer since
// index.__index__() or _getbytevalue() may alter 'self'.
// See https://github.com/python/cpython/issues/91153.
if (_PyIndex_Check(index)) {
Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
int ival = -1;
// GH-91153: We need to do this *before* the size check, in case values
// has a nasty __index__ method that changes the size of the bytearray:
if (values && !_getbytevalue(values, &ival)) {
return -1;
}
if (i < 0) {
i += PyByteArray_GET_SIZE(self);
}
if (i < 0 || i >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return -1;
}
if (values == NULL) {
/* Fall through to slice assignment */
start = i;
stop = i + 1;
step = 1;
slicelen = 1;
}
else {
assert(0 <= ival && ival < 256);
PyByteArray_AS_STRING(self)[i] = (char)ival;
return 0;
}
}
else if (PySlice_Check(index)) {
if (PySlice_Unpack(index, &start, &stop, &step) < 0) {
return -1;
}
slicelen = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start,
&stop, step);
}
else {
PyErr_Format(PyExc_TypeError,
"bytearray indices must be integers or slices, not %.200s",
Py_TYPE(index)->tp_name);
return -1;
}
char *bytes;
Py_ssize_t needed;
if (values == NULL) {
bytes = NULL;
needed = 0;
}
else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
int err;
if (PyNumber_Check(values) || PyUnicode_Check(values)) {
PyErr_SetString(PyExc_TypeError,
"can assign only bytes, buffers, or iterables "
"of ints in range(0, 256)");
return -1;
}
/* Make a copy and call this function recursively */
values = PyByteArray_FromObject(values);
if (values == NULL)
return -1;
err = bytearray_ass_subscript_lock_held((PyObject*)self, index, values);
Py_DECREF(values);
return err;
}
else {
assert(PyByteArray_Check(values));
bytes = PyByteArray_AS_STRING(values);
needed = Py_SIZE(values);
}
/* Make sure b[5:2] = ... inserts before 5, not before 2. */
if ((step < 0 && start < stop) ||
(step > 0 && start > stop))
{
stop = start;
}
if (step == 1) {
return bytearray_setslice_linear(self, start, stop, bytes, needed);
}
else {
if (needed == 0) {
/* Delete slice */
size_t cur;
Py_ssize_t i;
char *buf = PyByteArray_AS_STRING(self);
if (!_canresize(self))
return -1;
if (slicelen == 0)
/* Nothing to do here. */
return 0;
if (step < 0) {
stop = start + 1;
start = stop + step * (slicelen - 1) - 1;
step = -step;
}
for (cur = start, i = 0;
i < slicelen; cur += step, i++) {
Py_ssize_t lim = step - 1;
if (cur + step >= (size_t)PyByteArray_GET_SIZE(self))
lim = PyByteArray_GET_SIZE(self) - cur - 1;
memmove(buf + cur - i,
buf + cur + 1, lim);
}
/* Move the tail of the bytes, in one chunk */
cur = start + (size_t)slicelen*step;
if (cur < (size_t)PyByteArray_GET_SIZE(self)) {
memmove(buf + cur - slicelen,
buf + cur,
PyByteArray_GET_SIZE(self) - cur);
}
if (bytearray_resize_lock_held((PyObject *)self,
PyByteArray_GET_SIZE(self) - slicelen) < 0)
return -1;
return 0;
}
else {
/* Assign slice */
Py_ssize_t i;
size_t cur;
char *buf = PyByteArray_AS_STRING(self);
if (needed != slicelen) {
PyErr_Format(PyExc_ValueError,
"attempt to assign bytes of size %zd "
"to extended slice of size %zd",
needed, slicelen);
return -1;
}
for (cur = start, i = 0; i < slicelen; cur += step, i++)
buf[cur] = bytes[i];
return 0;
}
}
}
static int
bytearray_ass_subscript(PyObject *op, PyObject *index, PyObject *values)
{
int ret;
if (values != NULL && PyByteArray_Check(values)) {
Py_BEGIN_CRITICAL_SECTION2(op, values);
ret = bytearray_ass_subscript_lock_held(op, index, values);
Py_END_CRITICAL_SECTION2();
}
else {
Py_BEGIN_CRITICAL_SECTION(op);
ret = bytearray_ass_subscript_lock_held(op, index, values);
Py_END_CRITICAL_SECTION();
}
return ret;
}
/*[clinic input]
bytearray.__init__
source as arg: object = NULL
encoding: str = NULL
errors: str = NULL
[clinic start generated code]*/
static int
bytearray___init___impl(PyByteArrayObject *self, PyObject *arg,
const char *encoding, const char *errors)
/*[clinic end generated code: output=4ce1304649c2f8b3 input=1141a7122eefd7b9]*/
{
Py_ssize_t count;
PyObject *it;
PyObject *(*iternext)(PyObject *);
/* First __init__; set ob_bytes_object so ob_bytes is always non-null. */
if (self->ob_bytes_object == NULL) {
self->ob_bytes_object = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
bytearray_reinit_from_bytes(self, 0, 0);
self->ob_exports = 0;
}
if (Py_SIZE(self) != 0) {
/* Empty previous contents (yes, do this first of all!) */
if (PyByteArray_Resize((PyObject *)self, 0) < 0)
return -1;
}
/* Should be caused by first init or the resize to 0. */
assert(self->ob_bytes_object == Py_GetConstantBorrowed(Py_CONSTANT_EMPTY_BYTES));
assert(self->ob_exports == 0);
/* Make a quick exit if no first argument */
if (arg == NULL) {
if (encoding != NULL || errors != NULL) {
PyErr_SetString(PyExc_TypeError,
encoding != NULL ?
"encoding without a string argument" :
"errors without a string argument");
return -1;
}
return 0;
}
if (PyUnicode_Check(arg)) {
/* Encode via the codec registry */
PyObject *encoded, *new;
if (encoding == NULL) {
PyErr_SetString(PyExc_TypeError,
"string argument without an encoding");
return -1;
}
encoded = PyUnicode_AsEncodedString(arg, encoding, errors);
if (encoded == NULL) {
return -1;
}
assert(PyBytes_Check(encoded));
/* Most encodes return a new unique bytes, just use it as buffer. */
if (_PyObject_IsUniquelyReferenced(encoded)
&& PyBytes_CheckExact(encoded))
{
Py_ssize_t size = Py_SIZE(encoded);
self->ob_bytes_object = encoded;
bytearray_reinit_from_bytes(self, size, size);
return 0;
}
new = bytearray_iconcat((PyObject*)self, encoded);
Py_DECREF(encoded);
if (new == NULL)
return -1;
Py_DECREF(new);
return 0;
}
/* If it's not unicode, there can't be encoding or errors */
if (encoding != NULL || errors != NULL) {
PyErr_SetString(PyExc_TypeError,
encoding != NULL ?
"encoding without a string argument" :
"errors without a string argument");
return -1;
}
/* Is it an int? */
if (_PyIndex_Check(arg)) {
count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
if (count == -1 && PyErr_Occurred()) {
if (!PyErr_ExceptionMatches(PyExc_TypeError))
return -1;
PyErr_Clear(); /* fall through */
}
else {
if (count < 0) {
PyErr_SetString(PyExc_ValueError, "negative count");
return -1;
}
if (count > 0) {
if (PyByteArray_Resize((PyObject *)self, count))
return -1;
memset(PyByteArray_AS_STRING(self), 0, count);
}
return 0;
}
}
/* Use the buffer API */
if (PyObject_CheckBuffer(arg)) {
Py_ssize_t size;
Py_buffer view;
if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0)
return -1;
size = view.len;
if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
&view, size, 'C') < 0)
goto fail;
PyBuffer_Release(&view);
return 0;
fail:
PyBuffer_Release(&view);
return -1;
}
if (PyList_CheckExact(arg) || PyTuple_CheckExact(arg)) {
Py_ssize_t size = PySequence_Fast_GET_SIZE(arg);
if (PyByteArray_Resize((PyObject *)self, size) < 0) {
return -1;
}
PyObject **items = PySequence_Fast_ITEMS(arg);
char *s = PyByteArray_AS_STRING(self);
for (Py_ssize_t i = 0; i < size; i++) {
int value;
if (!PyLong_CheckExact(items[i])) {
/* Resize to 0 and go through slowpath */
if (Py_SIZE(self) != 0) {
if (PyByteArray_Resize((PyObject *)self, 0) < 0) {
return -1;
}
}
goto slowpath;
}
int rc = _getbytevalue(items[i], &value);
if (!rc) {
return -1;
}
s[i] = value;
}
return 0;
}
slowpath:
/* Get the iterator */
it = PyObject_GetIter(arg);
if (it == NULL) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_Format(PyExc_TypeError,
"cannot convert '%.200s' object to bytearray",
Py_TYPE(arg)->tp_name);
}
return -1;
}
iternext = *Py_TYPE(it)->tp_iternext;
/* Run the iterator to exhaustion */
for (;;) {
PyObject *item;
int rc, value;
/* Get the next item */
item = iternext(it);
if (item == NULL) {
if (PyErr_Occurred()) {
if (!PyErr_ExceptionMatches(PyExc_StopIteration))
goto error;
PyErr_Clear();
}
break;
}
/* Interpret it as an int (__index__) */
rc = _getbytevalue(item, &value);
Py_DECREF(item);
if (!rc)
goto error;
/* Append the byte */
if (Py_SIZE(self) + 1 < self->ob_alloc) {
Py_SET_SIZE(self, Py_SIZE(self) + 1);
PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0';
}
else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0)
goto error;
PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value;
}
/* Clean up and return success */
Py_DECREF(it);
return 0;
error:
/* Error handling when it != NULL */
Py_DECREF(it);
return -1;
}
static PyObject *
bytearray_repr_lock_held(PyObject *op)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
const char *className = _PyType_Name(Py_TYPE(op));
PyObject *bytes_repr = _Py_bytes_repr(PyByteArray_AS_STRING(op),
PyByteArray_GET_SIZE(op), 1,
"bytearray");
if (bytes_repr == NULL) {
return NULL;
}
PyObject *res = PyUnicode_FromFormat("%s(%U)", className, bytes_repr);
Py_DECREF(bytes_repr);
return res;
}
static PyObject *
bytearray_repr(PyObject *op)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(op);
ret = bytearray_repr_lock_held(op);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_str(PyObject *op)
{
if (_Py_GetConfig()->bytes_warning) {
if (PyErr_WarnEx(PyExc_BytesWarning,
"str() on a bytearray instance", 1)) {
return NULL;
}
}
return bytearray_repr(op);
}
static PyObject *
bytearray_richcompare(PyObject *self, PyObject *other, int op)
{
Py_ssize_t self_size, other_size;
Py_buffer self_bytes, other_bytes;
int cmp;
if (!PyObject_CheckBuffer(self) || !PyObject_CheckBuffer(other)) {
if (PyUnicode_Check(self) || PyUnicode_Check(other)) {
if (_Py_GetConfig()->bytes_warning && (op == Py_EQ || op == Py_NE)) {
if (PyErr_WarnEx(PyExc_BytesWarning,
"Comparison between bytearray and string", 1))
return NULL;
}
}
Py_RETURN_NOTIMPLEMENTED;
}
/* Bytearrays can be compared to anything that supports the buffer API. */
if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) {
PyErr_Clear();
Py_RETURN_NOTIMPLEMENTED;
}
self_size = self_bytes.len;
if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) {
PyErr_Clear();
PyBuffer_Release(&self_bytes);
Py_RETURN_NOTIMPLEMENTED;
}
other_size = other_bytes.len;
if (self_size != other_size && (op == Py_EQ || op == Py_NE)) {
/* Shortcut: if the lengths differ, the objects differ */
PyBuffer_Release(&self_bytes);
PyBuffer_Release(&other_bytes);
return PyBool_FromLong((op == Py_NE));
}
else {
cmp = memcmp(self_bytes.buf, other_bytes.buf,
Py_MIN(self_size, other_size));
/* In ISO C, memcmp() guarantees to use unsigned bytes! */
PyBuffer_Release(&self_bytes);
PyBuffer_Release(&other_bytes);
if (cmp != 0) {
Py_RETURN_RICHCOMPARE(cmp, 0, op);
}
Py_RETURN_RICHCOMPARE(self_size, other_size, op);
}
}
static void
bytearray_dealloc(PyObject *op)
{
PyByteArrayObject *self = _PyByteArray_CAST(op);
if (self->ob_exports > 0) {
PyErr_SetString(PyExc_SystemError,
"deallocated bytearray object has exported buffers");
PyErr_Print();
}
Py_XDECREF(self->ob_bytes_object);
Py_TYPE(self)->tp_free((PyObject *)self);
}
/* -------------------------------------------------------------------- */
/* Methods */
#define STRINGLIB_IS_UNICODE 0
#define FASTSEARCH fastsearch
#define STRINGLIB(F) stringlib_##F
#define STRINGLIB_CHAR char
#define STRINGLIB_SIZEOF_CHAR 1
#define STRINGLIB_LEN PyByteArray_GET_SIZE
#define STRINGLIB_STR PyByteArray_AS_STRING
#define STRINGLIB_NEW PyByteArray_FromStringAndSize
#define STRINGLIB_ISSPACE Py_ISSPACE
#define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r'))
#define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact
#define STRINGLIB_FAST_MEMCHR memchr
#define STRINGLIB_MUTABLE 1
#include "stringlib/fastsearch.h"
#include "stringlib/count.h"
#include "stringlib/find.h"
#include "stringlib/join.h"
#include "stringlib/partition.h"
#include "stringlib/split.h"
#include "stringlib/ctype.h"
#include "stringlib/transmogrify.h"
/*[clinic input]
@permit_long_summary
@critical_section
@text_signature "($self, sub[, start[, end]], /)"
bytearray.find
sub: object
start: slice_index(accept={int, NoneType}, c_default='0') = None
Optional start position. Default: start of the bytes.
end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
Optional stop position. Default: end of the bytes.
/
Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end].
Return -1 on failure.
[clinic start generated code]*/
static PyObject *
bytearray_find_impl(PyByteArrayObject *self, PyObject *sub, Py_ssize_t start,
Py_ssize_t end)
/*[clinic end generated code: output=413e1cab2ae87da0 input=df3aa94840d893a7]*/
{
return _bytearray_with_buffer(self, _Py_bytes_find, sub, start, end);
}
/*[clinic input]
@permit_long_summary
@critical_section
bytearray.count = bytearray.find
Return the number of non-overlapping occurrences of subsection 'sub' in bytes B[start:end].
[clinic start generated code]*/
static PyObject *
bytearray_count_impl(PyByteArrayObject *self, PyObject *sub,
Py_ssize_t start, Py_ssize_t end)
/*[clinic end generated code: output=a21ee2692e4f1233 input=e8fcdca8272857e0]*/
{
return _bytearray_with_buffer(self, _Py_bytes_count, sub, start, end);
}
/*[clinic input]
bytearray.clear
Remove all items from the bytearray.
[clinic start generated code]*/
static PyObject *
bytearray_clear_impl(PyByteArrayObject *self)
/*[clinic end generated code: output=85c2fe6aede0956c input=ed6edae9de447ac4]*/
{
if (PyByteArray_Resize((PyObject *)self, 0) < 0)
return NULL;
Py_RETURN_NONE;
}
/*[clinic input]
@critical_section
bytearray.copy
Return a copy of B.
[clinic start generated code]*/
static PyObject *
bytearray_copy_impl(PyByteArrayObject *self)
/*[clinic end generated code: output=68cfbcfed484c132 input=b96f8b01f73851ad]*/
{
return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self),
PyByteArray_GET_SIZE(self));
}
/*[clinic input]
@permit_long_summary
@critical_section
bytearray.index = bytearray.find
Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end].
Raise ValueError if the subsection is not found.
[clinic start generated code]*/
static PyObject *
bytearray_index_impl(PyByteArrayObject *self, PyObject *sub,
Py_ssize_t start, Py_ssize_t end)
/*[clinic end generated code: output=067a1e78efc672a7 input=c37f177cfee19fe4]*/
{
return _bytearray_with_buffer(self, _Py_bytes_index, sub, start, end);
}
/*[clinic input]
@permit_long_summary
@critical_section
bytearray.rfind = bytearray.find
Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end].
Return -1 on failure.
[clinic start generated code]*/
static PyObject *
bytearray_rfind_impl(PyByteArrayObject *self, PyObject *sub,
Py_ssize_t start, Py_ssize_t end)
/*[clinic end generated code: output=51bf886f932b283c input=1265b11c437d2750]*/
{
return _bytearray_with_buffer(self, _Py_bytes_rfind, sub, start, end);
}
/*[clinic input]
@permit_long_summary
@critical_section
bytearray.rindex = bytearray.find
Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end].
Raise ValueError if the subsection is not found.
[clinic start generated code]*/
static PyObject *
bytearray_rindex_impl(PyByteArrayObject *self, PyObject *sub,
Py_ssize_t start, Py_ssize_t end)
/*[clinic end generated code: output=38e1cf66bafb08b9 input=7d198b3d6b0a62ce]*/
{
return _bytearray_with_buffer(self, _Py_bytes_rindex, sub, start, end);
}
static int
bytearray_contains(PyObject *self, PyObject *arg)
{
int ret = -1;
Py_BEGIN_CRITICAL_SECTION(self);
PyByteArrayObject *ba = _PyByteArray_CAST(self);
/* Increase exports to prevent bytearray storage from changing during _Py_bytes_contains(). */
ba->ob_exports++;
ret = _Py_bytes_contains(PyByteArray_AS_STRING(ba),
PyByteArray_GET_SIZE(self),
arg);
ba->ob_exports--;
Py_END_CRITICAL_SECTION();
return ret;
}
/*[clinic input]
@permit_long_summary
@critical_section
@text_signature "($self, prefix[, start[, end]], /)"
bytearray.startswith
prefix as subobj: object
A bytes or a tuple of bytes to try.
start: slice_index(accept={int, NoneType}, c_default='0') = None
Optional start position. Default: start of the bytearray.
end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
Optional stop position. Default: end of the bytearray.
/
Return True if the bytearray starts with the specified prefix, False otherwise.
[clinic start generated code]*/
static PyObject *
bytearray_startswith_impl(PyByteArrayObject *self, PyObject *subobj,
Py_ssize_t start, Py_ssize_t end)
/*[clinic end generated code: output=a3d9b6d44d3662a6 input=93f9ffee684f109a]*/
{
return _bytearray_with_buffer(self, _Py_bytes_startswith, subobj, start, end);
}
/*[clinic input]
@permit_long_summary
@critical_section
@text_signature "($self, suffix[, start[, end]], /)"
bytearray.endswith
suffix as subobj: object
A bytes or a tuple of bytes to try.
start: slice_index(accept={int, NoneType}, c_default='0') = None
Optional start position. Default: start of the bytearray.
end: slice_index(accept={int, NoneType}, c_default='PY_SSIZE_T_MAX') = None
Optional stop position. Default: end of the bytearray.
/
Return True if the bytearray ends with the specified suffix, False otherwise.
[clinic start generated code]*/
static PyObject *
bytearray_endswith_impl(PyByteArrayObject *self, PyObject *subobj,
Py_ssize_t start, Py_ssize_t end)
/*[clinic end generated code: output=e75ea8c227954caa input=d158b030a11d0b06]*/
{
return _bytearray_with_buffer(self, _Py_bytes_endswith, subobj, start, end);
}
/*[clinic input]
@critical_section
bytearray.removeprefix as bytearray_removeprefix
prefix: Py_buffer
/
Return a bytearray with the given prefix string removed if present.
If the bytearray starts with the prefix string, return
bytearray[len(prefix):]. Otherwise, return a copy of the original
bytearray.
[clinic start generated code]*/
static PyObject *
bytearray_removeprefix_impl(PyByteArrayObject *self, Py_buffer *prefix)
/*[clinic end generated code: output=6cabc585e7f502e0 input=4323ba6d275fe7a8]*/
{
const char *self_start = PyByteArray_AS_STRING(self);
Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
const char *prefix_start = prefix->buf;
Py_ssize_t prefix_len = prefix->len;
if (self_len >= prefix_len
&& memcmp(self_start, prefix_start, prefix_len) == 0)
{
return PyByteArray_FromStringAndSize(self_start + prefix_len,
self_len - prefix_len);
}
return PyByteArray_FromStringAndSize(self_start, self_len);
}
/*[clinic input]
@critical_section
bytearray.removesuffix as bytearray_removesuffix
suffix: Py_buffer
/
Return a bytearray with the given suffix string removed if present.
If the bytearray ends with the suffix string and that suffix is not
empty, return bytearray[:-len(suffix)]. Otherwise, return a copy of
the original bytearray.
[clinic start generated code]*/
static PyObject *
bytearray_removesuffix_impl(PyByteArrayObject *self, Py_buffer *suffix)
/*[clinic end generated code: output=2bc8cfb79de793d3 input=f71ba2e1a40c47dd]*/
{
const char *self_start = PyByteArray_AS_STRING(self);
Py_ssize_t self_len = PyByteArray_GET_SIZE(self);
const char *suffix_start = suffix->buf;
Py_ssize_t suffix_len = suffix->len;
if (self_len >= suffix_len
&& memcmp(self_start + self_len - suffix_len,
suffix_start, suffix_len) == 0)
{
return PyByteArray_FromStringAndSize(self_start,
self_len - suffix_len);
}
return PyByteArray_FromStringAndSize(self_start, self_len);
}
/*[clinic input]
bytearray.resize
size: Py_ssize_t
New size to resize to.
/
Resize the internal buffer of bytearray to len.
[clinic start generated code]*/
static PyObject *
bytearray_resize_impl(PyByteArrayObject *self, Py_ssize_t size)
/*[clinic end generated code: output=f73524922990b2d9 input=6c9a260ca7f72071]*/
{
Py_ssize_t start_size = PyByteArray_GET_SIZE(self);
int result = PyByteArray_Resize((PyObject *)self, size);
if (result < 0) {
return NULL;
}
// Set new bytes to null bytes
if (size > start_size) {
memset(PyByteArray_AS_STRING(self) + start_size, 0, size - start_size);
}
Py_RETURN_NONE;
}
/*[clinic input]
@critical_section
bytearray.take_bytes
n: object = None
Bytes to take, negative indexes from end. None indicates all bytes.
/
Take *n* bytes from the bytearray and return them as a bytes object.
[clinic start generated code]*/
static PyObject *
bytearray_take_bytes_impl(PyByteArrayObject *self, PyObject *n)
/*[clinic end generated code: output=3147fbc0bbbe8d94 input=b15b5172cdc6deda]*/
{
Py_ssize_t to_take;
Py_ssize_t size = Py_SIZE(self);
if (Py_IsNone(n)) {
to_take = size;
}
// Integer index, from start (zero, positive) or end (negative).
else if (_PyIndex_Check(n)) {
to_take = PyNumber_AsSsize_t(n, PyExc_IndexError);
if (to_take == -1 && PyErr_Occurred()) {
return NULL;
}
if (to_take < 0) {
to_take += size;
}
}
else {
PyErr_SetString(PyExc_TypeError, "n must be an integer or None");
return NULL;
}
if (to_take < 0 || to_take > size) {
PyErr_Format(PyExc_IndexError,
"can't take %zd bytes outside size %zd",
to_take, size);
return NULL;
}
// Exports may change the contents. No mutable bytes allowed.
if (!_canresize(self)) {
return NULL;
}
if (to_take == 0 || size == 0) {
return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
}
Py_ssize_t remaining_length = size - to_take;
// optimization: If taking less than leaving, just copy the small to_take
// portion out and move ob_start.
if (to_take < remaining_length) {
PyObject *ret = PyBytes_FromStringAndSize(self->ob_start, to_take);
if (ret == NULL) {
return NULL;
}
self->ob_start += to_take;
Py_SET_SIZE(self, remaining_length);
return ret;
}
// Copy remaining bytes to a new bytes.
PyObject *remaining = PyBytes_FromStringAndSize(self->ob_start + to_take,
remaining_length);
if (remaining == NULL) {
return NULL;
}
// If the bytes are offset inside the buffer must first align.
if (self->ob_start != self->ob_bytes) {
memmove(self->ob_bytes, self->ob_start, to_take);
self->ob_start = self->ob_bytes;
}
if (_PyBytes_Resize(&self->ob_bytes_object, to_take) == -1) {
Py_DECREF(remaining);
return NULL;
}
// Point the bytearray towards the buffer with the remaining data.
PyObject *result = self->ob_bytes_object;
self->ob_bytes_object = remaining;
bytearray_reinit_from_bytes(self, remaining_length, remaining_length);
return result;
}
/*[clinic input]
@critical_section
bytearray.translate
table: object
Translation table, which must be a bytes object of length 256.
/
delete as deletechars: object(c_default="NULL") = b''
Return a copy with each character mapped by the given translation table.
All characters occurring in the optional argument delete are removed.
The remaining characters are mapped through the given translation table.
[clinic start generated code]*/
static PyObject *
bytearray_translate_impl(PyByteArrayObject *self, PyObject *table,
PyObject *deletechars)
/*[clinic end generated code: output=b6a8f01c2a74e446 input=cd6fa93ca04e05bc]*/
{
char *input, *output;
const char *table_chars;
Py_ssize_t i, c;
PyObject *input_obj = (PyObject*)self;
const char *output_start;
Py_ssize_t inlen;
PyObject *result = NULL;
int trans_table[256];
Py_buffer vtable, vdel;
if (table == Py_None) {
table_chars = NULL;
table = NULL;
} else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) {
return NULL;
} else {
if (vtable.len != 256) {
PyErr_SetString(PyExc_ValueError,
"translation table must be 256 characters long");
PyBuffer_Release(&vtable);
return NULL;
}
table_chars = (const char*)vtable.buf;
}
if (deletechars != NULL) {
if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) {
if (table != NULL)
PyBuffer_Release(&vtable);
return NULL;
}
}
else {
vdel.buf = NULL;
vdel.len = 0;
}
inlen = PyByteArray_GET_SIZE(input_obj);
result = PyByteArray_FromStringAndSize((char *)NULL, inlen);
if (result == NULL)
goto done;
output_start = output = PyByteArray_AS_STRING(result);
input = PyByteArray_AS_STRING(input_obj);
if (vdel.len == 0 && table_chars != NULL) {
/* If no deletions are required, use faster code */
for (i = inlen; --i >= 0; ) {
c = Py_CHARMASK(*input++);
*output++ = table_chars[c];
}
goto done;
}
if (table_chars == NULL) {
for (i = 0; i < 256; i++)
trans_table[i] = Py_CHARMASK(i);
} else {
for (i = 0; i < 256; i++)
trans_table[i] = Py_CHARMASK(table_chars[i]);
}
for (i = 0; i < vdel.len; i++)
trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1;
for (i = inlen; --i >= 0; ) {
c = Py_CHARMASK(*input++);
if (trans_table[c] != -1)
*output++ = (char)trans_table[c];
}
/* Fix the size of the resulting bytearray */
if (inlen > 0)
if (PyByteArray_Resize(result, output - output_start) < 0) {
Py_CLEAR(result);
goto done;
}
done:
if (table != NULL)
PyBuffer_Release(&vtable);
if (deletechars != NULL)
PyBuffer_Release(&vdel);
return result;
}
/*[clinic input]
@permit_long_summary
@permit_long_docstring_body
@staticmethod
bytearray.maketrans
frm: Py_buffer
to: Py_buffer
/
Return a translation table usable for the bytes or bytearray translate method.
The returned table will be one where each byte in frm is mapped to the byte at
the same position in to.
The bytes objects frm and to must be of the same length.
[clinic start generated code]*/
static PyObject *
bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to)
/*[clinic end generated code: output=1df267d99f56b15e input=1146b43a592eca13]*/
{
return _Py_bytes_maketrans(frm, to);
}
/*[clinic input]
@permit_long_docstring_body
@critical_section
bytearray.replace
old: Py_buffer
new: Py_buffer
count: Py_ssize_t = -1
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
/
Return a copy with all occurrences of substring old replaced by new.
If the optional argument count is given, only the first count occurrences are
replaced.
[clinic start generated code]*/
static PyObject *
bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old,
Py_buffer *new, Py_ssize_t count)
/*[clinic end generated code: output=d39884c4dc59412a input=66afec32f4e095e0]*/
{
return stringlib_replace((PyObject *)self,
(const char *)old->buf, old->len,
(const char *)new->buf, new->len, count);
}
/*[clinic input]
@permit_long_summary
@critical_section
bytearray.split
sep: object = None
The delimiter according which to split the bytearray.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit: Py_ssize_t = -1
Maximum number of splits to do.
-1 (the default value) means no limit.
Return a list of the sections in the bytearray, using sep as the delimiter.
[clinic start generated code]*/
static PyObject *
bytearray_split_impl(PyByteArrayObject *self, PyObject *sep,
Py_ssize_t maxsplit)
/*[clinic end generated code: output=833e2cf385d9a04d input=dd9f6e2910cc3a34]*/
{
PyObject *list = NULL;
/* Increase exports to prevent bytearray storage from changing during _Py_bytes_contains(). */
self->ob_exports++;
const char *sbuf = PyByteArray_AS_STRING(self);
Py_ssize_t slen = PyByteArray_GET_SIZE((PyObject *)self);
if (maxsplit < 0)
maxsplit = PY_SSIZE_T_MAX;
if (sep == Py_None) {
list = stringlib_split_whitespace((PyObject*)self, sbuf, slen, maxsplit);
goto done;
}
Py_buffer vsub;
if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) {
goto done;
}
list = stringlib_split((PyObject*)self, sbuf, slen,
(const char *)vsub.buf, vsub.len, maxsplit);
PyBuffer_Release(&vsub);
done:
self->ob_exports--;
return list;
}
/*[clinic input]
@permit_long_docstring_body
@critical_section
bytearray.partition
sep: object
/
Partition the bytearray into three parts using the given separator.
This will search for the separator sep in the bytearray. If the separator is
found, returns a 3-tuple containing the part before the separator, the
separator itself, and the part after it as new bytearray objects.
If the separator is not found, returns a 3-tuple containing the copy of the
original bytearray object and two empty bytearray objects.
[clinic start generated code]*/
static PyObject *
bytearray_partition_impl(PyByteArrayObject *self, PyObject *sep)
/*[clinic end generated code: output=b5fa1e03f10cfccb input=b87276af883f39d9]*/
{
PyObject *bytesep, *result;
bytesep = _PyByteArray_FromBufferObject(sep);
if (! bytesep)
return NULL;
result = stringlib_partition(
(PyObject*) self,
PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
bytesep,
PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
);
Py_DECREF(bytesep);
return result;
}
/*[clinic input]
@permit_long_docstring_body
@critical_section
bytearray.rpartition
sep: object
/
Partition the bytearray into three parts using the given separator.
This will search for the separator sep in the bytearray, starting at the end.
If the separator is found, returns a 3-tuple containing the part before the
separator, the separator itself, and the part after it as new bytearray
objects.
If the separator is not found, returns a 3-tuple containing two empty bytearray
objects and the copy of the original bytearray object.
[clinic start generated code]*/
static PyObject *
bytearray_rpartition_impl(PyByteArrayObject *self, PyObject *sep)
/*[clinic end generated code: output=0186ce7b1ef61289 input=5bdcfc4c333bcfab]*/
{
PyObject *bytesep, *result;
bytesep = _PyByteArray_FromBufferObject(sep);
if (! bytesep)
return NULL;
result = stringlib_rpartition(
(PyObject*) self,
PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self),
bytesep,
PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep)
);
Py_DECREF(bytesep);
return result;
}
/*[clinic input]
@permit_long_summary
@permit_long_docstring_body
@critical_section
bytearray.rsplit = bytearray.split
Return a list of the sections in the bytearray, using sep as the delimiter.
Splitting is done starting at the end of the bytearray and working to the front.
[clinic start generated code]*/
static PyObject *
bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep,
Py_ssize_t maxsplit)
/*[clinic end generated code: output=a55e0b5a03cb6190 input=60e9abf305128ff4]*/
{
PyObject *list = NULL;
/* Increase exports to prevent bytearray storage from changing during _Py_bytes_contains(). */
self->ob_exports++;
const char *sbuf = PyByteArray_AS_STRING(self);
Py_ssize_t slen = PyByteArray_GET_SIZE((PyObject *)self);
if (maxsplit < 0)
maxsplit = PY_SSIZE_T_MAX;
if (sep == Py_None) {
list = stringlib_rsplit_whitespace((PyObject*)self, sbuf, slen, maxsplit);
goto done;
}
Py_buffer vsub;
if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) {
goto done;
}
list = stringlib_rsplit((PyObject*)self, sbuf, slen,
(const char *)vsub.buf, vsub.len, maxsplit);
PyBuffer_Release(&vsub);
done:
self->ob_exports--;
return list;
}
/*[clinic input]
@critical_section
bytearray.reverse
Reverse the order of the values in B in place.
[clinic start generated code]*/
static PyObject *
bytearray_reverse_impl(PyByteArrayObject *self)
/*[clinic end generated code: output=9f7616f29ab309d3 input=2f3d5ce3180ffc53]*/
{
char swap, *head, *tail;
Py_ssize_t i, j, n = Py_SIZE(self);
j = n / 2;
head = PyByteArray_AS_STRING(self);
tail = head + n - 1;
for (i = 0; i < j; i++) {
swap = *head;
*head++ = *tail;
*tail-- = swap;
}
Py_RETURN_NONE;
}
/*[python input]
class bytesvalue_converter(CConverter):
type = 'int'
converter = '_getbytevalue'
[python start generated code]*/
/*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/
/*[clinic input]
@critical_section
bytearray.insert
index: Py_ssize_t
The index where the value is to be inserted.
item: bytesvalue
The item to be inserted.
/
Insert a single item into the bytearray before the given index.
[clinic start generated code]*/
static PyObject *
bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item)
/*[clinic end generated code: output=76c775a70e7b07b7 input=b3e14ede546dd8cc]*/
{
Py_ssize_t n = Py_SIZE(self);
char *buf;
if (bytearray_resize_lock_held((PyObject *)self, n + 1) < 0)
return NULL;
buf = PyByteArray_AS_STRING(self);
if (index < 0) {
index += n;
if (index < 0)
index = 0;
}
if (index > n)
index = n;
memmove(buf + index + 1, buf + index, n - index);
buf[index] = item;
Py_RETURN_NONE;
}
static PyObject *
bytearray_isalnum(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_isalnum(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_isalpha(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_isalpha(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_isascii(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_isascii(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_isdigit(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_isdigit(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_islower(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_islower(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_isspace(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_isspace(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_istitle(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_istitle(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_isupper(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_isupper(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
/*[clinic input]
@critical_section
bytearray.append
item: bytesvalue
The item to be appended.
/
Append a single item to the end of the bytearray.
[clinic start generated code]*/
static PyObject *
bytearray_append_impl(PyByteArrayObject *self, int item)
/*[clinic end generated code: output=a154e19ed1886cb6 input=a874689bac8bd352]*/
{
Py_ssize_t n = Py_SIZE(self);
if (bytearray_resize_lock_held((PyObject *)self, n + 1) < 0)
return NULL;
PyByteArray_AS_STRING(self)[n] = item;
Py_RETURN_NONE;
}
static PyObject *
bytearray_capitalize(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_capitalize(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_center(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_center(self, args, nargs);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_expandtabs(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_expandtabs(self, args, nargs, kwnames);
Py_END_CRITICAL_SECTION();
return ret;
}
/*[clinic input]
@permit_long_summary
@critical_section
bytearray.extend
iterable_of_ints: object
The iterable of items to append.
/
Append all the items from the iterator or sequence to the end of the bytearray.
[clinic start generated code]*/
static PyObject *
bytearray_extend_impl(PyByteArrayObject *self, PyObject *iterable_of_ints)
/*[clinic end generated code: output=2f25e0ce72b98748 input=aeed44b025146632]*/
{
PyObject *it, *item, *bytearray_obj;
Py_ssize_t buf_size = 0, len = 0;
int value;
char *buf;
/* bytearray_setslice code only accepts something supporting PEP 3118. */
if (PyObject_CheckBuffer(iterable_of_ints)) {
if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1)
return NULL;
Py_RETURN_NONE;
}
it = PyObject_GetIter(iterable_of_ints);
if (it == NULL) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_Format(PyExc_TypeError,
"can't extend bytearray with %.100s",
Py_TYPE(iterable_of_ints)->tp_name);
}
return NULL;
}
/* Try to determine the length of the argument. 32 is arbitrary. */
buf_size = PyObject_LengthHint(iterable_of_ints, 32);
if (buf_size == -1) {
Py_DECREF(it);
return NULL;
}
bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size);
if (bytearray_obj == NULL) {
Py_DECREF(it);
return NULL;
}
buf = PyByteArray_AS_STRING(bytearray_obj);
while ((item = PyIter_Next(it)) != NULL) {
if (! _getbytevalue(item, &value)) {
if (PyErr_ExceptionMatches(PyExc_TypeError) && PyUnicode_Check(iterable_of_ints)) {
PyErr_Format(PyExc_TypeError,
"expected iterable of integers; got: 'str'");
}
Py_DECREF(item);
Py_DECREF(it);
Py_DECREF(bytearray_obj);
return NULL;
}
Py_DECREF(item);
if (len >= buf_size) {
Py_ssize_t addition;
if (len == PyByteArray_SIZE_MAX) {
Py_DECREF(it);
Py_DECREF(bytearray_obj);
return PyErr_NoMemory();
}
addition = len ? len >> 1 : 1;
if (addition > PyByteArray_SIZE_MAX - len)
buf_size = PyByteArray_SIZE_MAX;
else
buf_size = len + addition;
if (bytearray_resize_lock_held((PyObject *)bytearray_obj, buf_size) < 0) {
Py_DECREF(it);
Py_DECREF(bytearray_obj);
return NULL;
}
/* Recompute the `buf' pointer, since the resizing operation may
have invalidated it. */
buf = PyByteArray_AS_STRING(bytearray_obj);
}
buf[len++] = value;
}
Py_DECREF(it);
if (PyErr_Occurred()) {
Py_DECREF(bytearray_obj);
return NULL;
}
/* Resize down to exact size. */
if (bytearray_resize_lock_held((PyObject *)bytearray_obj, len) < 0) {
Py_DECREF(bytearray_obj);
return NULL;
}
if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) {
Py_DECREF(bytearray_obj);
return NULL;
}
Py_DECREF(bytearray_obj);
assert(!PyErr_Occurred());
Py_RETURN_NONE;
}
/*[clinic input]
@critical_section
bytearray.pop
index: Py_ssize_t = -1
The index from where to remove the item.
-1 (the default value) means remove the last item.
/
Remove and return a single item from B.
If no index argument is given, will pop the last item.
[clinic start generated code]*/
static PyObject *
bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index)
/*[clinic end generated code: output=e0ccd401f8021da8 input=fc0fd8de4f97661c]*/
{
int value;
Py_ssize_t n = Py_SIZE(self);
char *buf;
if (n == 0) {
PyErr_SetString(PyExc_IndexError,
"pop from empty bytearray");
return NULL;
}
if (index < 0)
index += Py_SIZE(self);
if (index < 0 || index >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "pop index out of range");
return NULL;
}
if (!_canresize(self))
return NULL;
buf = PyByteArray_AS_STRING(self);
value = buf[index];
memmove(buf + index, buf + index + 1, n - index);
if (bytearray_resize_lock_held((PyObject *)self, n - 1) < 0)
return NULL;
return _PyLong_FromUnsignedChar((unsigned char)value);
}
/*[clinic input]
@critical_section
bytearray.remove
value: bytesvalue
The value to remove.
/
Remove the first occurrence of a value in the bytearray.
[clinic start generated code]*/
static PyObject *
bytearray_remove_impl(PyByteArrayObject *self, int value)
/*[clinic end generated code: output=d659e37866709c13 input=797588bc77f86afb]*/
{
Py_ssize_t where, n = Py_SIZE(self);
char *buf = PyByteArray_AS_STRING(self);
where = stringlib_find_char(buf, n, value);
if (where < 0) {
PyErr_SetString(PyExc_ValueError, "value not found in bytearray");
return NULL;
}
if (!_canresize(self))
return NULL;
memmove(buf + where, buf + where + 1, n - where);
if (bytearray_resize_lock_held((PyObject *)self, n - 1) < 0)
return NULL;
Py_RETURN_NONE;
}
#define LEFTSTRIP 0
#define RIGHTSTRIP 1
#define BOTHSTRIP 2
static PyObject*
bytearray_strip_impl_helper(PyByteArrayObject* self, PyObject* bytes, int striptype)
{
Py_ssize_t mysize, byteslen;
const char* myptr;
const char* bytesptr;
Py_buffer vbytes;
if (bytes == Py_None) {
bytesptr = "\t\n\r\f\v ";
byteslen = 6;
}
else {
if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0)
return NULL;
bytesptr = (const char*)vbytes.buf;
byteslen = vbytes.len;
}
myptr = PyByteArray_AS_STRING(self);
mysize = Py_SIZE(self);
Py_ssize_t left = 0;
if (striptype != RIGHTSTRIP) {
while (left < mysize && memchr(bytesptr, (unsigned char)myptr[left], byteslen))
left++;
}
Py_ssize_t right = mysize;
if (striptype != LEFTSTRIP) {
do {
right--;
} while (right >= left && memchr(bytesptr, (unsigned char)myptr[right], byteslen));
right++;
}
if (bytes != Py_None)
PyBuffer_Release(&vbytes);
return PyByteArray_FromStringAndSize(myptr + left, right - left);
}
/*[clinic input]
@permit_long_docstring_body
@critical_section
bytearray.strip
bytes: object = None
/
Strip leading and trailing bytes contained in the argument.
If the argument is omitted or None, strip leading and trailing ASCII whitespace.
[clinic start generated code]*/
static PyObject *
bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes)
/*[clinic end generated code: output=760412661a34ad5a input=6acaf88b2ec9daa7]*/
{
return bytearray_strip_impl_helper(self, bytes, BOTHSTRIP);
}
static PyObject *
bytearray_swapcase(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_swapcase(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_title(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_title(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_upper(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_upper(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_lower(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_lower(self, NULL);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_zfill(PyObject *self, PyObject *arg)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_zfill(self, arg);
Py_END_CRITICAL_SECTION();
return ret;
}
/*[clinic input]
@critical_section
bytearray.lstrip
bytes: object = None
/
Strip leading bytes contained in the argument.
If the argument is omitted or None, strip leading ASCII whitespace.
[clinic start generated code]*/
static PyObject *
bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes)
/*[clinic end generated code: output=d005c9d0ab909e66 input=ed86e00eb2023625]*/
{
return bytearray_strip_impl_helper(self, bytes, LEFTSTRIP);
}
/*[clinic input]
@critical_section
bytearray.rstrip
bytes: object = None
/
Strip trailing bytes contained in the argument.
If the argument is omitted or None, strip trailing ASCII whitespace.
[clinic start generated code]*/
static PyObject *
bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes)
/*[clinic end generated code: output=030e2fbd2f7276bd input=d9ca66cf20fe7649]*/
{
return bytearray_strip_impl_helper(self, bytes, RIGHTSTRIP);
}
/*[clinic input]
@critical_section
bytearray.decode
encoding: str(c_default="NULL") = 'utf-8'
The encoding with which to decode the bytearray.
errors: str(c_default="NULL") = 'strict'
The error handling scheme to use for the handling of decoding errors.
The default is 'strict' meaning that decoding errors raise a
UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that
can handle UnicodeDecodeErrors.
Decode the bytearray using the codec registered for encoding.
[clinic start generated code]*/
static PyObject *
bytearray_decode_impl(PyByteArrayObject *self, const char *encoding,
const char *errors)
/*[clinic end generated code: output=f57d43f4a00b42c5 input=86c303ee376b8453]*/
{
if (encoding == NULL)
encoding = PyUnicode_GetDefaultEncoding();
return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors);
}
PyDoc_STRVAR(alloc_doc,
"B.__alloc__() -> int\n\
\n\
Return the number of bytes actually allocated.");
static PyObject *
bytearray_alloc(PyObject *op, PyObject *Py_UNUSED(ignored))
{
PyByteArrayObject *self = _PyByteArray_CAST(op);
Py_ssize_t alloc = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->ob_alloc);
if (alloc > 0) {
alloc += _PyBytesObject_SIZE;
}
return PyLong_FromSsize_t(alloc);
}
/*[clinic input]
@critical_section
bytearray.join
iterable_of_bytes: object
/
Concatenate any number of bytes/bytearray objects.
The bytearray whose method is called is inserted in between each pair.
The result is returned as a new bytearray object.
[clinic start generated code]*/
static PyObject *
bytearray_join_impl(PyByteArrayObject *self, PyObject *iterable_of_bytes)
/*[clinic end generated code: output=0ced382b5846a7ee input=49627e07ca31ca26]*/
{
PyObject *ret;
self->ob_exports++; // this protects `self` from being cleared/resized if `iterable_of_bytes` is a custom iterator
ret = stringlib_bytes_join((PyObject*)self, iterable_of_bytes);
self->ob_exports--; // unexport `self`
return ret;
}
static PyObject *
bytearray_ljust(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_ljust(self, args, nargs);
Py_END_CRITICAL_SECTION();
return ret;
}
static PyObject *
bytearray_rjust(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
{
PyObject *ret;
Py_BEGIN_CRITICAL_SECTION(self);
ret = stringlib_rjust(self, args, nargs);
Py_END_CRITICAL_SECTION();
return ret;
}
/*[clinic input]
@permit_long_summary
@permit_long_docstring_body
@critical_section
bytearray.splitlines
keepends: bool = False
Return a list of the lines in the bytearray, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and
true.
[clinic start generated code]*/
static PyObject *
bytearray_splitlines_impl(PyByteArrayObject *self, int keepends)
/*[clinic end generated code: output=4223c94b895f6ad9 input=21bc3f02bf1be832]*/
{
return stringlib_splitlines(
(PyObject*) self, PyByteArray_AS_STRING(self),
PyByteArray_GET_SIZE(self), keepends
);
}
/*[clinic input]
@classmethod
bytearray.fromhex
string: object
/
Create a bytearray object from a string of hexadecimal numbers.
Spaces between two numbers are accepted.
Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
[clinic start generated code]*/
static PyObject *
bytearray_fromhex_impl(PyTypeObject *type, PyObject *string)
/*[clinic end generated code: output=8f0f0b6d30fb3ba0 input=7e314e5b2d7ab484]*/
{
PyObject *result = _PyBytes_FromHex(string, type == &PyByteArray_Type);
if (type != &PyByteArray_Type && result != NULL) {
Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result));
}
return result;
}
/*[clinic input]
@critical_section
bytearray.hex
sep: object = NULL
An optional single character or byte to separate hex bytes.
bytes_per_sep: int = 1
How many bytes between separators. Positive values count from the
right, negative values count from the left.
Create a string of hexadecimal numbers from a bytearray object.
Example:
>>> value = bytearray([0xb9, 0x01, 0xef])
>>> value.hex()
'b901ef'
>>> value.hex(':')
'b9:01:ef'
>>> value.hex(':', 2)
'b9:01ef'
>>> value.hex(':', -2)
'b901:ef'
[clinic start generated code]*/
static PyObject *
bytearray_hex_impl(PyByteArrayObject *self, PyObject *sep, int bytes_per_sep)
/*[clinic end generated code: output=29c4e5ef72c565a0 input=7784107de7048873]*/
{
char* argbuf = PyByteArray_AS_STRING(self);
Py_ssize_t arglen = PyByteArray_GET_SIZE(self);
// Prevent 'self' from being freed if computing len(sep) mutates 'self'
// in _Py_strhex_with_sep().
// See: https://github.com/python/cpython/issues/143195.
self->ob_exports++;
PyObject *res = _Py_strhex_with_sep(argbuf, arglen, sep, bytes_per_sep);
self->ob_exports--;
return res;
}
static PyObject *
_common_reduce(PyByteArrayObject *self, int proto)
{
PyObject *state;
const char *buf;
state = _PyObject_GetState((PyObject *)self);
if (state == NULL) {
return NULL;
}
if (!Py_SIZE(self)) {
return Py_BuildValue("(O()N)", Py_TYPE(self), state);
}
buf = PyByteArray_AS_STRING(self);
if (proto < 3) {
/* use str based reduction for backwards compatibility with Python 2.x */
PyObject *latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL);
return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", state);
}
else {
/* use more efficient byte based reduction */
return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), state);
}
}
/*[clinic input]
@critical_section
bytearray.__reduce__ as bytearray_reduce
Return state information for pickling.
[clinic start generated code]*/
static PyObject *
bytearray_reduce_impl(PyByteArrayObject *self)
/*[clinic end generated code: output=52bf304086464cab input=0fac78e4b7d84dd2]*/
{
return _common_reduce(self, 2);
}
/*[clinic input]
@critical_section
bytearray.__reduce_ex__ as bytearray_reduce_ex
proto: int = 0
/
Return state information for pickling.
[clinic start generated code]*/
static PyObject *
bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto)
/*[clinic end generated code: output=52eac33377197520 input=751718f477033a29]*/
{
return _common_reduce(self, proto);
}
/*[clinic input]
bytearray.__sizeof__ as bytearray_sizeof
Returns the size of the bytearray object in memory, in bytes.
[clinic start generated code]*/
static PyObject *
bytearray_sizeof_impl(PyByteArrayObject *self)
/*[clinic end generated code: output=738abdd17951c427 input=e27320fd98a4bc5a]*/
{
Py_ssize_t res = _PyObject_SIZE(Py_TYPE(self));
Py_ssize_t alloc = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->ob_alloc);
if (alloc > 0) {
res += _PyBytesObject_SIZE + alloc;
}
return PyLong_FromSsize_t(res);
}
static PySequenceMethods bytearray_as_sequence = {
bytearray_length, /* sq_length */
PyByteArray_Concat, /* sq_concat */
bytearray_repeat, /* sq_repeat */
bytearray_getitem, /* sq_item */
0, /* sq_slice */
bytearray_setitem, /* sq_ass_item */
0, /* sq_ass_slice */
bytearray_contains, /* sq_contains */
bytearray_iconcat, /* sq_inplace_concat */
bytearray_irepeat, /* sq_inplace_repeat */
};
static PyMappingMethods bytearray_as_mapping = {
bytearray_length,
bytearray_subscript,
bytearray_ass_subscript,
};
static PyBufferProcs bytearray_as_buffer = {
bytearray_getbuffer,
bytearray_releasebuffer,
};
static PyMethodDef bytearray_methods[] = {
{"__alloc__", bytearray_alloc, METH_NOARGS, alloc_doc},
BYTEARRAY_REDUCE_METHODDEF
BYTEARRAY_REDUCE_EX_METHODDEF
BYTEARRAY_SIZEOF_METHODDEF
BYTEARRAY_APPEND_METHODDEF
{"capitalize", bytearray_capitalize, METH_NOARGS, _Py_capitalize__doc__},
{"center", _PyCFunction_CAST(bytearray_center), METH_FASTCALL,
stringlib_center__doc__},
BYTEARRAY_CLEAR_METHODDEF
BYTEARRAY_COPY_METHODDEF
BYTEARRAY_COUNT_METHODDEF
BYTEARRAY_DECODE_METHODDEF
BYTEARRAY_ENDSWITH_METHODDEF
{"expandtabs", _PyCFunction_CAST(bytearray_expandtabs),
METH_FASTCALL|METH_KEYWORDS, stringlib_expandtabs__doc__},
BYTEARRAY_EXTEND_METHODDEF
BYTEARRAY_FIND_METHODDEF
BYTEARRAY_FROMHEX_METHODDEF
BYTEARRAY_HEX_METHODDEF
BYTEARRAY_INDEX_METHODDEF
BYTEARRAY_INSERT_METHODDEF
{"isalnum", bytearray_isalnum, METH_NOARGS, _Py_isalnum__doc__},
{"isalpha", bytearray_isalpha, METH_NOARGS, _Py_isalpha__doc__},
{"isascii", bytearray_isascii, METH_NOARGS, _Py_isascii__doc__},
{"isdigit", bytearray_isdigit, METH_NOARGS, _Py_isdigit__doc__},
{"islower", bytearray_islower, METH_NOARGS, _Py_islower__doc__},
{"isspace", bytearray_isspace, METH_NOARGS, _Py_isspace__doc__},
{"istitle", bytearray_istitle, METH_NOARGS, _Py_istitle__doc__},
{"isupper", bytearray_isupper, METH_NOARGS, _Py_isupper__doc__},
BYTEARRAY_JOIN_METHODDEF
{"ljust", _PyCFunction_CAST(bytearray_ljust), METH_FASTCALL,
stringlib_ljust__doc__},
{"lower", bytearray_lower, METH_NOARGS, _Py_lower__doc__},
BYTEARRAY_LSTRIP_METHODDEF
BYTEARRAY_MAKETRANS_METHODDEF
BYTEARRAY_PARTITION_METHODDEF
BYTEARRAY_POP_METHODDEF
BYTEARRAY_REMOVE_METHODDEF
BYTEARRAY_REPLACE_METHODDEF
BYTEARRAY_REMOVEPREFIX_METHODDEF
BYTEARRAY_REMOVESUFFIX_METHODDEF
BYTEARRAY_RESIZE_METHODDEF
BYTEARRAY_REVERSE_METHODDEF
BYTEARRAY_RFIND_METHODDEF
BYTEARRAY_RINDEX_METHODDEF
{"rjust", _PyCFunction_CAST(bytearray_rjust), METH_FASTCALL,
stringlib_rjust__doc__},
BYTEARRAY_RPARTITION_METHODDEF
BYTEARRAY_RSPLIT_METHODDEF
BYTEARRAY_RSTRIP_METHODDEF
BYTEARRAY_SPLIT_METHODDEF
BYTEARRAY_SPLITLINES_METHODDEF
BYTEARRAY_STARTSWITH_METHODDEF
BYTEARRAY_STRIP_METHODDEF
{"swapcase", bytearray_swapcase, METH_NOARGS, _Py_swapcase__doc__},
BYTEARRAY_TAKE_BYTES_METHODDEF
{"title", bytearray_title, METH_NOARGS, _Py_title__doc__},
BYTEARRAY_TRANSLATE_METHODDEF
{"upper", bytearray_upper, METH_NOARGS, _Py_upper__doc__},
{"zfill", bytearray_zfill, METH_O, stringlib_zfill__doc__},
{NULL}
};
static PyObject *
bytearray_mod_lock_held(PyObject *v, PyObject *w)
{
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(v);
if (!PyByteArray_Check(v))
Py_RETURN_NOTIMPLEMENTED;
PyByteArrayObject *self = _PyByteArray_CAST(v);
/* Increase exports to prevent bytearray storage from changing during op. */
self->ob_exports++;
PyObject *res = _PyBytes_FormatEx(
PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1
);
self->ob_exports--;
return res;
}
static PyObject *
bytearray_mod(PyObject *v, PyObject *w)
{
PyObject *ret;
if (PyByteArray_Check(w)) {
Py_BEGIN_CRITICAL_SECTION2(v, w);
ret = bytearray_mod_lock_held(v, w);
Py_END_CRITICAL_SECTION2();
}
else {
Py_BEGIN_CRITICAL_SECTION(v);
ret = bytearray_mod_lock_held(v, w);
Py_END_CRITICAL_SECTION();
}
return ret;
}
static PyNumberMethods bytearray_as_number = {
0, /*nb_add*/
0, /*nb_subtract*/
0, /*nb_multiply*/
bytearray_mod, /*nb_remainder*/
};
PyDoc_STRVAR(bytearray_doc,
"bytearray(iterable_of_ints) -> bytearray\n\
bytearray(string, encoding[, errors]) -> bytearray\n\
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\
bytearray() -> empty bytes array\n\
\n\
Construct a mutable bytearray object from:\n\
- an iterable yielding integers in range(256)\n\
- a text string encoded using the specified encoding\n\
- a bytes or a buffer object\n\
- any object implementing the buffer API.\n\
- an integer");
static PyObject *bytearray_iter(PyObject *seq);
PyTypeObject PyByteArray_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"bytearray",
sizeof(PyByteArrayObject),
0,
bytearray_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
bytearray_repr, /* tp_repr */
&bytearray_as_number, /* tp_as_number */
&bytearray_as_sequence, /* tp_as_sequence */
&bytearray_as_mapping, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
bytearray_str, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
&bytearray_as_buffer, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
_Py_TPFLAGS_MATCH_SELF, /* tp_flags */
bytearray_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
bytearray_richcompare, /* tp_richcompare */
0, /* tp_weaklistoffset */
bytearray_iter, /* tp_iter */
0, /* tp_iternext */
bytearray_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
bytearray___init__, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
PyType_GenericNew, /* tp_new */
PyObject_Free, /* tp_free */
.tp_version_tag = _Py_TYPE_VERSION_BYTEARRAY,
};
/*********************** Bytearray Iterator ****************************/
typedef struct {
PyObject_HEAD
Py_ssize_t it_index;
PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */
} bytesiterobject;
#define _bytesiterobject_CAST(op) ((bytesiterobject *)(op))
static void
bytearrayiter_dealloc(PyObject *self)
{
bytesiterobject *it = _bytesiterobject_CAST(self);
_PyObject_GC_UNTRACK(it);
Py_XDECREF(it->it_seq);
PyObject_GC_Del(it);
}
static int
bytearrayiter_traverse(PyObject *self, visitproc visit, void *arg)
{
bytesiterobject *it = _bytesiterobject_CAST(self);
Py_VISIT(it->it_seq);
return 0;
}
static PyObject *
bytearrayiter_next(PyObject *self)
{
bytesiterobject *it = _bytesiterobject_CAST(self);
int val;
assert(it != NULL);
Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
if (index < 0) {
return NULL;
}
PyByteArrayObject *seq = it->it_seq;
assert(PyByteArray_Check(seq));
Py_BEGIN_CRITICAL_SECTION(seq);
if (index < Py_SIZE(seq)) {
val = (unsigned char)PyByteArray_AS_STRING(seq)[index];
}
else {
val = -1;
}
Py_END_CRITICAL_SECTION();
if (val == -1) {
FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, -1);
#ifndef Py_GIL_DISABLED
Py_CLEAR(it->it_seq);
#endif
return NULL;
}
FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index + 1);
return _PyLong_FromUnsignedChar((unsigned char)val);
}
static PyObject *
bytearrayiter_length_hint(PyObject *self, PyObject *Py_UNUSED(ignored))
{
bytesiterobject *it = _bytesiterobject_CAST(self);
Py_ssize_t len = 0;
Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
if (index >= 0) {
len = PyByteArray_GET_SIZE(it->it_seq) - index;
if (len < 0) {
len = 0;
}
}
return PyLong_FromSsize_t(len);
}
PyDoc_STRVAR(length_hint_doc,
"Private method returning an estimate of len(list(it)).");
static PyObject *
bytearrayiter_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
{
PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
/* _PyEval_GetBuiltin can invoke arbitrary code,
* call must be before access of iterator pointers.
* see issue #101765 */
bytesiterobject *it = _bytesiterobject_CAST(self);
Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
if (index >= 0) {
return Py_BuildValue("N(O)n", iter, it->it_seq, index);
}
return Py_BuildValue("N(())", iter);
}
static PyObject *
bytearrayiter_setstate(PyObject *self, PyObject *state)
{
Py_ssize_t index = PyLong_AsSsize_t(state);
if (index == -1 && PyErr_Occurred()) {
return NULL;
}
bytesiterobject *it = _bytesiterobject_CAST(self);
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index) >= 0) {
if (index < -1) {
index = -1;
}
else {
Py_ssize_t size = PyByteArray_GET_SIZE(it->it_seq);
if (index > size) {
index = size; /* iterator at end */
}
}
FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index);
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
static PyMethodDef bytearrayiter_methods[] = {
{"__length_hint__", bytearrayiter_length_hint, METH_NOARGS,
length_hint_doc},
{"__reduce__", bytearrayiter_reduce, METH_NOARGS,
bytearray_reduce__doc__},
{"__setstate__", bytearrayiter_setstate, METH_O,
setstate_doc},
{NULL, NULL} /* sentinel */
};
PyTypeObject PyByteArrayIter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"bytearray_iterator", /* tp_name */
sizeof(bytesiterobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
bytearrayiter_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
0, /* tp_doc */
bytearrayiter_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
bytearrayiter_next, /* tp_iternext */
bytearrayiter_methods, /* tp_methods */
0,
};
static PyObject *
bytearray_iter(PyObject *seq)
{
bytesiterobject *it;
if (!PyByteArray_Check(seq)) {
PyErr_BadInternalCall();
return NULL;
}
it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type);
if (it == NULL)
return NULL;
it->it_index = 0; // -1 indicates exhausted
it->it_seq = (PyByteArrayObject *)Py_NewRef(seq);
_PyObject_GC_TRACK(it);
return (PyObject *)it;
}
/* Abstract Object Interface (many thanks to Jim Fulton) */
#include "Python.h"
#include "pycore_abstract.h" // _PyIndex_Check()
#include "pycore_call.h" // _PyObject_CallNoArgs()
#include "pycore_ceval.h" // _Py_EnterRecursiveCallTstate()
#include "pycore_crossinterp.h" // _Py_CallInInterpreter()
#include "pycore_genobject.h" // _PyGen_FetchStopIterationValue()
#include "pycore_list.h" // _PyList_AppendTakeRef()
#include "pycore_long.h" // _PyLong_IsNegative()
#include "pycore_object.h" // _Py_CheckSlotResult()
#include "pycore_pybuffer.h" // _PyBuffer_ReleaseInInterpreterAndRawFree()
#include "pycore_pyerrors.h" // _PyErr_Occurred()
#include "pycore_pystate.h" // _PyThreadState_GET()
#include "pycore_tuple.h" // _PyTuple_FromArraySteal()
#include "pycore_unionobject.h" // _PyUnion_Check()
#include <stddef.h> // offsetof()
/* Shorthands to return certain errors */
static PyObject *
type_error(const char *msg, PyObject *obj)
{
PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name);
return NULL;
}
static PyObject *
null_error(void)
{
PyThreadState *tstate = _PyThreadState_GET();
if (!_PyErr_Occurred(tstate)) {
_PyErr_SetString(tstate, PyExc_SystemError,
"null argument to internal routine");
}
return NULL;
}
/* Operations on any object */
PyObject *
PyObject_Type(PyObject *o)
{
PyObject *v;
if (o == NULL) {
return null_error();
}
v = (PyObject *)Py_TYPE(o);
return Py_NewRef(v);
}
Py_ssize_t
PyObject_Size(PyObject *o)
{
if (o == NULL) {
null_error();
return -1;
}
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
if (m && m->sq_length) {
Py_ssize_t len = m->sq_length(o);
assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
return len;
}
return PyMapping_Size(o);
}
#undef PyObject_Length
Py_ssize_t
PyObject_Length(PyObject *o)
{
return PyObject_Size(o);
}
#define PyObject_Length PyObject_Size
int
_PyObject_HasLen(PyObject *o) {
return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
(Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
}
/* The length hint function returns a non-negative value from o.__len__()
or o.__length_hint__(). If those methods aren't found the defaultvalue is
returned. If one of the calls fails with an exception other than TypeError
this function returns -1.
*/
Py_ssize_t
PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
{
PyObject *hint, *result;
Py_ssize_t res;
if (_PyObject_HasLen(o)) {
res = PyObject_Length(o);
if (res < 0) {
PyThreadState *tstate = _PyThreadState_GET();
assert(_PyErr_Occurred(tstate));
if (!_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
return -1;
}
_PyErr_Clear(tstate);
}
else {
return res;
}
}
hint = _PyObject_LookupSpecial(o, &_Py_ID(__length_hint__));
if (hint == NULL) {
if (PyErr_Occurred()) {
return -1;
}
return defaultvalue;
}
result = _PyObject_CallNoArgs(hint);
Py_DECREF(hint);
if (result == NULL) {
PyThreadState *tstate = _PyThreadState_GET();
if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
_PyErr_Clear(tstate);
return defaultvalue;
}
return -1;
}
else if (result == Py_NotImplemented) {
Py_DECREF(result);
return defaultvalue;
}
if (!PyLong_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%T.__length_hint__() must return an int, not %T",
o, result);
Py_DECREF(result);
return -1;
}
res = PyLong_AsSsize_t(result);
Py_DECREF(result);
if (res < 0 && PyErr_Occurred()) {
return -1;
}
if (res < 0) {
PyErr_Format(PyExc_ValueError,
"%T.__length_hint__() must return a non-negative int", o);
return -1;
}
return res;
}
PyObject *
PyObject_GetItem(PyObject *o, PyObject *key)
{
if (o == NULL || key == NULL) {
return null_error();
}
PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
if (m && m->mp_subscript) {
PyObject *item = m->mp_subscript(o, key);
assert(_Py_CheckSlotResult(o, "__getitem__", item != NULL));
return item;
}
PySequenceMethods *ms = Py_TYPE(o)->tp_as_sequence;
if (ms && ms->sq_item) {
if (_PyIndex_Check(key)) {
Py_ssize_t key_value;
key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (key_value == -1 && PyErr_Occurred())
return NULL;
return PySequence_GetItem(o, key_value);
}
else {
return type_error("sequence index must "
"be integer, not '%.200s'", key);
}
}
if (PyType_Check(o)) {
PyObject *meth, *result;
// Special case type[int], but disallow other types so str[int] fails
if ((PyTypeObject*)o == &PyType_Type) {
return Py_GenericAlias(o, key);
}
if (PyObject_GetOptionalAttr(o, &_Py_ID(__class_getitem__), &meth) < 0) {
return NULL;
}
if (meth && meth != Py_None) {
result = PyObject_CallOneArg(meth, key);
Py_DECREF(meth);
return result;
}
Py_XDECREF(meth);
PyErr_Format(PyExc_TypeError, "type '%.200s' is not subscriptable",
((PyTypeObject *)o)->tp_name);
return NULL;
}
return type_error("'%.200s' object is not subscriptable", o);
}
int
PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result)
{
if (PyDict_CheckExact(obj)) {
return PyDict_GetItemRef(obj, key, result);
}
*result = PyObject_GetItem(obj, key);
if (*result) {
return 1;
}
assert(PyErr_Occurred());
if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
return -1;
}
PyErr_Clear();
return 0;
}
PyObject*
_PyMapping_GetOptionalItem2(PyObject *obj, PyObject *key, int *err)
{
PyObject* result;
*err = PyMapping_GetOptionalItem(obj, key, &result);
return result;
}
int
PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
{
if (o == NULL || key == NULL || value == NULL) {
null_error();
return -1;
}
PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
if (m && m->mp_ass_subscript) {
int res = m->mp_ass_subscript(o, key, value);
assert(_Py_CheckSlotResult(o, "__setitem__", res >= 0));
return res;
}
if (Py_TYPE(o)->tp_as_sequence) {
if (_PyIndex_Check(key)) {
Py_ssize_t key_value;
key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (key_value == -1 && PyErr_Occurred())
return -1;
return PySequence_SetItem(o, key_value, value);
}
else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
type_error("sequence index must be "
"integer, not '%.200s'", key);
return -1;
}
}
type_error("'%.200s' object does not support item assignment", o);
return -1;
}
int
PyObject_DelItem(PyObject *o, PyObject *key)
{
if (o == NULL || key == NULL) {
null_error();
return -1;
}
PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
if (m && m->mp_ass_subscript) {
int res = m->mp_ass_subscript(o, key, (PyObject*)NULL);
assert(_Py_CheckSlotResult(o, "__delitem__", res >= 0));
return res;
}
if (Py_TYPE(o)->tp_as_sequence) {
if (_PyIndex_Check(key)) {
Py_ssize_t key_value;
key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (key_value == -1 && PyErr_Occurred())
return -1;
return PySequence_DelItem(o, key_value);
}
else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
type_error("sequence index must be "
"integer, not '%.200s'", key);
return -1;
}
}
type_error("'%.200s' object does not support item deletion", o);
return -1;
}
int
PyObject_DelItemString(PyObject *o, const char *key)
{
PyObject *okey;
int ret;
if (o == NULL || key == NULL) {
null_error();
return -1;
}
okey = PyUnicode_FromString(key);
if (okey == NULL)
return -1;
ret = PyObject_DelItem(o, okey);
Py_DECREF(okey);
return ret;
}
/* Return 1 if the getbuffer function is available, otherwise return 0. */
int
PyObject_CheckBuffer(PyObject *obj)
{
PyBufferProcs *tp_as_buffer = Py_TYPE(obj)->tp_as_buffer;
return (tp_as_buffer != NULL && tp_as_buffer->bf_getbuffer != NULL);
}
// Old buffer protocols (deprecated, abi only)
/* Checks whether an arbitrary object supports the (character, single segment)
buffer interface.
Returns 1 on success, 0 on failure.
We release the buffer right after use of this function which could
cause issues later on. Don't use these functions in new code.
*/
PyAPI_FUNC(int) /* abi_only */
PyObject_CheckReadBuffer(PyObject *obj)
{
PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
Py_buffer view;
if (pb == NULL ||
pb->bf_getbuffer == NULL)
return 0;
if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
PyErr_Clear();
return 0;
}
PyBuffer_Release(&view);
return 1;
}
static int
as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
{
Py_buffer view;
if (obj == NULL || buffer == NULL || buffer_len == NULL) {
null_error();
return -1;
}
if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
return -1;
*buffer = view.buf;
*buffer_len = view.len;
PyBuffer_Release(&view);
return 0;
}
/* Takes an arbitrary object which must support the (character, single segment)
buffer interface and returns a pointer to a read-only memory location
usable as character based input for subsequent processing.
Return 0 on success. buffer and buffer_len are only set in case no error
occurs. Otherwise, -1 is returned and an exception set. */
PyAPI_FUNC(int) /* abi_only */
PyObject_AsCharBuffer(PyObject *obj,
const char **buffer,
Py_ssize_t *buffer_len)
{
return as_read_buffer(obj, (const void **)buffer, buffer_len);
}
/* Same as PyObject_AsCharBuffer() except that this API expects (readable,
single segment) buffer interface and returns a pointer to a read-only memory
location which can contain arbitrary data.
0 is returned on success. buffer and buffer_len are only set in case no
error occurs. Otherwise, -1 is returned and an exception set. */
PyAPI_FUNC(int) /* abi_only */
PyObject_AsReadBuffer(PyObject *obj,
const void **buffer,
Py_ssize_t *buffer_len)
{
return as_read_buffer(obj, buffer, buffer_len);
}
/* Takes an arbitrary object which must support the (writable, single segment)
buffer interface and returns a pointer to a writable memory location in
buffer of size 'buffer_len'.
Return 0 on success. buffer and buffer_len are only set in case no error
occurs. Otherwise, -1 is returned and an exception set. */
PyAPI_FUNC(int) /* abi_only */
PyObject_AsWriteBuffer(PyObject *obj,
void **buffer,
Py_ssize_t *buffer_len)
{
PyBufferProcs *pb;
Py_buffer view;
if (obj == NULL || buffer == NULL || buffer_len == NULL) {
null_error();
return -1;
}
pb = Py_TYPE(obj)->tp_as_buffer;
if (pb == NULL ||
pb->bf_getbuffer == NULL ||
((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
PyErr_SetString(PyExc_TypeError,
"expected a writable bytes-like object");
return -1;
}
*buffer = view.buf;
*buffer_len = view.len;
PyBuffer_Release(&view);
return 0;
}
/* Buffer C-API for Python 3.0 */
int
PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
{
if (flags != PyBUF_SIMPLE) { /* fast path */
if (flags == PyBUF_READ || flags == PyBUF_WRITE) {
PyErr_BadInternalCall();
return -1;
}
}
PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
if (pb == NULL || pb->bf_getbuffer == NULL) {
PyErr_Format(PyExc_TypeError,
"a bytes-like object is required, not '%.100s'",
Py_TYPE(obj)->tp_name);
return -1;
}
int res = (*pb->bf_getbuffer)(obj, view, flags);
assert(_Py_CheckSlotResult(obj, "getbuffer", res >= 0));
return res;
}
static int
_IsFortranContiguous(const Py_buffer *view)
{
Py_ssize_t sd, dim;
int i;
/* 1) len = product(shape) * itemsize
2) itemsize > 0
3) len = 0 <==> exists i: shape[i] = 0 */
if (view->len == 0) return 1;
if (view->strides == NULL) { /* C-contiguous by definition */
/* Trivially F-contiguous */
if (view->ndim <= 1) return 1;
/* ndim > 1 implies shape != NULL */
assert(view->shape != NULL);
/* Effectively 1-d */
sd = 0;
for (i=0; i<view->ndim; i++) {
if (view->shape[i] > 1) sd += 1;
}
return sd <= 1;
}
/* strides != NULL implies both of these */
assert(view->ndim > 0);
assert(view->shape != NULL);
sd = view->itemsize;
for (i=0; i<view->ndim; i++) {
dim = view->shape[i];
if (dim > 1 && view->strides[i] != sd) {
return 0;
}
sd *= dim;
}
return 1;
}
static int
_IsCContiguous(const Py_buffer *view)
{
Py_ssize_t sd, dim;
int i;
/* 1) len = product(shape) * itemsize
2) itemsize > 0
3) len = 0 <==> exists i: shape[i] = 0 */
if (view->len == 0) return 1;
if (view->strides == NULL) return 1; /* C-contiguous by definition */
/* strides != NULL implies both of these */
assert(view->ndim > 0);
assert(view->shape != NULL);
sd = view->itemsize;
for (i=view->ndim-1; i>=0; i--) {
dim = view->shape[i];
if (dim > 1 && view->strides[i] != sd) {
return 0;
}
sd *= dim;
}
return 1;
}
int
PyBuffer_IsContiguous(const Py_buffer *view, char order)
{
if (view->suboffsets != NULL) return 0;
if (order == 'C')
return _IsCContiguous(view);
else if (order == 'F')
return _IsFortranContiguous(view);
else if (order == 'A')
return (_IsCContiguous(view) || _IsFortranContiguous(view));
return 0;
}
void*
PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices)
{
char* pointer;
int i;
pointer = (char *)view->buf;
for (i = 0; i < view->ndim; i++) {
pointer += view->strides[i]*indices[i];
if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
pointer = *((char**)pointer) + view->suboffsets[i];
}
}
return (void*)pointer;
}
static void
_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
{
int k;
for (k=0; k<nd; k++) {
if (index[k] < shape[k]-1) {
index[k]++;
break;
}
else {
index[k] = 0;
}
}
}
static void
_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
{
int k;
for (k=nd-1; k>=0; k--) {
if (index[k] < shape[k]-1) {
index[k]++;
break;
}
else {
index[k] = 0;
}
}
}
Py_ssize_t
PyBuffer_SizeFromFormat(const char *format)
{
PyObject *calcsize = NULL;
PyObject *res = NULL;
PyObject *fmt = NULL;
Py_ssize_t itemsize = -1;
calcsize = PyImport_ImportModuleAttrString("struct", "calcsize");
if (calcsize == NULL) {
goto done;
}
fmt = PyUnicode_FromString(format);
if (fmt == NULL) {
goto done;
}
res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
if (res == NULL) {
goto done;
}
itemsize = PyLong_AsSsize_t(res);
if (itemsize < 0) {
goto done;
}
done:
Py_XDECREF(calcsize);
Py_XDECREF(fmt);
Py_XDECREF(res);
return itemsize;
}
int
PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
{
int k;
void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
Py_ssize_t *indices, elements;
char *ptr;
const char *src;
if (len > view->len) {
len = view->len;
}
if (PyBuffer_IsContiguous(view, fort)) {
/* simplest copy is all that is needed */
memcpy(view->buf, buf, len);
return 0;
}
/* Otherwise a more elaborate scheme is needed */
/* view->ndim <= 64 */
indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
if (indices == NULL) {
PyErr_NoMemory();
return -1;
}
for (k=0; k<view->ndim;k++) {
indices[k] = 0;
}
if (fort == 'F') {
addone = _Py_add_one_to_index_F;
}
else {
addone = _Py_add_one_to_index_C;
}
src = buf;
/* XXX : This is not going to be the fastest code in the world
several optimizations are possible.
*/
elements = len / view->itemsize;
while (elements--) {
ptr = PyBuffer_GetPointer(view, indices);
memcpy(ptr, src, view->itemsize);
src += view->itemsize;
addone(view->ndim, indices, view->shape);
}
PyMem_Free(indices);
return 0;
}
int PyObject_CopyData(PyObject *dest, PyObject *src)
{
Py_buffer view_dest, view_src;
int k;
Py_ssize_t *indices, elements;
char *dptr, *sptr;
if (!PyObject_CheckBuffer(dest) ||
!PyObject_CheckBuffer(src)) {
PyErr_SetString(PyExc_TypeError,
"both destination and source must be "\
"bytes-like objects");
return -1;
}
if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
PyBuffer_Release(&view_dest);
return -1;
}
if (view_dest.len < view_src.len) {
PyErr_SetString(PyExc_BufferError,
"destination is too small to receive data from source");
PyBuffer_Release(&view_dest);
PyBuffer_Release(&view_src);
return -1;
}
if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
PyBuffer_IsContiguous(&view_src, 'C')) ||
(PyBuffer_IsContiguous(&view_dest, 'F') &&
PyBuffer_IsContiguous(&view_src, 'F'))) {
/* simplest copy is all that is needed */
memcpy(view_dest.buf, view_src.buf, view_src.len);
PyBuffer_Release(&view_dest);
PyBuffer_Release(&view_src);
return 0;
}
/* Otherwise a more elaborate copy scheme is needed */
/* XXX(nnorwitz): need to check for overflow! */
indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
if (indices == NULL) {
PyErr_NoMemory();
PyBuffer_Release(&view_dest);
PyBuffer_Release(&view_src);
return -1;
}
for (k=0; k<view_src.ndim;k++) {
indices[k] = 0;
}
elements = 1;
for (k=0; k<view_src.ndim; k++) {
/* XXX(nnorwitz): can this overflow? */
elements *= view_src.shape[k];
}
while (elements--) {
_Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
dptr = PyBuffer_GetPointer(&view_dest, indices);
sptr = PyBuffer_GetPointer(&view_src, indices);
memcpy(dptr, sptr, view_src.itemsize);
}
PyMem_Free(indices);
PyBuffer_Release(&view_dest);
PyBuffer_Release(&view_src);
return 0;
}
void
PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
Py_ssize_t *strides, int itemsize,
char fort)
{
int k;
Py_ssize_t sd;
sd = itemsize;
if (fort == 'F') {
for (k=0; k<nd; k++) {
strides[k] = sd;
sd *= shape[k];
}
}
else {
for (k=nd-1; k>=0; k--) {
strides[k] = sd;
sd *= shape[k];
}
}
return;
}
int
PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
int readonly, int flags)
{
if (view == NULL) {
PyErr_SetString(PyExc_BufferError,
"PyBuffer_FillInfo: view==NULL argument is obsolete");
return -1;
}
if (flags != PyBUF_SIMPLE) { /* fast path */
if (flags == PyBUF_READ || flags == PyBUF_WRITE) {
PyErr_BadInternalCall();
return -1;
}
if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
(readonly == 1)) {
PyErr_SetString(PyExc_BufferError,
"Object is not writable.");
return -1;
}
}
view->obj = Py_XNewRef(obj);
view->buf = buf;
view->len = len;
view->readonly = readonly;
view->itemsize = 1;
view->format = NULL;
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
view->format = "B";
view->ndim = 1;
view->shape = NULL;
if ((flags & PyBUF_ND) == PyBUF_ND)
view->shape = &(view->len);
view->strides = NULL;
if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
view->strides = &(view->itemsize);
view->suboffsets = NULL;
view->internal = NULL;
return 0;
}
void
PyBuffer_Release(Py_buffer *view)
{
PyObject *obj = view->obj;
PyBufferProcs *pb;
if (obj == NULL)
return;
pb = Py_TYPE(obj)->tp_as_buffer;
if (pb && pb->bf_releasebuffer) {
pb->bf_releasebuffer(obj, view);
}
view->obj = NULL;
Py_DECREF(obj);
}
static int
_buffer_release_call(void *arg)
{
PyBuffer_Release((Py_buffer *)arg);
return 0;
}
int
_PyBuffer_ReleaseInInterpreter(PyInterpreterState *interp,
Py_buffer *view)
{
return _Py_CallInInterpreter(interp, _buffer_release_call, view);
}
int
_PyBuffer_ReleaseInInterpreterAndRawFree(PyInterpreterState *interp,
Py_buffer *view)
{
return _Py_CallInInterpreterAndRawFree(interp, _buffer_release_call, view);
}
PyObject *
PyObject_Format(PyObject *obj, PyObject *format_spec)
{
PyObject *meth;
PyObject *empty = NULL;
PyObject *result = NULL;
if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
PyErr_Format(PyExc_SystemError,
"Format specifier must be a string, not %.200s",
Py_TYPE(format_spec)->tp_name);
return NULL;
}
/* Fast path for common types. */
if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
if (PyUnicode_CheckExact(obj)) {
return Py_NewRef(obj);
}
if (PyLong_CheckExact(obj)) {
return PyObject_Str(obj);
}
}
/* If no format_spec is provided, use an empty string */
if (format_spec == NULL) {
empty = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
format_spec = empty;
}
/* Find the (unbound!) __format__ method */
meth = _PyObject_LookupSpecial(obj, &_Py_ID(__format__));
if (meth == NULL) {
PyThreadState *tstate = _PyThreadState_GET();
if (!_PyErr_Occurred(tstate)) {
_PyErr_Format(tstate, PyExc_TypeError,
"Type %.100s doesn't define __format__",
Py_TYPE(obj)->tp_name);
}
goto done;
}
/* And call it. */
result = PyObject_CallOneArg(meth, format_spec);
Py_DECREF(meth);
if (result && !PyUnicode_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%T.__format__() must return a str, not %T",
obj, result);
Py_SETREF(result, NULL);
goto done;
}
done:
Py_XDECREF(empty);
return result;
}
/* Operations on numbers */
int
PyNumber_Check(PyObject *o)
{
if (o == NULL)
return 0;
PyNumberMethods *nb = Py_TYPE(o)->tp_as_number;
return nb && (nb->nb_index || nb->nb_int || nb->nb_float || PyComplex_Check(o));
}
/* Binary operators */
#define NB_SLOT(x) offsetof(PyNumberMethods, x)
#define NB_BINOP(nb_methods, slot) \
(*(binaryfunc*)(& ((char*)nb_methods)[slot]))
#define NB_TERNOP(nb_methods, slot) \
(*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
/*
Calling scheme used for binary operations:
Order operations are tried until either a valid result or error:
w.op(v,w)[*], v.op(v,w), w.op(v,w)
[*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of
Py_TYPE(v)
*/
static PyObject *
binary_op1(PyObject *v, PyObject *w, const int op_slot
#ifndef NDEBUG
, const char *op_name
#endif
)
{
binaryfunc slotv;
if (Py_TYPE(v)->tp_as_number != NULL) {
slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot);
}
else {
slotv = NULL;
}
binaryfunc slotw;
if (!Py_IS_TYPE(w, Py_TYPE(v)) && Py_TYPE(w)->tp_as_number != NULL) {
slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot);
if (slotw == slotv) {
slotw = NULL;
}
}
else {
slotw = NULL;
}
if (slotv) {
PyObject *x;
if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
x = slotw(v, w);
if (x != Py_NotImplemented)
return x;
Py_DECREF(x); /* can't do it */
slotw = NULL;
}
x = slotv(v, w);
assert(_Py_CheckSlotResult(v, op_name, x != NULL));
if (x != Py_NotImplemented) {
return x;
}
Py_DECREF(x); /* can't do it */
}
if (slotw) {
PyObject *x = slotw(v, w);
assert(_Py_CheckSlotResult(w, op_name, x != NULL));
if (x != Py_NotImplemented) {
return x;
}
Py_DECREF(x); /* can't do it */
}
Py_RETURN_NOTIMPLEMENTED;
}
#ifdef NDEBUG
# define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot)
#else
# define BINARY_OP1(v, w, op_slot, op_name) binary_op1(v, w, op_slot, op_name)
#endif
static PyObject *
binop_type_error(PyObject *v, PyObject *w, const char *op_name)
{
PyErr_Format(PyExc_TypeError,
"unsupported operand type(s) for %.100s: "
"'%.100s' and '%.100s'",
op_name,
Py_TYPE(v)->tp_name,
Py_TYPE(w)->tp_name);
return NULL;
}
static PyObject *
binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
{
PyObject *result = BINARY_OP1(v, w, op_slot, op_name);
if (result == Py_NotImplemented) {
Py_DECREF(result);
return binop_type_error(v, w, op_name);
}
return result;
}
/*
Calling scheme used for ternary operations:
Order operations are tried until either a valid result or error:
v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
*/
static PyObject *
ternary_op(PyObject *v,
PyObject *w,
PyObject *z,
const int op_slot,
const char *op_name
)
{
PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
PyNumberMethods *mw = Py_TYPE(w)->tp_as_number;
ternaryfunc slotv;
if (mv != NULL) {
slotv = NB_TERNOP(mv, op_slot);
}
else {
slotv = NULL;
}
ternaryfunc slotw;
if (!Py_IS_TYPE(w, Py_TYPE(v)) && mw != NULL) {
slotw = NB_TERNOP(mw, op_slot);
if (slotw == slotv) {
slotw = NULL;
}
}
else {
slotw = NULL;
}
if (slotv) {
PyObject *x;
if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
x = slotw(v, w, z);
if (x != Py_NotImplemented) {
return x;
}
Py_DECREF(x); /* can't do it */
slotw = NULL;
}
x = slotv(v, w, z);
assert(_Py_CheckSlotResult(v, op_name, x != NULL));
if (x != Py_NotImplemented) {
return x;
}
Py_DECREF(x); /* can't do it */
}
if (slotw) {
PyObject *x = slotw(v, w, z);
assert(_Py_CheckSlotResult(w, op_name, x != NULL));
if (x != Py_NotImplemented) {
return x;
}
Py_DECREF(x); /* can't do it */
}
PyNumberMethods *mz = Py_TYPE(z)->tp_as_number;
if (mz != NULL) {
ternaryfunc slotz = NB_TERNOP(mz, op_slot);
if (slotz == slotv || slotz == slotw) {
slotz = NULL;
}
if (slotz) {
PyObject *x = slotz(v, w, z);
assert(_Py_CheckSlotResult(z, op_name, x != NULL));
if (x != Py_NotImplemented) {
return x;
}
Py_DECREF(x); /* can't do it */
}
}
if (z == Py_None) {
PyErr_Format(
PyExc_TypeError,
"unsupported operand type(s) for %.100s: "
"'%.100s' and '%.100s'",
op_name,
Py_TYPE(v)->tp_name,
Py_TYPE(w)->tp_name);
}
else {
PyErr_Format(
PyExc_TypeError,
"unsupported operand type(s) for %.100s: "
"'%.100s', '%.100s', '%.100s'",
op_name,
Py_TYPE(v)->tp_name,
Py_TYPE(w)->tp_name,
Py_TYPE(z)->tp_name);
}
return NULL;
}
#define BINARY_FUNC(func, op, op_name) \
PyObject * \
func(PyObject *v, PyObject *w) { \
return binary_op(v, w, NB_SLOT(op), op_name); \
}
BINARY_FUNC(PyNumber_Or, nb_or, "|")
BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
BINARY_FUNC(PyNumber_And, nb_and, "&")
BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
PyObject *
PyNumber_Add(PyObject *v, PyObject *w)
{
PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_add), "+");
if (result != Py_NotImplemented) {
return result;
}
Py_DECREF(result);
PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
if (m && m->sq_concat) {
result = (*m->sq_concat)(v, w);
assert(_Py_CheckSlotResult(v, "+", result != NULL));
return result;
}
return binop_type_error(v, w, "+");
}
static PyObject *
sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
{
Py_ssize_t count;
if (_PyIndex_Check(n)) {
count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
if (count == -1 && PyErr_Occurred()) {
return NULL;
}
}
else {
return type_error("can't multiply sequence by "
"non-int of type '%.200s'", n);
}
PyObject *res = (*repeatfunc)(seq, count);
assert(_Py_CheckSlotResult(seq, "*", res != NULL));
return res;
}
PyObject *
PyNumber_Multiply(PyObject *v, PyObject *w)
{
PyObject *result = BINARY_OP1(v, w, NB_SLOT(nb_multiply), "*");
if (result == Py_NotImplemented) {
PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Py_DECREF(result);
if (mv && mv->sq_repeat) {
return sequence_repeat(mv->sq_repeat, v, w);
}
else if (mw && mw->sq_repeat) {
return sequence_repeat(mw->sq_repeat, w, v);
}
result = binop_type_error(v, w, "*");
}
return result;
}
BINARY_FUNC(PyNumber_MatrixMultiply, nb_matrix_multiply, "@")
BINARY_FUNC(PyNumber_FloorDivide, nb_floor_divide, "//")
BINARY_FUNC(PyNumber_TrueDivide, nb_true_divide, "/")
BINARY_FUNC(PyNumber_Remainder, nb_remainder, "%")
PyObject *
PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
{
return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
}
PyObject *
_PyNumber_PowerNoMod(PyObject *lhs, PyObject *rhs)
{
return PyNumber_Power(lhs, rhs, Py_None);
}
/* Binary in-place operators */
/* The in-place operators are defined to fall back to the 'normal',
non in-place operations, if the in-place methods are not in place.
- If the left hand object has the appropriate struct members, and
they are filled, call the appropriate function and return the
result. No coercion is done on the arguments; the left-hand object
is the one the operation is performed on, and it's up to the
function to deal with the right-hand object.
- Otherwise, in-place modification is not supported. Handle it exactly as
a non in-place operation of the same kind.
*/
static PyObject *
binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot
#ifndef NDEBUG
, const char *op_name
#endif
)
{
PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
if (mv != NULL) {
binaryfunc slot = NB_BINOP(mv, iop_slot);
if (slot) {
PyObject *x = (slot)(v, w);
assert(_Py_CheckSlotResult(v, op_name, x != NULL));
if (x != Py_NotImplemented) {
return x;
}
Py_DECREF(x);
}
}
#ifdef NDEBUG
return binary_op1(v, w, op_slot);
#else
return binary_op1(v, w, op_slot, op_name);
#endif
}
#ifdef NDEBUG
# define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot)
#else
# define BINARY_IOP1(v, w, iop_slot, op_slot, op_name) binary_iop1(v, w, iop_slot, op_slot, op_name)
#endif
static PyObject *
binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
const char *op_name)
{
PyObject *result = BINARY_IOP1(v, w, iop_slot, op_slot, op_name);
if (result == Py_NotImplemented) {
Py_DECREF(result);
return binop_type_error(v, w, op_name);
}
return result;
}
static PyObject *
ternary_iop(PyObject *v, PyObject *w, PyObject *z, const int iop_slot, const int op_slot,
const char *op_name)
{
PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
if (mv != NULL) {
ternaryfunc slot = NB_TERNOP(mv, iop_slot);
if (slot) {
PyObject *x = (slot)(v, w, z);
if (x != Py_NotImplemented) {
return x;
}
Py_DECREF(x);
}
}
return ternary_op(v, w, z, op_slot, op_name);
}
#define INPLACE_BINOP(func, iop, op, op_name) \
PyObject * \
func(PyObject *v, PyObject *w) { \
return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
}
INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
INPLACE_BINOP(PyNumber_InPlaceMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
INPLACE_BINOP(PyNumber_InPlaceFloorDivide, nb_inplace_floor_divide, nb_floor_divide, "//=")
INPLACE_BINOP(PyNumber_InPlaceTrueDivide, nb_inplace_true_divide, nb_true_divide, "/=")
INPLACE_BINOP(PyNumber_InPlaceRemainder, nb_inplace_remainder, nb_remainder, "%=")
PyObject *
PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
{
PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_add),
NB_SLOT(nb_add), "+=");
if (result == Py_NotImplemented) {
PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
Py_DECREF(result);
if (m != NULL) {
binaryfunc func = m->sq_inplace_concat;
if (func == NULL)
func = m->sq_concat;
if (func != NULL) {
result = func(v, w);
assert(_Py_CheckSlotResult(v, "+=", result != NULL));
return result;
}
}
result = binop_type_error(v, w, "+=");
}
return result;
}
PyObject *
PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
{
PyObject *result = BINARY_IOP1(v, w, NB_SLOT(nb_inplace_multiply),
NB_SLOT(nb_multiply), "*=");
if (result == Py_NotImplemented) {
ssizeargfunc f = NULL;
PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Py_DECREF(result);
if (mv != NULL) {
f = mv->sq_inplace_repeat;
if (f == NULL)
f = mv->sq_repeat;
if (f != NULL)
return sequence_repeat(f, v, w);
}
else if (mw != NULL) {
/* Note that the right hand operand should not be
* mutated in this case so sq_inplace_repeat is not
* used. */
if (mw->sq_repeat)
return sequence_repeat(mw->sq_repeat, w, v);
}
result = binop_type_error(v, w, "*=");
}
return result;
}
PyObject *
PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
{
return ternary_iop(v, w, z, NB_SLOT(nb_inplace_power),
NB_SLOT(nb_power), "**=");
}
PyObject *
_PyNumber_InPlacePowerNoMod(PyObject *lhs, PyObject *rhs)
{
return PyNumber_InPlacePower(lhs, rhs, Py_None);
}
/* Unary operators and functions */
#define UNARY_FUNC(func, op, meth_name, descr) \
PyObject * \
func(PyObject *o) { \
if (o == NULL) { \
return null_error(); \
} \
\
PyNumberMethods *m = Py_TYPE(o)->tp_as_number; \
if (m && m->op) { \
PyObject *res = (*m->op)(o); \
assert(_Py_CheckSlotResult(o, #meth_name, res != NULL)); \
return res; \
} \
\
return type_error("bad operand type for "descr": '%.200s'", o); \
}
UNARY_FUNC(PyNumber_Negative, nb_negative, __neg__, "unary -")
UNARY_FUNC(PyNumber_Positive, nb_positive, __pos__, "unary +")
UNARY_FUNC(PyNumber_Invert, nb_invert, __invert__, "unary ~")
UNARY_FUNC(PyNumber_Absolute, nb_absolute, __abs__, "abs()")
int
PyIndex_Check(PyObject *obj)
{
return _PyIndex_Check(obj);
}
/* Return a Python int from the object item.
Can return an instance of int subclass.
Raise TypeError if the result is not an int
or if the object cannot be interpreted as an index.
*/
PyObject *
_PyNumber_Index(PyObject *item)
{
if (item == NULL) {
return null_error();
}
if (PyLong_Check(item)) {
return Py_NewRef(item);
}
if (!_PyIndex_Check(item)) {
PyErr_Format(PyExc_TypeError,
"'%.200s' object cannot be interpreted "
"as an integer", Py_TYPE(item)->tp_name);
return NULL;
}
PyObject *result = Py_TYPE(item)->tp_as_number->nb_index(item);
assert(_Py_CheckSlotResult(item, "__index__", result != NULL));
if (!result || PyLong_CheckExact(result)) {
return result;
}
if (!PyLong_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%T.__index__() must return an int, not %T",
item, result);
Py_DECREF(result);
return NULL;
}
/* Issue #17576: warn if 'result' not of exact type int. */
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
"%T.__index__() must return an int, not %T. "
"The ability to return an instance of a strict subclass of int "
"is deprecated, and may be removed in a future version of Python.",
item, result)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* Return an exact Python int from the object item.
Raise TypeError if the result is not an int
or if the object cannot be interpreted as an index.
*/
PyObject *
PyNumber_Index(PyObject *item)
{
PyObject *result = _PyNumber_Index(item);
if (result != NULL && !PyLong_CheckExact(result)) {
Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
}
return result;
}
/* Return an error on Overflow only if err is not NULL*/
Py_ssize_t
PyNumber_AsSsize_t(PyObject *item, PyObject *err)
{
Py_ssize_t result;
PyObject *runerr;
PyObject *value = _PyNumber_Index(item);
if (value == NULL)
return -1;
/* We're done if PyLong_AsSsize_t() returns without error. */
result = PyLong_AsSsize_t(value);
if (result != -1)
goto finish;
PyThreadState *tstate = _PyThreadState_GET();
runerr = _PyErr_Occurred(tstate);
if (!runerr) {
goto finish;
}
/* Error handling code -- only manage OverflowError differently */
if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) {
goto finish;
}
_PyErr_Clear(tstate);
/* If no error-handling desired then the default clipping
is sufficient. */
if (!err) {
assert(PyLong_Check(value));
/* Whether or not it is less than or equal to
zero is determined by the sign of ob_size
*/
if (_PyLong_IsNegative((PyLongObject *)value))
result = PY_SSIZE_T_MIN;
else
result = PY_SSIZE_T_MAX;
}
else {
/* Otherwise replace the error with caller's error object. */
_PyErr_Format(tstate, err,
"cannot fit '%.200s' into an index-sized integer",
Py_TYPE(item)->tp_name);
}
finish:
Py_DECREF(value);
return result;
}
PyObject *
PyNumber_Long(PyObject *o)
{
PyObject *result;
PyNumberMethods *m;
Py_buffer view;
if (o == NULL) {
return null_error();
}
if (PyLong_CheckExact(o)) {
return Py_NewRef(o);
}
m = Py_TYPE(o)->tp_as_number;
if (m && m->nb_int) { /* This should include subclasses of int */
/* Convert using the nb_int slot, which should return something
of exact type int. */
result = m->nb_int(o);
assert(_Py_CheckSlotResult(o, "__int__", result != NULL));
if (!result || PyLong_CheckExact(result)) {
return result;
}
if (!PyLong_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%T.__int__() must return an int, not %T",
o, result);
Py_DECREF(result);
return NULL;
}
/* Issue #17576: warn if 'result' not of exact type int. */
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
"%T.__int__() must return an int, not %T. "
"The ability to return an instance of a strict subclass of int "
"is deprecated, and may be removed in a future version of Python.",
o, result)) {
Py_DECREF(result);
return NULL;
}
Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
return result;
}
if (m && m->nb_index) {
return PyNumber_Index(o);
}
if (PyUnicode_Check(o))
/* The below check is done in PyLong_FromUnicodeObject(). */
return PyLong_FromUnicodeObject(o, 10);
if (PyBytes_Check(o))
/* need to do extra error checking that PyLong_FromString()
* doesn't do. In particular int('9\x005') must raise an
* exception, not truncate at the null.
*/
return _PyLong_FromBytes(PyBytes_AS_STRING(o),
PyBytes_GET_SIZE(o), 10);
if (PyByteArray_Check(o))
return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
PyByteArray_GET_SIZE(o), 10);
if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
PyObject *bytes;
/* Copy to NUL-terminated buffer. */
bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
if (bytes == NULL) {
PyBuffer_Release(&view);
return NULL;
}
result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
PyBytes_GET_SIZE(bytes), 10);
Py_DECREF(bytes);
PyBuffer_Release(&view);
return result;
}
return type_error("int() argument must be a string, a bytes-like object "
"or a real number, not '%.200s'", o);
}
PyObject *
PyNumber_Float(PyObject *o)
{
if (o == NULL) {
return null_error();
}
if (PyFloat_CheckExact(o)) {
return Py_NewRef(o);
}
PyNumberMethods *m = Py_TYPE(o)->tp_as_number;
if (m && m->nb_float) { /* This should include subclasses of float */
PyObject *res = m->nb_float(o);
assert(_Py_CheckSlotResult(o, "__float__", res != NULL));
if (!res || PyFloat_CheckExact(res)) {
return res;
}
if (!PyFloat_Check(res)) {
PyErr_Format(PyExc_TypeError,
"%T.__float__() must return a float, not %T", o, res);
Py_DECREF(res);
return NULL;
}
/* Issue #26983: warn if 'res' not of exact type float. */
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
"%T.__float__() must return a float, not %T. "
"The ability to return an instance of a strict subclass of float "
"is deprecated, and may be removed in a future version of Python.",
o, res)) {
Py_DECREF(res);
return NULL;
}
double val = PyFloat_AS_DOUBLE(res);
Py_DECREF(res);
return PyFloat_FromDouble(val);
}
if (m && m->nb_index) {
PyObject *res = _PyNumber_Index(o);
if (!res) {
return NULL;
}
double val = PyLong_AsDouble(res);
Py_DECREF(res);
if (val == -1.0 && PyErr_Occurred()) {
return NULL;
}
return PyFloat_FromDouble(val);
}
/* A float subclass with nb_float == NULL */
if (PyFloat_Check(o)) {
return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
}
return PyFloat_FromString(o);
}
PyObject *
PyNumber_ToBase(PyObject *n, int base)
{
if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
PyErr_SetString(PyExc_SystemError,
"PyNumber_ToBase: base must be 2, 8, 10 or 16");
return NULL;
}
PyObject *index = _PyNumber_Index(n);
if (!index)
return NULL;
PyObject *res = _PyLong_Format(index, base);
Py_DECREF(index);
return res;
}
/* Operations on sequences */
int
PySequence_Check(PyObject *s)
{
if (PyDict_Check(s))
return 0;
return Py_TYPE(s)->tp_as_sequence &&
Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
}
Py_ssize_t
PySequence_Size(PyObject *s)
{
if (s == NULL) {
null_error();
return -1;
}
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
if (m && m->sq_length) {
Py_ssize_t len = m->sq_length(s);
assert(_Py_CheckSlotResult(s, "__len__", len >= 0));
return len;
}
if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
type_error("%.200s is not a sequence", s);
return -1;
}
type_error("object of type '%.200s' has no len()", s);
return -1;
}
#undef PySequence_Length
Py_ssize_t
PySequence_Length(PyObject *s)
{
return PySequence_Size(s);
}
#define PySequence_Length PySequence_Size
PyObject *
PySequence_Concat(PyObject *s, PyObject *o)
{
if (s == NULL || o == NULL) {
return null_error();
}
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
if (m && m->sq_concat) {
PyObject *res = m->sq_concat(s, o);
assert(_Py_CheckSlotResult(s, "+", res != NULL));
return res;
}
/* Instances of user classes defining an __add__() method only
have an nb_add slot, not an sq_concat slot. So we fall back
to nb_add if both arguments appear to be sequences. */
if (PySequence_Check(s) && PySequence_Check(o)) {
PyObject *result = BINARY_OP1(s, o, NB_SLOT(nb_add), "+");
if (result != Py_NotImplemented)
return result;
Py_DECREF(result);
}
return type_error("'%.200s' object can't be concatenated", s);
}
PyObject *
PySequence_Repeat(PyObject *o, Py_ssize_t count)
{
if (o == NULL) {
return null_error();
}
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
if (m && m->sq_repeat) {
PyObject *res = m->sq_repeat(o, count);
assert(_Py_CheckSlotResult(o, "*", res != NULL));
return res;
}
/* Instances of user classes defining a __mul__() method only
have an nb_multiply slot, not an sq_repeat slot. so we fall back
to nb_multiply if o appears to be a sequence. */
if (PySequence_Check(o)) {
PyObject *n, *result;
n = PyLong_FromSsize_t(count);
if (n == NULL)
return NULL;
result = BINARY_OP1(o, n, NB_SLOT(nb_multiply), "*");
Py_DECREF(n);
if (result != Py_NotImplemented)
return result;
Py_DECREF(result);
}
return type_error("'%.200s' object can't be repeated", o);
}
PyObject *
PySequence_InPlaceConcat(PyObject *s, PyObject *o)
{
if (s == NULL || o == NULL) {
return null_error();
}
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
if (m && m->sq_inplace_concat) {
PyObject *res = m->sq_inplace_concat(s, o);
assert(_Py_CheckSlotResult(s, "+=", res != NULL));
return res;
}
if (m && m->sq_concat) {
PyObject *res = m->sq_concat(s, o);
assert(_Py_CheckSlotResult(s, "+", res != NULL));
return res;
}
if (PySequence_Check(s) && PySequence_Check(o)) {
PyObject *result = BINARY_IOP1(s, o, NB_SLOT(nb_inplace_add),
NB_SLOT(nb_add), "+=");
if (result != Py_NotImplemented)
return result;
Py_DECREF(result);
}
return type_error("'%.200s' object can't be concatenated", s);
}
PyObject *
PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
{
if (o == NULL) {
return null_error();
}
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
if (m && m->sq_inplace_repeat) {
PyObject *res = m->sq_inplace_repeat(o, count);
assert(_Py_CheckSlotResult(o, "*=", res != NULL));
return res;
}
if (m && m->sq_repeat) {
PyObject *res = m->sq_repeat(o, count);
assert(_Py_CheckSlotResult(o, "*", res != NULL));
return res;
}
if (PySequence_Check(o)) {
PyObject *n, *result;
n = PyLong_FromSsize_t(count);
if (n == NULL)
return NULL;
result = BINARY_IOP1(o, n, NB_SLOT(nb_inplace_multiply),
NB_SLOT(nb_multiply), "*=");
Py_DECREF(n);
if (result != Py_NotImplemented)
return result;
Py_DECREF(result);
}
return type_error("'%.200s' object can't be repeated", o);
}
PyObject *
PySequence_GetItem(PyObject *s, Py_ssize_t i)
{
if (s == NULL) {
return null_error();
}
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
if (m && m->sq_item) {
if (i < 0) {
if (m->sq_length) {
Py_ssize_t l = (*m->sq_length)(s);
assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
if (l < 0) {
return NULL;
}
i += l;
}
}
PyObject *res = m->sq_item(s, i);
assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
return res;
}
if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
return type_error("%.200s is not a sequence", s);
}
return type_error("'%.200s' object does not support indexing", s);
}
PyObject *
PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
{
if (!s) {
return null_error();
}
PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
if (mp && mp->mp_subscript) {
PyObject *slice = _PySlice_FromIndices(i1, i2);
if (!slice) {
return NULL;
}
PyObject *res = mp->mp_subscript(s, slice);
assert(_Py_CheckSlotResult(s, "__getitem__", res != NULL));
Py_DECREF(slice);
return res;
}
return type_error("'%.200s' object is unsliceable", s);
}
int
PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
{
if (s == NULL) {
null_error();
return -1;
}
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
if (m && m->sq_ass_item) {
if (i < 0) {
if (m->sq_length) {
Py_ssize_t l = (*m->sq_length)(s);
assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
if (l < 0) {
return -1;
}
i += l;
}
}
int res = m->sq_ass_item(s, i, o);
assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
return res;
}
if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
type_error("%.200s is not a sequence", s);
return -1;
}
type_error("'%.200s' object does not support item assignment", s);
return -1;
}
int
PySequence_DelItem(PyObject *s, Py_ssize_t i)
{
if (s == NULL) {
null_error();
return -1;
}
PySequenceMethods *m = Py_TYPE(s)->tp_as_sequence;
if (m && m->sq_ass_item) {
if (i < 0) {
if (m->sq_length) {
Py_ssize_t l = (*m->sq_length)(s);
assert(_Py_CheckSlotResult(s, "__len__", l >= 0));
if (l < 0) {
return -1;
}
i += l;
}
}
int res = m->sq_ass_item(s, i, (PyObject *)NULL);
assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
return res;
}
if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
type_error("%.200s is not a sequence", s);
return -1;
}
type_error("'%.200s' object doesn't support item deletion", s);
return -1;
}
int
PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
{
if (s == NULL) {
null_error();
return -1;
}
PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
if (mp && mp->mp_ass_subscript) {
PyObject *slice = _PySlice_FromIndices(i1, i2);
if (!slice)
return -1;
int res = mp->mp_ass_subscript(s, slice, o);
assert(_Py_CheckSlotResult(s, "__setitem__", res >= 0));
Py_DECREF(slice);
return res;
}
type_error("'%.200s' object doesn't support slice assignment", s);
return -1;
}
int
PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
{
if (s == NULL) {
null_error();
return -1;
}
PyMappingMethods *mp = Py_TYPE(s)->tp_as_mapping;
if (mp && mp->mp_ass_subscript) {
PyObject *slice = _PySlice_FromIndices(i1, i2);
if (!slice) {
return -1;
}
int res = mp->mp_ass_subscript(s, slice, NULL);
assert(_Py_CheckSlotResult(s, "__delitem__", res >= 0));
Py_DECREF(slice);
return res;
}
type_error("'%.200s' object doesn't support slice deletion", s);
return -1;
}
PyObject *
PySequence_Tuple(PyObject *v)
{
PyObject *it; /* iter(v) */
if (v == NULL) {
return null_error();
}
/* Special-case the common tuple and list cases, for efficiency. */
if (PyTuple_CheckExact(v)) {
/* Note that we can't know whether it's safe to return
a tuple *subclass* instance as-is, hence the restriction
to exact tuples here. In contrast, lists always make
a copy, so there's no need for exactness below. */
return Py_NewRef(v);
}
if (PyList_CheckExact(v))
return PyList_AsTuple(v);
/* Get iterator. */
it = PyObject_GetIter(v);
if (it == NULL)
return NULL;
Py_ssize_t n;
PyObject *buffer[8];
for (n = 0; n < 8; n++) {
PyObject *item = PyIter_Next(it);
if (item == NULL) {
if (PyErr_Occurred()) {
goto fail;
}
Py_DECREF(it);
return _PyTuple_FromArraySteal(buffer, n);
}
buffer[n] = item;
}
PyListObject *list = (PyListObject *)PyList_New(16);
if (list == NULL) {
goto fail;
}
assert(n == 8);
Py_SET_SIZE(list, n);
for (Py_ssize_t j = 0; j < n; j++) {
PyList_SET_ITEM(list, j, buffer[j]);
}
for (;;) {
PyObject *item = PyIter_Next(it);
if (item == NULL) {
if (PyErr_Occurred()) {
Py_DECREF(list);
Py_DECREF(it);
return NULL;
}
break;
}
if (_PyList_AppendTakeRef(list, item) < 0) {
Py_DECREF(list);
Py_DECREF(it);
return NULL;
}
}
Py_DECREF(it);
PyObject *res = _PyList_AsTupleAndClear(list);
Py_DECREF(list);
return res;
fail:
Py_DECREF(it);
while (n > 0) {
n--;
Py_DECREF(buffer[n]);
}
return NULL;
}
PyObject *
PySequence_List(PyObject *v)
{
PyObject *result; /* result list */
PyObject *rv; /* return value from PyList_Extend */
if (v == NULL) {
return null_error();
}
result = PyList_New(0);
if (result == NULL)
return NULL;
rv = _PyList_Extend((PyListObject *)result, v);
if (rv == NULL) {
Py_DECREF(result);
return NULL;
}
Py_DECREF(rv);
return result;
}
PyObject *
PySequence_Fast(PyObject *v, const char *m)
{
PyObject *it;
if (v == NULL) {
return null_error();
}
if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
return Py_NewRef(v);
}
it = PyObject_GetIter(v);
if (it == NULL) {
PyThreadState *tstate = _PyThreadState_GET();
if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
_PyErr_SetString(tstate, PyExc_TypeError, m);
}
return NULL;
}
v = PySequence_List(it);
Py_DECREF(it);
return v;
}
/* Iterate over seq. Result depends on the operation:
PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
set ValueError and return -1 if none found; also return -1 on error.
PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
*/
Py_ssize_t
_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
{
Py_ssize_t n;
int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
PyObject *it; /* iter(seq) */
if (seq == NULL || obj == NULL) {
null_error();
return -1;
}
it = PyObject_GetIter(seq);
if (it == NULL) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
if (operation == PY_ITERSEARCH_CONTAINS) {
type_error(
"argument of type '%.200s' is not a container or iterable",
seq
);
}
else {
type_error("argument of type '%.200s' is not iterable", seq);
}
}
return -1;
}
n = wrapped = 0;
for (;;) {
int cmp;
PyObject *item = PyIter_Next(it);
if (item == NULL) {
if (PyErr_Occurred())
goto Fail;
break;
}
cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
Py_DECREF(item);
if (cmp < 0)
goto Fail;
if (cmp > 0) {
switch (operation) {
case PY_ITERSEARCH_COUNT:
if (n == PY_SSIZE_T_MAX) {
PyErr_SetString(PyExc_OverflowError,
"count exceeds C integer size");
goto Fail;
}
++n;
break;
case PY_ITERSEARCH_INDEX:
if (wrapped) {
PyErr_SetString(PyExc_OverflowError,
"index exceeds C integer size");
goto Fail;
}
goto Done;
case PY_ITERSEARCH_CONTAINS:
n = 1;
goto Done;
default:
Py_UNREACHABLE();
}
}
if (operation == PY_ITERSEARCH_INDEX) {
if (n == PY_SSIZE_T_MAX)
wrapped = 1;
++n;
}
}
if (operation != PY_ITERSEARCH_INDEX)
goto Done;
PyErr_SetString(PyExc_ValueError,
"sequence.index(x): x not in sequence");
/* fall into failure code */
Fail:
n = -1;
/* fall through */
Done:
Py_DECREF(it);
return n;
}
/* Return # of times o appears in s. */
Py_ssize_t
PySequence_Count(PyObject *s, PyObject *o)
{
return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
}
/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
* Use sq_contains if possible, else defer to _PySequence_IterSearch().
*/
int
PySequence_Contains(PyObject *seq, PyObject *ob)
{
PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
if (sqm != NULL && sqm->sq_contains != NULL) {
int res = (*sqm->sq_contains)(seq, ob);
assert(_Py_CheckSlotResult(seq, "__contains__", res >= 0));
return res;
}
Py_ssize_t result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
}
/* Backwards compatibility */
#undef PySequence_In
int
PySequence_In(PyObject *w, PyObject *v)
{
return PySequence_Contains(w, v);
}
Py_ssize_t
PySequence_Index(PyObject *s, PyObject *o)
{
return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
}
/* Operations on mappings */
int
PyMapping_Check(PyObject *o)
{
return o && Py_TYPE(o)->tp_as_mapping &&
Py_TYPE(o)->tp_as_mapping->mp_subscript;
}
Py_ssize_t
PyMapping_Size(PyObject *o)
{
if (o == NULL) {
null_error();
return -1;
}
PyMappingMethods *m = Py_TYPE(o)->tp_as_mapping;
if (m && m->mp_length) {
Py_ssize_t len = m->mp_length(o);
assert(_Py_CheckSlotResult(o, "__len__", len >= 0));
return len;
}
if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
type_error("%.200s is not a mapping", o);
return -1;
}
/* PyMapping_Size() can be called from PyObject_Size(). */
type_error("object of type '%.200s' has no len()", o);
return -1;
}
#undef PyMapping_Length
Py_ssize_t
PyMapping_Length(PyObject *o)
{
return PyMapping_Size(o);
}
#define PyMapping_Length PyMapping_Size
PyObject *
PyMapping_GetItemString(PyObject *o, const char *key)
{
PyObject *okey, *r;
if (key == NULL) {
return null_error();
}
okey = PyUnicode_FromString(key);
if (okey == NULL)
return NULL;
r = PyObject_GetItem(o, okey);
Py_DECREF(okey);
return r;
}
int
PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result)
{
if (key == NULL) {
*result = NULL;
null_error();
return -1;
}
PyObject *okey = PyUnicode_FromString(key);
if (okey == NULL) {
*result = NULL;
return -1;
}
int rc = PyMapping_GetOptionalItem(obj, okey, result);
Py_DECREF(okey);
return rc;
}
int
PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
{
PyObject *okey;
int r;
if (key == NULL) {
null_error();
return -1;
}
okey = PyUnicode_FromString(key);
if (okey == NULL)
return -1;
r = PyObject_SetItem(o, okey, value);
Py_DECREF(okey);
return r;
}
int
PyMapping_HasKeyStringWithError(PyObject *obj, const char *key)
{
PyObject *res;
int rc = PyMapping_GetOptionalItemString(obj, key, &res);
Py_XDECREF(res);
return rc;
}
int
PyMapping_HasKeyWithError(PyObject *obj, PyObject *key)
{
PyObject *res;
int rc = PyMapping_GetOptionalItem(obj, key, &res);
Py_XDECREF(res);
return rc;
}
int
PyMapping_HasKeyString(PyObject *obj, const char *key)
{
PyObject *value;
int rc;
if (obj == NULL) {
// For backward compatibility.
// PyMapping_GetOptionalItemString() crashes if obj is NULL.
null_error();
rc = -1;
}
else {
rc = PyMapping_GetOptionalItemString(obj, key, &value);
}
if (rc < 0) {
PyErr_FormatUnraisable(
"Exception ignored in PyMapping_HasKeyString(); consider using "
"PyMapping_HasKeyStringWithError(), "
"PyMapping_GetOptionalItemString() or PyMapping_GetItemString()");
return 0;
}
Py_XDECREF(value);
return rc;
}
int
PyMapping_HasKey(PyObject *obj, PyObject *key)
{
PyObject *value;
int rc;
if (obj == NULL || key == NULL) {
// For backward compatibility.
// PyMapping_GetOptionalItem() crashes if any of them is NULL.
null_error();
rc = -1;
}
else {
rc = PyMapping_GetOptionalItem(obj, key, &value);
}
if (rc < 0) {
PyErr_FormatUnraisable(
"Exception ignored in PyMapping_HasKey(); consider using "
"PyMapping_HasKeyWithError(), "
"PyMapping_GetOptionalItem() or PyObject_GetItem()");
return 0;
}
Py_XDECREF(value);
return rc;
}
/* This function is quite similar to PySequence_Fast(), but specialized to be
a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
*/
static PyObject *
method_output_as_list(PyObject *o, PyObject *meth)
{
PyObject *it, *result, *meth_output;
assert(o != NULL);
meth_output = PyObject_CallMethodNoArgs(o, meth);
if (meth_output == NULL || PyList_CheckExact(meth_output)) {
return meth_output;
}
it = PyObject_GetIter(meth_output);
if (it == NULL) {
PyThreadState *tstate = _PyThreadState_GET();
if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
_PyErr_Format(tstate, PyExc_TypeError,
"%T.%U() must return an iterable, not %T",
o, meth, meth_output);
}
Py_DECREF(meth_output);
return NULL;
}
Py_DECREF(meth_output);
result = PySequence_List(it);
Py_DECREF(it);
return result;
}
PyObject *
PyMapping_Keys(PyObject *o)
{
if (o == NULL) {
return null_error();
}
if (PyDict_CheckExact(o)) {
return PyDict_Keys(o);
}
return method_output_as_list(o, &_Py_ID(keys));
}
PyObject *
PyMapping_Items(PyObject *o)
{
if (o == NULL) {
return null_error();
}
if (PyDict_CheckExact(o)) {
return PyDict_Items(o);
}
return method_output_as_list(o, &_Py_ID(items));
}
PyObject *
PyMapping_Values(PyObject *o)
{
if (o == NULL) {
return null_error();
}
if (PyDict_CheckExact(o)) {
return PyDict_Values(o);
}
return method_output_as_list(o, &_Py_ID(values));
}
/* isinstance(), issubclass() */
/* abstract_get_bases() has logically 4 return states:
*
* 1. getattr(cls, '__bases__') could raise an AttributeError
* 2. getattr(cls, '__bases__') could raise some other exception
* 3. getattr(cls, '__bases__') could return a tuple
* 4. getattr(cls, '__bases__') could return something other than a tuple
*
* Only state #3 is a non-error state and only it returns a non-NULL object
* (it returns the retrieved tuple).
*
* Any raised AttributeErrors are masked by clearing the exception and
* returning NULL. If an object other than a tuple comes out of __bases__,
* then again, the return value is NULL. So yes, these two situations
* produce exactly the same results: NULL is returned and no error is set.
*
* If some exception other than AttributeError is raised, then NULL is also
* returned, but the exception is not cleared. That's because we want the
* exception to be propagated along.
*
* Callers are expected to test for PyErr_Occurred() when the return value
* is NULL to decide whether a valid exception should be propagated or not.
* When there's no exception to propagate, it's customary for the caller to
* set a TypeError.
*/
static PyObject *
abstract_get_bases(PyObject *cls)
{
PyObject *bases;
(void)PyObject_GetOptionalAttr(cls, &_Py_ID(__bases__), &bases);
if (bases != NULL && !PyTuple_Check(bases)) {
Py_DECREF(bases);
return NULL;
}
return bases;
}
static int
abstract_issubclass(PyObject *derived, PyObject *cls)
{
PyObject *bases = NULL;
Py_ssize_t i, n;
int r = 0;
while (1) {
if (derived == cls) {
Py_XDECREF(bases); /* See below comment */
return 1;
}
/* Use XSETREF to drop bases reference *after* finishing with
derived; bases might be the only reference to it.
XSETREF is used instead of SETREF, because bases is NULL on the
first iteration of the loop.
*/
Py_XSETREF(bases, abstract_get_bases(derived));
if (bases == NULL) {
if (PyErr_Occurred())
return -1;
return 0;
}
n = PyTuple_GET_SIZE(bases);
if (n == 0) {
Py_DECREF(bases);
return 0;
}
/* Avoid recursivity in the single inheritance case */
if (n == 1) {
derived = PyTuple_GET_ITEM(bases, 0);
continue;
}
break;
}
assert(n >= 2);
if (_Py_EnterRecursiveCall(" in __issubclass__")) {
Py_DECREF(bases);
return -1;
}
for (i = 0; i < n; i++) {
r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
if (r != 0) {
break;
}
}
_Py_LeaveRecursiveCall();
Py_DECREF(bases);
return r;
}
static int
check_class(PyObject *cls, const char *error)
{
PyObject *bases = abstract_get_bases(cls);
if (bases == NULL) {
/* Do not mask errors. */
PyThreadState *tstate = _PyThreadState_GET();
if (!_PyErr_Occurred(tstate)) {
_PyErr_SetString(tstate, PyExc_TypeError, error);
}
return 0;
}
Py_DECREF(bases);
return -1;
}
static int
object_isinstance(PyObject *inst, PyObject *cls)
{
PyObject *icls;
int retval;
if (PyType_Check(cls)) {
retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
if (retval == 0) {
retval = PyObject_GetOptionalAttr(inst, &_Py_ID(__class__), &icls);
if (icls != NULL) {
if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
retval = PyType_IsSubtype(
(PyTypeObject *)icls,
(PyTypeObject *)cls);
}
else {
retval = 0;
}
Py_DECREF(icls);
}
}
}
else {
if (!check_class(cls,
"isinstance() arg 2 must be a type, a tuple of types, or a union"))
return -1;
retval = PyObject_GetOptionalAttr(inst, &_Py_ID(__class__), &icls);
if (icls != NULL) {
retval = abstract_issubclass(icls, cls);
Py_DECREF(icls);
}
}
return retval;
}
static int
object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
{
/* Quick test for an exact match */
if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
return 1;
}
/* We know what type's __instancecheck__ does. */
if (PyType_CheckExact(cls)) {
return object_isinstance(inst, cls);
}
if (_PyUnion_Check(cls)) {
cls = _Py_union_args(cls);
}
if (PyTuple_Check(cls)) {
/* Not a general sequence -- that opens up the road to
recursion and stack overflow. */
if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
return -1;
}
Py_ssize_t n = PyTuple_GET_SIZE(cls);
int r = 0;
for (Py_ssize_t i = 0; i < n; ++i) {
PyObject *item = PyTuple_GET_ITEM(cls, i);
r = object_recursive_isinstance(tstate, inst, item);
if (r != 0) {
/* either found it, or got an error */
break;
}
}
_Py_LeaveRecursiveCallTstate(tstate);
return r;
}
PyObject *checker = _PyObject_LookupSpecial(cls, &_Py_ID(__instancecheck__));
if (checker != NULL) {
if (_Py_EnterRecursiveCallTstate(tstate, " in __instancecheck__")) {
Py_DECREF(checker);
return -1;
}
PyObject *res = PyObject_CallOneArg(checker, inst);
_Py_LeaveRecursiveCallTstate(tstate);
Py_DECREF(checker);
if (res == NULL) {
return -1;
}
int ok = PyObject_IsTrue(res);
Py_DECREF(res);
return ok;
}
else if (_PyErr_Occurred(tstate)) {
return -1;
}
/* cls has no __instancecheck__() method */
return object_isinstance(inst, cls);
}
int
PyObject_IsInstance(PyObject *inst, PyObject *cls)
{
PyThreadState *tstate = _PyThreadState_GET();
return object_recursive_isinstance(tstate, inst, cls);
}
static int
recursive_issubclass(PyObject *derived, PyObject *cls)
{
if (PyType_Check(cls) && PyType_Check(derived)) {
/* Fast path (non-recursive) */
return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
}
if (!check_class(derived,
"issubclass() arg 1 must be a class"))
return -1;
if (!_PyUnion_Check(cls) && !check_class(cls,
"issubclass() arg 2 must be a class,"
" a tuple of classes, or a union")) {
return -1;
}
return abstract_issubclass(derived, cls);
}
static int
object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
{
PyObject *checker;
/* We know what type's __subclasscheck__ does. */
if (PyType_CheckExact(cls)) {
/* Quick test for an exact match */
if (derived == cls)
return 1;
return recursive_issubclass(derived, cls);
}
if (_PyUnion_Check(cls)) {
cls = _Py_union_args(cls);
}
if (PyTuple_Check(cls)) {
if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
return -1;
}
Py_ssize_t n = PyTuple_GET_SIZE(cls);
int r = 0;
for (Py_ssize_t i = 0; i < n; ++i) {
PyObject *item = PyTuple_GET_ITEM(cls, i);
r = object_issubclass(tstate, derived, item);
if (r != 0)
/* either found it, or got an error */
break;
}
_Py_LeaveRecursiveCallTstate(tstate);
return r;
}
checker = _PyObject_LookupSpecial(cls, &_Py_ID(__subclasscheck__));
if (checker != NULL) {
int ok = -1;
if (_Py_EnterRecursiveCallTstate(tstate, " in __subclasscheck__")) {
Py_DECREF(checker);
return ok;
}
PyObject *res = PyObject_CallOneArg(checker, derived);
_Py_LeaveRecursiveCallTstate(tstate);
Py_DECREF(checker);
if (res != NULL) {
ok = PyObject_IsTrue(res);
Py_DECREF(res);
}
return ok;
}
else if (_PyErr_Occurred(tstate)) {
return -1;
}
/* Can be reached when infinite recursion happens. */
return recursive_issubclass(derived, cls);
}
int
PyObject_IsSubclass(PyObject *derived, PyObject *cls)
{
PyThreadState *tstate = _PyThreadState_GET();
return object_issubclass(tstate, derived, cls);
}
int
_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
{
return object_isinstance(inst, cls);
}
int
_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
{
return recursive_issubclass(derived, cls);
}
PyObject *
PyObject_GetIter(PyObject *o)
{
PyTypeObject *t = Py_TYPE(o);
getiterfunc f;
f = t->tp_iter;
if (f == NULL) {
if (PySequence_Check(o))
return PySeqIter_New(o);
return type_error("'%.200s' object is not iterable", o);
}
else {
PyObject *res = (*f)(o);
if (res != NULL && !PyIter_Check(res)) {
PyErr_Format(PyExc_TypeError,
"%T.__iter__() must return an iterator, not %T",
o, res);
Py_SETREF(res, NULL);
}
return res;
}
}
PyObject *
PyObject_GetAIter(PyObject *o) {
PyTypeObject *t = Py_TYPE(o);
unaryfunc f;
if (t->tp_as_async == NULL || t->tp_as_async->am_aiter == NULL) {
return type_error("'%.200s' object is not an async iterable", o);
}
f = t->tp_as_async->am_aiter;
PyObject *it = (*f)(o);
if (it != NULL && !PyAIter_Check(it)) {
PyErr_Format(PyExc_TypeError,
"%T.__aiter__() must return an async iterator, not %T",
o, it);
Py_SETREF(it, NULL);
}
return it;
}
int
PyIter_Check(PyObject *obj)
{
PyTypeObject *tp = Py_TYPE(obj);
return (tp->tp_iternext != NULL &&
tp->tp_iternext != &_PyObject_NextNotImplemented);
}
int
PyAIter_Check(PyObject *obj)
{
PyTypeObject *tp = Py_TYPE(obj);
return (tp->tp_as_async != NULL &&
tp->tp_as_async->am_anext != NULL &&
tp->tp_as_async->am_anext != &_PyObject_NextNotImplemented);
}
static int
iternext(PyObject *iter, PyObject **item)
{
iternextfunc tp_iternext = Py_TYPE(iter)->tp_iternext;
if ((*item = tp_iternext(iter))) {
return 1;
}
PyThreadState *tstate = _PyThreadState_GET();
/* When the iterator is exhausted it must return NULL;
* a StopIteration exception may or may not be set. */
if (!_PyErr_Occurred(tstate)) {
return 0;
}
if (_PyErr_ExceptionMatches(tstate, PyExc_StopIteration)) {
_PyErr_Clear(tstate);
return 0;
}
/* Error case: an exception (different than StopIteration) is set. */
return -1;
}
/* Return 1 and set 'item' to the next item of 'iter' on success.
* Return 0 and set 'item' to NULL when there are no remaining values.
* Return -1, set 'item' to NULL and set an exception on error.
*/
int
PyIter_NextItem(PyObject *iter, PyObject **item)
{
assert(iter != NULL);
assert(item != NULL);
if (Py_TYPE(iter)->tp_iternext == NULL) {
*item = NULL;
PyErr_Format(PyExc_TypeError, "expected an iterator, got '%T'", iter);
return -1;
}
return iternext(iter, item);
}
/* Return next item.
*
* If an error occurs, return NULL. PyErr_Occurred() will be true.
* If the iteration terminates normally, return NULL and clear the
* PyExc_StopIteration exception (if it was set). PyErr_Occurred()
* will be false.
* Else return the next object. PyErr_Occurred() will be false.
*/
PyObject *
PyIter_Next(PyObject *iter)
{
PyObject *item;
(void)iternext(iter, &item);
return item;
}
PySendResult
PyIter_Send(PyObject *iter, PyObject *arg, PyObject **result)
{
assert(arg != NULL);
assert(result != NULL);
if (Py_TYPE(iter)->tp_as_async && Py_TYPE(iter)->tp_as_async->am_send) {
PySendResult res = Py_TYPE(iter)->tp_as_async->am_send(iter, arg, result);
assert(_Py_CheckSlotResult(iter, "am_send", res != PYGEN_ERROR));
return res;
}
if (arg == Py_None && PyIter_Check(iter)) {
*result = Py_TYPE(iter)->tp_iternext(iter);
}
else {
*result = PyObject_CallMethodOneArg(iter, &_Py_ID(send), arg);
}
if (*result != NULL) {
return PYGEN_NEXT;
}
if (_PyGen_FetchStopIterationValue(result) == 0) {
return PYGEN_RETURN;
}
return PYGEN_ERROR;
}
NOTES ON DICTIONARIES
================================
Principal Use Cases for Dictionaries
------------------------------------
Passing keyword arguments
Typically, one read and one write for 1 to 3 elements.
Occurs frequently in normal python code.
Class method lookup
Dictionaries vary in size with 8 to 16 elements being common.
Usually written once with many lookups.
When base classes are used, there are many failed lookups
followed by a lookup in a base class.
Instance attribute lookup and Global variables
Dictionaries vary in size. 4 to 10 elements are common.
Both reads and writes are common.
Builtins
Frequent reads. Almost never written.
About 150 interned strings (as of Py3.3).
A few keys are accessed much more frequently than others.
Uniquification
Dictionaries of any size. Bulk of work is in creation.
Repeated writes to a smaller set of keys.
Single read of each key.
Some use cases have two consecutive accesses to the same key.
* Removing duplicates from a sequence.
dict.fromkeys(seqn).keys()
* Counting elements in a sequence.
for e in seqn:
d[e] = d.get(e,0) + 1
* Accumulating references in a dictionary of lists:
for pagenumber, page in enumerate(pages):
for word in page:
d.setdefault(word, []).append(pagenumber)
Note, the second example is a use case characterized by a get and set
to the same key. There are similar use cases with a __contains__
followed by a get, set, or del to the same key. Part of the
justification for d.setdefault is combining the two lookups into one.
Membership Testing
Dictionaries of any size. Created once and then rarely changes.
Single write to each key.
Many calls to __contains__() or has_key().
Similar access patterns occur with replacement dictionaries
such as with the % formatting operator.
Dynamic Mappings
Characterized by deletions interspersed with adds and replacements.
Performance benefits greatly from the re-use of dummy entries.
Data Layout
-----------
Dictionaries are composed of 3 components:
The dictobject struct itself
A dict-keys object (keys & hashes)
A values array
Tunable Dictionary Parameters
-----------------------------
See comments for PyDict_MINSIZE, USABLE_FRACTION and GROWTH_RATE in
dictobject.c
Tune-ups should be measured across a broad range of applications and
use cases. A change to any parameter will help in some situations and
hurt in others. The key is to find settings that help the most common
cases and do the least damage to the less common cases. Results will
vary dramatically depending on the exact number of keys, whether the
keys are all strings, whether reads or writes dominate, the exact
hash values of the keys (some sets of values have fewer collisions than
others). Any one test or benchmark is likely to prove misleading.
While making a dictionary more sparse reduces collisions, it impairs
iteration and key listing. Those methods loop over every potential
entry. Doubling the size of dictionary results in twice as many
non-overlapping memory accesses for keys(), items(), values(),
__iter__(), iterkeys(), iteritems(), itervalues(), and update().
Also, every dictionary iterates at least twice, once for the memset()
when it is created and once by dealloc().
Dictionary operations involving only a single key can be O(1) unless
resizing is possible. By checking for a resize only when the
dictionary can grow (and may *require* resizing), other operations
remain O(1), and the odds of resize thrashing or memory fragmentation
are reduced. In particular, an algorithm that empties a dictionary
by repeatedly invoking .pop will see no resizing, which might
not be necessary at all because the dictionary is eventually
discarded entirely.
The key differences between this implementation and earlier versions are:
1. The table can be split into two parts, the keys and the values.
2. There is an additional key-value combination: (key, NULL).
Unlike (<dummy>, NULL) which represents a deleted value, (key, NULL)
represented a yet to be inserted value. This combination can only occur
when the table is split.
3. No small table embedded in the dict,
as this would make sharing of key-tables impossible.
These changes have the following consequences.
1. General dictionaries are slightly larger.
2. All object dictionaries of a single class can share a single key-table,
saving about 60% memory for such cases.
Results of Cache Locality Experiments
--------------------------------------
Experiments on an earlier design of dictionary, in which all tables were
combined, showed the following:
When an entry is retrieved from memory, several adjacent entries are also
retrieved into a cache line. Since accessing items in cache is *much*
cheaper than a cache miss, an enticing idea is to probe the adjacent
entries as a first step in collision resolution. Unfortunately, the
introduction of any regularity into collision searches results in more
collisions than the current random chaining approach.
Exploiting cache locality at the expense of additional collisions fails
to payoff when the entries are already loaded in cache (the expense
is paid with no compensating benefit). This occurs in small dictionaries
where the whole dictionary fits into a pair of cache lines. It also
occurs frequently in large dictionaries which have a common access pattern
where some keys are accessed much more frequently than others. The
more popular entries *and* their collision chains tend to remain in cache.
To exploit cache locality, change the collision resolution section
in lookdict() and lookdict_string(). Set i^=1 at the top of the
loop and move the i = (i << 2) + i + perturb + 1 to an unrolled
version of the loop.
For split tables, the above will apply to the keys, but the value will
always be in a different cache line from the key.
// namespace object implementation
#include "Python.h"
#include "pycore_modsupport.h" // _PyArg_NoPositional()
#include "pycore_namespace.h" // _PyNamespace_Type
#include <stddef.h> // offsetof()
typedef struct {
PyObject_HEAD
PyObject *ns_dict;
} _PyNamespaceObject;
#define _PyNamespace_CAST(op) _Py_CAST(_PyNamespaceObject*, (op))
static PyMemberDef namespace_members[] = {
{"__dict__", _Py_T_OBJECT, offsetof(_PyNamespaceObject, ns_dict), Py_READONLY},
{NULL}
};
// Methods
static PyObject *
namespace_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *self;
assert(type != NULL && type->tp_alloc != NULL);
self = type->tp_alloc(type, 0);
if (self != NULL) {
_PyNamespaceObject *ns = (_PyNamespaceObject *)self;
ns->ns_dict = PyDict_New();
if (ns->ns_dict == NULL) {
Py_DECREF(ns);
return NULL;
}
}
return self;
}
static int
namespace_init(PyObject *op, PyObject *args, PyObject *kwds)
{
_PyNamespaceObject *ns = _PyNamespace_CAST(op);
PyObject *arg = NULL;
if (!PyArg_UnpackTuple(args, _PyType_Name(Py_TYPE(ns)), 0, 1, &arg)) {
return -1;
}
if (arg != NULL) {
PyObject *dict;
if (PyDict_CheckExact(arg)) {
dict = Py_NewRef(arg);
}
else {
dict = PyObject_CallOneArg((PyObject *)&PyDict_Type, arg);
if (dict == NULL) {
return -1;
}
}
int err = (!PyArg_ValidateKeywordArguments(dict) ||
PyDict_Update(ns->ns_dict, dict) < 0);
Py_DECREF(dict);
if (err) {
return -1;
}
}
if (kwds == NULL) {
return 0;
}
if (!PyArg_ValidateKeywordArguments(kwds)) {
return -1;
}
return PyDict_Update(ns->ns_dict, kwds);
}
static void
namespace_dealloc(PyObject *op)
{
_PyNamespaceObject *ns = _PyNamespace_CAST(op);
PyObject_GC_UnTrack(ns);
Py_CLEAR(ns->ns_dict);
Py_TYPE(ns)->tp_free((PyObject *)ns);
}
static PyObject *
namespace_repr(PyObject *ns)
{
int i, loop_error = 0;
PyObject *pairs = NULL, *d = NULL, *keys = NULL, *keys_iter = NULL;
PyObject *key;
PyObject *separator, *pairsrepr, *repr = NULL;
const char * name;
name = Py_IS_TYPE(ns, &_PyNamespace_Type) ? "namespace"
: Py_TYPE(ns)->tp_name;
i = Py_ReprEnter(ns);
if (i != 0) {
return i > 0 ? PyUnicode_FromFormat("%s(...)", name) : NULL;
}
pairs = PyList_New(0);
if (pairs == NULL)
goto error;
assert(((_PyNamespaceObject *)ns)->ns_dict != NULL);
d = Py_NewRef(((_PyNamespaceObject *)ns)->ns_dict);
keys = PyDict_Keys(d);
if (keys == NULL)
goto error;
keys_iter = PyObject_GetIter(keys);
if (keys_iter == NULL)
goto error;
while ((key = PyIter_Next(keys_iter)) != NULL) {
if (PyUnicode_Check(key) && PyUnicode_GET_LENGTH(key) > 0) {
PyObject *value, *item;
int has_key = PyDict_GetItemRef(d, key, &value);
if (has_key == 1) {
item = PyUnicode_FromFormat("%U=%R", key, value);
Py_DECREF(value);
if (item == NULL) {
loop_error = 1;
}
else {
loop_error = PyList_Append(pairs, item);
Py_DECREF(item);
}
}
else if (has_key < 0) {
loop_error = 1;
}
}
Py_DECREF(key);
if (loop_error)
goto error;
}
if (PyErr_Occurred()) {
goto error;
}
separator = PyUnicode_FromString(", ");
if (separator == NULL)
goto error;
pairsrepr = PyUnicode_Join(separator, pairs);
Py_DECREF(separator);
if (pairsrepr == NULL)
goto error;
repr = PyUnicode_FromFormat("%s(%S)", name, pairsrepr);
Py_DECREF(pairsrepr);
error:
Py_XDECREF(pairs);
Py_XDECREF(d);
Py_XDECREF(keys);
Py_XDECREF(keys_iter);
Py_ReprLeave(ns);
return repr;
}
static int
namespace_traverse(PyObject *op, visitproc visit, void *arg)
{
_PyNamespaceObject *ns = _PyNamespace_CAST(op);
Py_VISIT(ns->ns_dict);
return 0;
}
static int
namespace_clear(PyObject *op)
{
_PyNamespaceObject *ns = _PyNamespace_CAST(op);
Py_CLEAR(ns->ns_dict);
return 0;
}
static PyObject *
namespace_richcompare(PyObject *self, PyObject *other, int op)
{
if (
(op == Py_EQ || op == Py_NE) &&
PyObject_TypeCheck(self, &_PyNamespace_Type) &&
PyObject_TypeCheck(other, &_PyNamespace_Type)
) {
return PyObject_RichCompare(((_PyNamespaceObject *)self)->ns_dict,
((_PyNamespaceObject *)other)->ns_dict, op);
}
Py_RETURN_NOTIMPLEMENTED;
}
PyDoc_STRVAR(namespace_reduce__doc__, "Return state information for pickling");
static PyObject *
namespace_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
{
_PyNamespaceObject *ns = (_PyNamespaceObject*)op;
PyObject *result, *args = PyTuple_New(0);
if (!args)
return NULL;
result = PyTuple_Pack(3, (PyObject *)Py_TYPE(ns), args, ns->ns_dict);
Py_DECREF(args);
return result;
}
static PyObject *
namespace_replace(PyObject *self, PyObject *args, PyObject *kwargs)
{
if (!_PyArg_NoPositional("__replace__", args)) {
return NULL;
}
PyObject *result = PyObject_CallNoArgs((PyObject *)Py_TYPE(self));
if (!result) {
return NULL;
}
if (PyDict_Update(((_PyNamespaceObject*)result)->ns_dict,
((_PyNamespaceObject*)self)->ns_dict) < 0)
{
Py_DECREF(result);
return NULL;
}
if (kwargs) {
if (PyDict_Update(((_PyNamespaceObject*)result)->ns_dict, kwargs) < 0) {
Py_DECREF(result);
return NULL;
}
}
return result;
}
static PyMethodDef namespace_methods[] = {
{"__reduce__", namespace_reduce, METH_NOARGS,
namespace_reduce__doc__},
{"__replace__", _PyCFunction_CAST(namespace_replace), METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("__replace__($self, /, **changes)\n--\n\n"
"Return a copy of the namespace object with new values for the specified attributes.")},
{NULL, NULL} // sentinel
};
PyDoc_STRVAR(namespace_doc,
"SimpleNamespace(mapping_or_iterable=(), /, **kwargs)\n\
--\n\n\
A simple attribute-based namespace.");
PyTypeObject _PyNamespace_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"types.SimpleNamespace", /* tp_name */
sizeof(_PyNamespaceObject), /* tp_basicsize */
0, /* tp_itemsize */
namespace_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
namespace_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE, /* tp_flags */
namespace_doc, /* tp_doc */
namespace_traverse, /* tp_traverse */
namespace_clear, /* tp_clear */
namespace_richcompare, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
namespace_methods, /* tp_methods */
namespace_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(_PyNamespaceObject, ns_dict), /* tp_dictoffset */
namespace_init, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
namespace_new, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
PyObject *
_PyNamespace_New(PyObject *kwds)
{
PyObject *ns = namespace_new(&_PyNamespace_Type, NULL, NULL);
if (ns == NULL)
return NULL;
if (kwds == NULL)
return ns;
if (PyDict_Update(((_PyNamespaceObject *)ns)->ns_dict, kwds) != 0) {
Py_DECREF(ns);
return NULL;
}
return (PyObject *)ns;
}
"""
|