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
|
from __future__ import with_statement
import py.test
import sys
from collections import OrderedDict
from rpython.conftest import option
from rpython.annotator import model as annmodel
from rpython.annotator.model import AnnotatorError, UnionError
from rpython.annotator.annrpython import RPythonAnnotator as _RPythonAnnotator
from rpython.annotator.classdesc import NoSuchAttrError
from rpython.translator.translator import graphof as tgraphof
from rpython.annotator.policy import AnnotatorPolicy
from rpython.annotator.signature import Sig, SignatureError
from rpython.annotator.listdef import ListDef, ListChangeUnallowed
from rpython.annotator.dictdef import DictDef
from rpython.flowspace.model import *
from rpython.rlib.rarithmetic import r_uint, base_int, r_longlong, r_ulonglong
from rpython.rlib.rarithmetic import r_singlefloat
from rpython.rlib import objectmodel
from rpython.flowspace.flowcontext import FlowingError
from rpython.flowspace.operation import op
from rpython.translator.test import snippet
def graphof(a, func):
return tgraphof(a.translator, func)
def listitem(s_list):
assert isinstance(s_list, annmodel.SomeList)
return s_list.listdef.listitem.s_value
def somelist(s_type):
return annmodel.SomeList(ListDef(None, s_type))
def dictkey(s_dict):
assert isinstance(s_dict, annmodel.SomeDict)
return s_dict.dictdef.dictkey.s_value
def dictvalue(s_dict):
assert isinstance(s_dict, annmodel.SomeDict)
return s_dict.dictdef.dictvalue.s_value
def somedict(annotator, s_key, s_value):
return annmodel.SomeDict(DictDef(annotator.bookkeeper, s_key, s_value))
class TestAnnotateTestCase:
def teardown_method(self, meth):
assert annmodel.s_Bool == annmodel.SomeBool()
class RPythonAnnotator(_RPythonAnnotator):
def build_types(self, *args):
s = _RPythonAnnotator.build_types(self, *args)
self.validate()
if option.view:
self.translator.view()
return s
def test_simple_func(self):
"""
one test source:
def f(x):
return x+1
"""
x = Variable("x")
oper = op.add(x, Constant(1))
block = Block([x])
fun = FunctionGraph("f", block)
block.operations.append(oper)
block.closeblock(Link([oper.result], fun.returnblock))
a = self.RPythonAnnotator()
a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
a.complete()
assert a.gettype(fun.getreturnvar()) == int
def test_while(self):
"""
one test source:
def f(i):
while i > 0:
i = i - 1
return i
"""
i1 = Variable("i1")
i2 = Variable("i2")
conditionop = op.gt(i1, Constant(0))
decop = op.add(i2, Constant(-1))
headerblock = Block([i1])
whileblock = Block([i2])
fun = FunctionGraph("f", headerblock)
headerblock.operations.append(conditionop)
headerblock.exitswitch = conditionop.result
headerblock.closeblock(Link([i1], fun.returnblock, False),
Link([i1], whileblock, True))
whileblock.operations.append(decop)
whileblock.closeblock(Link([decop.result], headerblock))
a = self.RPythonAnnotator()
a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
a.complete()
assert a.gettype(fun.getreturnvar()) == int
def test_while_sum(self):
"""
one test source:
def f(i):
sum = 0
while i > 0:
sum = sum + i
i = i - 1
return sum
"""
i1 = Variable("i1")
i2 = Variable("i2")
i3 = Variable("i3")
sum2 = Variable("sum2")
sum3 = Variable("sum3")
conditionop = op.gt(i2, Constant(0))
decop = op.add(i3, Constant(-1))
addop = op.add(i3, sum3)
startblock = Block([i1])
headerblock = Block([i2, sum2])
whileblock = Block([i3, sum3])
fun = FunctionGraph("f", startblock)
startblock.closeblock(Link([i1, Constant(0)], headerblock))
headerblock.operations.append(conditionop)
headerblock.exitswitch = conditionop.result
headerblock.closeblock(Link([sum2], fun.returnblock, False),
Link([i2, sum2], whileblock, True))
whileblock.operations.append(addop)
whileblock.operations.append(decop)
whileblock.closeblock(Link([decop.result, addop.result], headerblock))
a = self.RPythonAnnotator()
a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
a.complete()
assert a.gettype(fun.getreturnvar()) == int
def test_f_calls_g(self):
a = self.RPythonAnnotator()
s = a.build_types(f_calls_g, [int])
# result should be an integer
assert s.knowntype == int
def test_lists(self):
a = self.RPythonAnnotator()
end_cell = a.build_types(snippet.poor_man_rev_range, [int])
# result should be a list of integers
assert listitem(end_cell).knowntype == int
def test_factorial(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.factorial, [int])
# result should be an integer
assert s.knowntype == int
def test_factorial2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.factorial2, [int])
# result should be an integer
assert s.knowntype == int
def test_build_instance(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.build_instance, [])
# result should be a snippet.C instance
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.C)
def test_set_attr(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.set_attr, [])
# result should be an integer
assert s.knowntype == int
def test_merge_setattr(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.merge_setattr, [int])
# result should be an integer
assert s.knowntype == int
def test_inheritance1(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.inheritance1, [])
# result should be exactly:
assert s == annmodel.SomeTuple([
a.bookkeeper.immutablevalue(()),
annmodel.SomeInteger()
])
def test_poor_man_range(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.poor_man_range, [int])
# result should be a list of integers
assert listitem(s).knowntype == int
def test_staticmethod(self):
class X(object):
@staticmethod
def stat(value):
return value + 4
def f(v):
return X().stat(v)
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeInteger)
def test_classmethod(self):
class X(object):
@classmethod
def meth(cls):
return None
def f():
return X().meth()
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [])
def test_methodcall1(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet._methodcall1, [int])
# result should be a tuple of (C, positive_int)
assert s.knowntype == tuple
assert len(s.items) == 2
s0 = s.items[0]
assert isinstance(s0, annmodel.SomeInstance)
assert s0.classdef == a.bookkeeper.getuniqueclassdef(snippet.C)
assert s.items[1].knowntype == int
assert s.items[1].nonneg == True
def test_classes_methodcall1(self):
a = self.RPythonAnnotator()
a.build_types(snippet._methodcall1, [int])
# the user classes should have the following attributes:
getcdef = a.bookkeeper.getuniqueclassdef
assert getcdef(snippet.F).attrs.keys() == ['m']
assert getcdef(snippet.G).attrs.keys() == ['m2']
assert getcdef(snippet.H).attrs.keys() == ['attr']
assert getcdef(snippet.H).about_attribute('attr') == (
a.bookkeeper.immutablevalue(1))
def test_generaldict(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.generaldict, [str, int, str, int])
# result should be an integer
assert s.knowntype == int
def test_somebug1(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet._somebug1, [int])
# result should be a built-in method
assert isinstance(s, annmodel.SomeBuiltin)
def test_with_init(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.with_init, [int])
# result should be an integer
assert s.knowntype == int
def test_with_more_init(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.with_more_init, [int, bool])
# the user classes should have the following attributes:
getcdef = a.bookkeeper.getuniqueclassdef
# XXX on which class should the attribute 'a' appear? We only
# ever flow WithInit.__init__ with a self which is an instance
# of WithMoreInit, so currently it appears on WithMoreInit.
assert getcdef(snippet.WithMoreInit).about_attribute('a') == (
annmodel.SomeInteger())
assert getcdef(snippet.WithMoreInit).about_attribute('b') == (
annmodel.SomeBool())
def test_global_instance(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.global_instance, [])
# currently this returns the constant 42.
# XXX not sure this is the best behavior...
assert s == a.bookkeeper.immutablevalue(42)
def test_call_five(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.call_five, [])
# returns should be a list of constants (= 5)
assert listitem(s) == a.bookkeeper.immutablevalue(5)
def test_call_five_six(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.call_five_six, [])
# returns should be a list of positive integers
assert listitem(s) == annmodel.SomeInteger(nonneg=True)
def test_constant_result(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.constant_result, [])
#a.translator.simplify()
# must return "yadda"
assert s == a.bookkeeper.immutablevalue("yadda")
graphs = a.translator.graphs
assert len(graphs) == 2
assert graphs[0].func is snippet.constant_result
assert graphs[1].func is snippet.forty_two
a.simplify()
#a.translator.view()
def test_flow_type_info(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_type_info, [int])
a.simplify()
assert s.knowntype == int
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_type_info, [str])
a.simplify()
assert s.knowntype == int
def test_flow_type_info_2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_type_info,
[annmodel.SomeInteger(nonneg=True)])
# this checks that isinstance(i, int) didn't lose the
# actually more precise information that i is non-negative
assert s == annmodel.SomeInteger(nonneg=True)
def test_flow_usertype_info(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_usertype_info, [snippet.WithInit])
#a.translator.view()
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.WithInit)
def test_flow_usertype_info2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_usertype_info, [snippet.WithMoreInit])
#a.translator.view()
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.WithMoreInit)
def test_mergefunctions(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.mergefunctions, [int])
# the test is mostly that the above line hasn't blown up
# but let's at least check *something*
assert isinstance(s, annmodel.SomePBC)
def test_func_calls_func_which_just_raises(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.funccallsex, [])
# the test is mostly that the above line hasn't blown up
# but let's at least check *something*
#self.assert_(isinstance(s, SomeCallable))
def test_tuple_unpack_from_const_tuple_with_different_types(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.func_arg_unpack, [])
assert isinstance(s, annmodel.SomeInteger)
assert s.const == 3
def test_star_unpack_list(self):
def g():
pass
def f(l):
return g(*l)
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [[int]])
def test_star_unpack_and_keywords(self):
def g(a, b, c=0, d=0):
return a + b + c + d
def f(a, b):
return g(a, *(b,), d=5)
a = self.RPythonAnnotator()
s_result = a.build_types(f, [int, int])
assert isinstance(s_result, annmodel.SomeInteger)
def test_pbc_attr_preserved_on_instance(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.preserve_pbc_attr_on_instance, [bool])
#a.simplify()
#a.translator.view()
assert s == annmodel.SomeInteger(nonneg=True)
#self.assertEquals(s.__class__, annmodel.SomeInteger)
def test_pbc_attr_preserved_on_instance_with_slots(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.preserve_pbc_attr_on_instance_with_slots,
[bool])
assert s == annmodel.SomeInteger(nonneg=True)
def test_is_and_knowntype_data(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.is_and_knowntype, [str])
#a.simplify()
#a.translator.view()
assert s == a.bookkeeper.immutablevalue(None)
def test_isinstance_and_knowntype_data(self):
a = self.RPythonAnnotator()
x = a.bookkeeper.immutablevalue(snippet.apbc)
s = a.build_types(snippet.isinstance_and_knowntype, [x])
#a.simplify()
#a.translator.view()
assert s == x
def test_somepbc_simplify(self):
a = self.RPythonAnnotator()
# this example used to trigger an AssertionError
a.build_types(snippet.somepbc_simplify, [])
def test_builtin_methods(self):
a = self.RPythonAnnotator()
iv = a.bookkeeper.immutablevalue
# this checks that some built-in methods are really supported by
# the annotator (it doesn't check that they operate property, though)
for example, methname, s_example in [
('', 'join', annmodel.SomeString()),
([], 'append', somelist(annmodel.s_Int)),
([], 'extend', somelist(annmodel.s_Int)),
([], 'reverse', somelist(annmodel.s_Int)),
([], 'insert', somelist(annmodel.s_Int)),
([], 'pop', somelist(annmodel.s_Int)),
]:
constmeth = getattr(example, methname)
s_constmeth = iv(constmeth)
assert isinstance(s_constmeth, annmodel.SomeBuiltin)
s_meth = s_example.getattr(iv(methname))
assert isinstance(s_constmeth, annmodel.SomeBuiltin)
def test_str_join(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return ["foo", "bar"]
def f(n):
g(0)
return ''.join(g(n))
s = a.build_types(f, [int])
assert s.knowntype == str
assert s.no_nul
def test_unicode_join(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return [u"foo", u"bar"]
def f(n):
g(0)
return u''.join(g(n))
s = a.build_types(f, [int])
assert s.knowntype == unicode
assert s.no_nul
def test_str_split(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return "test string"
def f(n):
if n:
return g(n).split(' ')
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeList)
s_item = s.listdef.listitem.s_value
assert s_item.no_nul
def test_unicode_split(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return u"test string"
def f(n):
if n:
return g(n).split(u' ')
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeList)
s_item = s.listdef.listitem.s_value
assert s_item.no_nul
def test_str_split_nul(self):
def f(n):
return n.split('\0')[0]
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(f, [annmodel.SomeString(no_nul=False, can_be_None=False)])
assert isinstance(s, annmodel.SomeString)
assert not s.can_be_None
assert s.no_nul
def g(n):
return n.split('\0', 1)[0]
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(g, [annmodel.SomeString(no_nul=False, can_be_None=False)])
assert isinstance(s, annmodel.SomeString)
assert not s.can_be_None
assert not s.no_nul
def test_unicode_split_nul(self):
def f(n):
return n.split(u'\0')[0]
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(f, [annmodel.SomeUnicodeString(
no_nul=False, can_be_None=False)])
assert isinstance(s, annmodel.SomeUnicodeString)
assert not s.can_be_None
assert s.no_nul
def g(n):
return n.split(u'\0', 1)[0]
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(g, [annmodel.SomeUnicodeString(
no_nul=False, can_be_None=False)])
assert isinstance(s, annmodel.SomeUnicodeString)
assert not s.can_be_None
assert not s.no_nul
def test_str_splitlines(self):
a = self.RPythonAnnotator()
def f(a_str):
return a_str.splitlines()
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeList)
assert s.listdef.listitem.resized
def test_str_strip(self):
a = self.RPythonAnnotator()
def f(n, a_str):
if n == 0:
return a_str.strip(' ')
elif n == 1:
return a_str.rstrip(' ')
else:
return a_str.lstrip(' ')
s = a.build_types(f, [int, annmodel.SomeString(no_nul=True)])
assert s.no_nul
def test_unicode_strip(self):
a = self.RPythonAnnotator()
def f(n, a_str):
if n == 0:
return a_str.strip(u' ')
elif n == 1:
return a_str.rstrip(u' ')
else:
return a_str.lstrip(u' ')
s = a.build_types(f, [int, annmodel.SomeUnicodeString(no_nul=True)])
assert s.no_nul
def test_str_mul(self):
a = self.RPythonAnnotator()
def f(a_str):
return a_str * 3
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeString)
def test_str_isalpha(self):
def f(s):
return s.isalpha()
a = self.RPythonAnnotator()
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeBool)
def test_simple_slicing(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.simple_slice, [somelist(annmodel.s_Int)])
assert isinstance(s, annmodel.SomeList)
def test_simple_iter_list(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.simple_iter, [somelist(annmodel.s_Int)])
assert isinstance(s, annmodel.SomeIterator)
def test_simple_iter_next(self):
def f(x):
i = iter(range(x))
return i.next()
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeInteger)
def test_simple_iter_dict(self):
a = self.RPythonAnnotator()
t = somedict(a, annmodel.SomeInteger(), annmodel.SomeInteger())
s = a.build_types(snippet.simple_iter, [t])
assert isinstance(s, annmodel.SomeIterator)
def test_simple_zip(self):
a = self.RPythonAnnotator()
x = somelist(annmodel.SomeInteger())
y = somelist(annmodel.SomeString())
s = a.build_types(snippet.simple_zip, [x,y])
assert s.knowntype == list
assert listitem(s).knowntype == tuple
assert listitem(s).items[0].knowntype == int
assert listitem(s).items[1].knowntype == str
def test_dict_copy(self):
a = self.RPythonAnnotator()
t = somedict(a, annmodel.SomeInteger(), annmodel.SomeInteger())
s = a.build_types(snippet.dict_copy, [t])
assert isinstance(dictkey(s), annmodel.SomeInteger)
assert isinstance(dictvalue(s), annmodel.SomeInteger)
def test_dict_update(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_update, [int])
assert isinstance(dictkey(s), annmodel.SomeInteger)
assert isinstance(dictvalue(s), annmodel.SomeInteger)
def test_dict_update_2(self):
a = self.RPythonAnnotator()
def g(n):
if n:
return {3: 4}
def f(n):
g(0)
d = {}
d.update(g(n))
return d
s = a.build_types(f, [int])
assert dictkey(s).knowntype == int
def test_dict_keys(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_keys, [])
assert isinstance(listitem(s), annmodel.SomeString)
def test_dict_keys2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_keys2, [])
assert type(listitem(s)) is annmodel.SomeString
def test_dict_values(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_values, [])
assert isinstance(listitem(s), annmodel.SomeString)
def test_dict_values2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_values2, [])
assert type(listitem(s)) is annmodel.SomeString
def test_dict_items(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.dict_items, [])
assert isinstance(listitem(s), annmodel.SomeTuple)
s_key, s_value = listitem(s).items
assert isinstance(s_key, annmodel.SomeString)
assert isinstance(s_value, annmodel.SomeInteger)
def test_dict_setdefault(self):
a = self.RPythonAnnotator()
def f():
d = {}
d.setdefault('a', 2)
d.setdefault('a', -3)
return d
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeDict)
assert isinstance(dictkey(s), annmodel.SomeString)
assert isinstance(dictvalue(s), annmodel.SomeInteger)
assert not dictvalue(s).nonneg
def test_exception_deduction(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction, [])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_exception_deduction_we_are_dumb(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction_we_are_dumb, [])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_nested_exception_deduction(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.nested_exception_deduction, [])
assert isinstance(s, annmodel.SomeTuple)
assert isinstance(s.items[0], annmodel.SomeInstance)
assert isinstance(s.items[1], annmodel.SomeInstance)
assert s.items[0].classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
assert s.items[1].classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc2)
def test_exc_deduction_our_exc_plus_others(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exc_deduction_our_exc_plus_others, [])
assert isinstance(s, annmodel.SomeInteger)
def test_exc_deduction_our_excs_plus_others(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exc_deduction_our_excs_plus_others, [])
assert isinstance(s, annmodel.SomeInteger)
def test_complex_exception_deduction(self):
class InternalError(Exception):
def __init__(self, msg):
self.msg = msg
class AppError(Exception):
def __init__(self, msg):
self.msg = msg
def apperror(msg):
return AppError(msg)
def f(string):
if not string:
raise InternalError('Empty string')
return string, None
def cleanup():
pass
def g(string):
try:
try:
string, _ = f(string)
except ZeroDivisionError:
raise apperror('ZeroDivisionError')
try:
result, _ = f(string)
finally:
cleanup()
except InternalError as e:
raise apperror(e.msg)
return result
a = self.RPythonAnnotator()
s_result = a.build_types(g, [str])
assert isinstance(s_result, annmodel.SomeString)
def test_method_exception_specialization(self):
def f(l):
try:
return l.pop()
except Exception:
raise
a = self.RPythonAnnotator()
s = a.build_types(f, [[int]])
graph = graphof(a, f)
etype, evalue = graph.exceptblock.inputargs
assert evalue.annotation.classdefs == {
a.bookkeeper.getuniqueclassdef(IndexError)}
assert etype.annotation.const == IndexError
def test_operation_always_raising(self):
def operation_always_raising(n):
lst = []
try:
return lst[n]
except IndexError:
return 24
a = self.RPythonAnnotator()
s = a.build_types(operation_always_raising, [int])
assert s == a.bookkeeper.immutablevalue(24)
def test_propagation_of_fresh_instances_through_attrs(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.propagation_of_fresh_instances_through_attrs, [int])
assert s is not None
def test_propagation_of_fresh_instances_through_attrs_rec_0(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.make_r, [int])
Rdef = a.bookkeeper.getuniqueclassdef(snippet.R)
assert s.classdef == Rdef
assert Rdef.attrs['r'].s_value.classdef == Rdef
assert Rdef.attrs['n'].s_value.knowntype == int
assert Rdef.attrs['m'].s_value.knowntype == int
def test_propagation_of_fresh_instances_through_attrs_rec_eo(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.make_eo, [int])
assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.B)
Even_def = a.bookkeeper.getuniqueclassdef(snippet.Even)
Odd_def = a.bookkeeper.getuniqueclassdef(snippet.Odd)
assert listitem(Even_def.attrs['x'].s_value).classdef == Odd_def
assert listitem(Even_def.attrs['y'].s_value).classdef == Even_def
assert listitem(Odd_def.attrs['x'].s_value).classdef == Even_def
assert listitem(Odd_def.attrs['y'].s_value).classdef == Odd_def
def test_flow_rev_numbers(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.flow_rev_numbers, [int])
assert s.knowntype == int
assert not s.is_constant() # !
def test_methodcall_is_precise(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.methodcall_is_precise, [bool])
getcdef = a.bookkeeper.getuniqueclassdef
assert 'x' not in getcdef(snippet.CBase).attrs
assert (getcdef(snippet.CSub1).attrs['x'].s_value ==
a.bookkeeper.immutablevalue(42))
assert (getcdef(snippet.CSub2).attrs['x'].s_value ==
a.bookkeeper.immutablevalue('world'))
assert s == a.bookkeeper.immutablevalue(42)
def test_call_star_args(self):
a = self.RPythonAnnotator(policy=AnnotatorPolicy())
s = a.build_types(snippet.call_star_args, [int])
assert s.knowntype == int
def test_call_star_args_multiple(self):
a = self.RPythonAnnotator(policy=AnnotatorPolicy())
s = a.build_types(snippet.call_star_args_multiple, [int])
assert s.knowntype == int
def test_exception_deduction_with_raise1(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction_with_raise1, [bool])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_exception_deduction_with_raise2(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction_with_raise2, [bool])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_exception_deduction_with_raise3(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.exception_deduction_with_raise3, [bool])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
def test_type_is(self):
class B(object):
pass
class C(B):
pass
def f(x):
assert type(x) is C
return x
a = self.RPythonAnnotator()
s = a.build_types(f, [B])
assert s.classdef is a.bookkeeper.getuniqueclassdef(C)
@py.test.mark.xfail
def test_union_type_some_pbc(self):
class A(object):
name = "A"
def f(self):
return type(self)
class B(A):
name = "B"
def f(tp):
return tp
def main(n):
if n:
if n == 1:
inst = A()
else:
inst = B()
arg = inst.f()
else:
arg = B
return f(arg).name
a = self.RPythonAnnotator()
s = a.build_types(main, [int])
assert isinstance(s, annmodel.SomeString)
def test_ann_assert(self):
def assert_(x):
assert x,"XXX"
a = self.RPythonAnnotator()
s = a.build_types(assert_, [int])
assert s.const is None
def test_string_and_none(self):
def f(n):
if n:
return 'y'
else:
return 'n'
def g(n):
if n:
return 'y'
else:
return None
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert s.knowntype == str
assert not s.can_be_None
s = a.build_types(g, [bool])
assert s.knowntype == str
assert s.can_be_None
def test_implicit_exc(self):
def f(l):
try:
l[0]
except (KeyError, IndexError) as e:
return e
return None
a = self.RPythonAnnotator()
s = a.build_types(f, [somelist(annmodel.s_Int)])
assert s.classdef is a.bookkeeper.getuniqueclassdef(IndexError) # KeyError ignored because l is a list
def test_freeze_protocol(self):
class Stuff:
def __init__(self):
self.called = False
def _freeze_(self):
self.called = True
return True
myobj = Stuff()
a = self.RPythonAnnotator()
s = a.build_types(lambda: myobj, [])
assert myobj.called
assert isinstance(s, annmodel.SomePBC)
assert s.const == myobj
def test_cleanup_protocol(self):
class Stuff:
def __init__(self):
self.called = False
def _cleanup_(self):
self.called = True
myobj = Stuff()
a = self.RPythonAnnotator()
s = a.build_types(lambda: myobj, [])
assert myobj.called
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef is a.bookkeeper.getuniqueclassdef(Stuff)
def test_circular_mutable_getattr(self):
class C:
pass
c = C()
c.x = c
def f():
return c.x
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef == a.bookkeeper.getuniqueclassdef(C)
def test_circular_list_type(self):
def f(n):
lst = []
for i in range(n):
lst = [lst]
return lst
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert listitem(s) == s
def test_harmonic(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.harmonic, [int])
assert s.knowntype == float
# check that the list produced by range() is not mutated or resized
graph = graphof(a, snippet.harmonic)
all_vars = set().union(*[block.getvariables() for block in graph.iterblocks()])
print all_vars
for var in all_vars:
s_value = var.annotation
if isinstance(s_value, annmodel.SomeList):
assert not s_value.listdef.listitem.resized
assert not s_value.listdef.listitem.mutated
assert s_value.listdef.listitem.range_step
def test_bool(self):
def f(a,b):
return bool(a) or bool(b)
a = self.RPythonAnnotator()
s = a.build_types(f, [int, somelist(annmodel.s_Int)])
assert s.knowntype == bool
def test_float(self):
def f(n):
return float(n)
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.knowntype == float
def test_r_uint(self):
def f(n):
return n + constant_unsigned_five
a = self.RPythonAnnotator()
s = a.build_types(f, [r_uint])
assert s == annmodel.SomeInteger(nonneg = True, unsigned = True)
def test_large_unsigned(self):
large_constant = sys.maxint * 2 + 1 # 0xFFFFFFFF on 32-bit platforms
def f():
return large_constant
a = self.RPythonAnnotator()
with py.test.raises(ValueError):
a.build_types(f, [])
# if you want to get a r_uint, you have to be explicit about it
def test_add_different_ints(self):
def f(a, b):
return a + b
a = self.RPythonAnnotator()
with py.test.raises(UnionError):
a.build_types(f, [r_uint, int])
def test_merge_different_ints(self):
def f(a, b):
if a:
c = a
else:
c = b
return c
a = self.RPythonAnnotator()
with py.test.raises(UnionError):
a.build_types(f, [r_uint, int])
def test_merge_ruint_zero(self):
def f(a):
if a:
c = a
else:
c = 0
return c
a = self.RPythonAnnotator()
s = a.build_types(f, [r_uint])
assert s == annmodel.SomeInteger(nonneg = True, unsigned = True)
def test_merge_ruint_nonneg_signed(self):
def f(a, b):
if a:
c = a
else:
assert b >= 0
c = b
return c
a = self.RPythonAnnotator()
s = a.build_types(f, [r_uint, int])
assert s == annmodel.SomeInteger(nonneg = True, unsigned = True)
def test_prebuilt_long_that_is_not_too_long(self):
small_constant = 12L
def f():
return small_constant
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == 12
assert s.nonneg
assert not s.unsigned
#
small_constant = -23L
def f():
return small_constant
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == -23
assert not s.nonneg
assert not s.unsigned
def test_pbc_getattr(self):
class C:
def __init__(self, v1, v2):
self.v2 = v2
self.v1 = v1
def _freeze_(self):
return True
c1 = C(1,'a')
c2 = C(2,'b')
c3 = C(3,'c')
def f1(l, c):
l.append(c.v1)
def f2(l, c):
l.append(c.v2)
def g():
l1 = []
l2 = []
f1(l1, c1)
f1(l1, c2)
f2(l2, c2)
f2(l2, c3)
return l1,l2
a = self.RPythonAnnotator()
s = a.build_types(g,[])
l1, l2 = s.items
assert listitem(l1).knowntype == int
assert listitem(l2).knowntype == str
acc1 = a.bookkeeper.getdesc(c1).getattrfamily()
acc2 = a.bookkeeper.getdesc(c2).getattrfamily()
acc3 = a.bookkeeper.getdesc(c3).getattrfamily()
assert acc1 is acc2 is acc3
assert len(acc1.descs) == 3
assert dict.fromkeys(acc1.attrs) == {'v1': None, 'v2': None}
def test_single_pbc_getattr(self):
class C:
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def _freeze_(self):
return True
c1 = C(11, "hello")
c2 = C(22, 623)
def f1(l, c):
l.append(c.v1)
def f2(c):
return c.v2
def f3(c):
return c.v2
def g():
l = []
f1(l, c1)
f1(l, c2)
return l, f2(c1), f3(c2)
a = self.RPythonAnnotator()
s = a.build_types(g,[])
s_l, s_c1v2, s_c2v2 = s.items
assert listitem(s_l).knowntype == int
assert s_c1v2.const == "hello"
assert s_c2v2.const == 623
acc1 = a.bookkeeper.getdesc(c1).getattrfamily()
acc2 = a.bookkeeper.getdesc(c2).getattrfamily()
assert acc1 is acc2
assert acc1.attrs.keys() == ['v1']
def test_isinstance_unsigned_1(self):
def f(x):
return isinstance(x, r_uint)
def g():
v = r_uint(1)
return f(v)
a = self.RPythonAnnotator()
s = a.build_types(g, [])
assert s.const == True
def test_isinstance_unsigned_2(self):
class Foo:
pass
def f(x):
return isinstance(x, r_uint)
def g():
v = Foo()
return f(v)
a = self.RPythonAnnotator()
s = a.build_types(g, [])
assert s.const == False
def test_isinstance_base_int(self):
def f(x):
return isinstance(x, base_int)
def g(n):
v = r_uint(n)
return f(v)
a = self.RPythonAnnotator()
s = a.build_types(g, [int])
assert s.const == True
def test_isinstance_basic(self):
def f():
return isinstance(IndexError(), type)
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == False
def test_alloc_like(self):
class Base(object):
pass
class C1(Base):
pass
class C2(Base):
pass
def inst(cls):
return cls()
def alloc(cls):
i = inst(cls)
assert isinstance(i, cls)
return i
alloc._annspecialcase_ = "specialize:arg(0)"
def f():
c1 = alloc(C1)
c2 = alloc(C2)
return c1,c2
a = self.RPythonAnnotator()
s = a.build_types(f, [])
C1df = a.bookkeeper.getuniqueclassdef(C1)
C2df = a.bookkeeper.getuniqueclassdef(C2)
assert s.items[0].classdef == C1df
assert s.items[1].classdef == C2df
allocdesc = a.bookkeeper.getdesc(alloc)
s_C1 = a.bookkeeper.immutablevalue(C1)
s_C2 = a.bookkeeper.immutablevalue(C2)
graph1 = allocdesc.specialize([s_C1], None)
graph2 = allocdesc.specialize([s_C2], None)
assert a.binding(graph1.getreturnvar()).classdef == C1df
assert a.binding(graph2.getreturnvar()).classdef == C2df
assert graph1 in a.translator.graphs
assert graph2 in a.translator.graphs
def test_specialcase_args(self):
class C1(object):
pass
class C2(object):
pass
def alloc(cls, cls2):
i = cls()
assert isinstance(i, cls)
j = cls2()
assert isinstance(j, cls2)
return i
def f():
alloc(C1, C1)
alloc(C1, C2)
alloc(C2, C1)
alloc(C2, C2)
alloc._annspecialcase_ = "specialize:arg(0,1)"
a = self.RPythonAnnotator()
C1df = a.bookkeeper.getuniqueclassdef(C1)
C2df = a.bookkeeper.getuniqueclassdef(C2)
s = a.build_types(f, [])
allocdesc = a.bookkeeper.getdesc(alloc)
s_C1 = a.bookkeeper.immutablevalue(C1)
s_C2 = a.bookkeeper.immutablevalue(C2)
graph1 = allocdesc.specialize([s_C1, s_C2], None)
graph2 = allocdesc.specialize([s_C2, s_C2], None)
assert a.binding(graph1.getreturnvar()).classdef == C1df
assert a.binding(graph2.getreturnvar()).classdef == C2df
assert graph1 in a.translator.graphs
assert graph2 in a.translator.graphs
def test_specialize_arg_bound_method(self):
class GC(object):
def trace(self, callback, *args):
return callback(*args)
trace._annspecialcase_ = "specialize:arg(1)"
def callback1(self, arg1):
self.x = arg1
return "hello"
def callback2(self, arg2, arg3):
self.y = arg2
self.z = arg3
return 6
def f():
gc = GC()
s1 = gc.trace(gc.callback1, "foo")
n2 = gc.trace(gc.callback2, 7, 2)
return (s1, n2, gc.x, gc.y, gc.z)
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.items[0].const == "hello"
assert s.items[1].const == 6
assert s.items[2].const == "foo"
assert s.items[3].const == 7
assert s.items[4].const == 2
def test_specialize_and_star_args(self):
class I(object):
def execute(self, op, *args):
if op == 0:
return args[0]+args[1]
if op == 1:
return args[0] * args[1] + args[2]
execute._annspecialcase_ = "specialize:arg(1)"
def f(x, y):
i = I()
a = i.execute(0, x, y)
b = i.execute(1, y, y, 5)
return a+b
a = self.RPythonAnnotator()
s = a.build_types(f, [int, int])
executedesc = a.bookkeeper.getdesc(I.execute.im_func)
assert len(executedesc._cache) == 2
assert len(executedesc._cache[(0, 'star', 2)].startblock.inputargs) == 4
assert len(executedesc._cache[(1, 'star', 3)].startblock.inputargs) == 5
def test_specialize_arg_or_var(self):
def f(a):
return 1
f._annspecialcase_ = 'specialize:arg_or_var(0)'
def fn(a):
return f(3) + f(a)
a = self.RPythonAnnotator()
a.build_types(fn, [int])
executedesc = a.bookkeeper.getdesc(f)
assert sorted(executedesc._cache.keys()) == [None, (3,)]
# we got two different special
def test_specialize_call_location(self):
def g(a):
return a
g._annspecialcase_ = "specialize:call_location"
def f(x):
return g(x)
f._annspecialcase_ = "specialize:argtype(0)"
def h(y):
w = f(y)
return int(f(str(y))) + w
a = self.RPythonAnnotator()
assert a.build_types(h, [int]) == annmodel.SomeInteger()
def test_assert_list_doesnt_lose_info(self):
class T(object):
pass
def g(l):
assert isinstance(l, list)
return l
def f():
l = [T()]
return g(l)
a = self.RPythonAnnotator()
s = a.build_types(f, [])
s_item = listitem(s)
assert isinstance(s_item, annmodel.SomeInstance)
assert s_item.classdef is a.bookkeeper.getuniqueclassdef(T)
def test_int_str_mul(self):
def f(x,a,b):
return a*x+x*b
a = self.RPythonAnnotator()
s = a.build_types(f, [str,int,int])
assert s.knowntype == str
def test_list_tuple(self):
def g0(x):
return list(x)
def g1(x):
return list(x)
def f(n):
l1 = g0(())
l2 = g1((1,))
if n:
t = (1,)
else:
t = (2,)
l3 = g1(t)
return l1, l2, l3
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert listitem(s.items[0]) == annmodel.SomeImpossibleValue()
assert listitem(s.items[1]).knowntype == int
assert listitem(s.items[2]).knowntype == int
def test_empty_list(self):
def f():
l = []
return bool(l)
def g():
l = []
x = bool(l)
l.append(1)
return x, bool(l)
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == False
a = self.RPythonAnnotator()
s = a.build_types(g, [])
assert s.items[0].knowntype == bool and not s.items[0].is_constant()
assert s.items[1].knowntype == bool and not s.items[1].is_constant()
def test_empty_dict(self):
def f():
d = {}
return bool(d)
def g():
d = {}
x = bool(d)
d['a'] = 1
return x, bool(d)
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == False
a = self.RPythonAnnotator()
s = a.build_types(g, [])
assert s.items[0].knowntype == bool and not s.items[0].is_constant()
assert s.items[1].knowntype == bool and not s.items[1].is_constant()
def test_call_two_funcs_but_one_can_only_raise(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.call_two_funcs_but_one_can_only_raise,
[int])
assert s == a.bookkeeper.immutablevalue(None)
def test_reraiseKeyError(self):
def f(dic):
try:
dic[5]
except KeyError:
raise
a = self.RPythonAnnotator()
a.build_types(f, [somedict(a, annmodel.s_Int, annmodel.s_Int)])
fg = graphof(a, f)
et, ev = fg.exceptblock.inputargs
t = annmodel.SomeTypeOf([ev])
t.const = KeyError
assert et.annotation == t
s_ev = ev.annotation
assert s_ev == a.bookkeeper.new_exception([KeyError])
def test_reraiseAnything(self):
def f(dic):
try:
dic[5]
except:
raise
a = self.RPythonAnnotator()
a.build_types(f, [somedict(a, annmodel.s_Int, annmodel.s_Int)])
fg = graphof(a, f)
et, ev = fg.exceptblock.inputargs
t = annmodel.SomeTypeOf([ev])
t.const = KeyError # IndexError ignored because 'dic' is a dict
assert et.annotation == t
s_ev = ev.annotation
assert s_ev == a.bookkeeper.new_exception([KeyError])
def test_exception_mixing(self):
def h():
pass
def g():
pass
class X(Exception):
def __init__(self, x=0):
self.x = x
def f(a, l):
if a==1:
raise X
elif a==2:
raise X(1)
elif a==3:
raise X(4)
else:
try:
l[0]
x,y = l
g()
finally:
h()
a = self.RPythonAnnotator()
a.build_types(f, [int, somelist(annmodel.s_Int)])
fg = graphof(a, f)
et, ev = fg.exceptblock.inputargs
t = annmodel.SomeTypeOf([ev])
assert et.annotation == t
s_ev = ev.annotation
assert (isinstance(s_ev, annmodel.SomeInstance) and
s_ev.classdef == a.bookkeeper.getuniqueclassdef(Exception))
def test_try_except_raise_finally1(self):
def h(): pass
def g(): pass
class X(Exception): pass
def f():
try:
try:
g()
except X:
h()
raise
finally:
h()
a = self.RPythonAnnotator()
a.build_types(f, [])
fg = graphof(a, f)
et, ev = fg.exceptblock.inputargs
t = annmodel.SomeTypeOf([ev])
assert et.annotation == t
s_ev = ev.annotation
assert (isinstance(s_ev, annmodel.SomeInstance) and
s_ev.classdef == a.bookkeeper.getuniqueclassdef(Exception))
def test_inplace_div(self):
def f(n):
n /= 2
return n / 2
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.knowntype == int
def test_prime(self):
a = self.RPythonAnnotator()
s = a.build_types(snippet.prime, [int])
assert s.knowntype == bool
def test_and_bool_coalesce(self):
def f(a,b,c,d,e):
x = a and b
if x:
return d,c
return e,c
a = self.RPythonAnnotator()
s = a.build_types(f, [int, str, a.bookkeeper.immutablevalue(1.0), a.bookkeeper.immutablevalue('d'), a.bookkeeper.immutablevalue('e')])
assert s == annmodel.SomeTuple([annmodel.SomeChar(), a.bookkeeper.immutablevalue(1.0)])
def test_bool_coalesce2(self):
def f(a,b,a1,b1,c,d,e):
x = (a or b) and (a1 or b1)
if x:
return d,c
return e,c
a = self.RPythonAnnotator()
s = a.build_types(f, [int, str, float, somelist(annmodel.s_Int),
a.bookkeeper.immutablevalue(1.0),
a.bookkeeper.immutablevalue('d'),
a.bookkeeper.immutablevalue('e')])
assert s == annmodel.SomeTuple([annmodel.SomeChar(),
a.bookkeeper.immutablevalue(1.0)])
def test_bool_coalesce_sanity(self):
def f(a):
while a:
pass
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s == a.bookkeeper.immutablevalue(None)
def test_non_None_path(self):
class C:
pass
def g(c):
if c is None:
return C()
return c
def f(x):
if x:
c = None
else:
c = C()
return g(c)
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert s.can_be_none() == False
def test_can_be_None_path(self):
class C:
pass
def f(x):
if x:
c = None
else:
c = C()
return isinstance(c, C)
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert not s.is_constant()
def test_nonneg_cleverness(self):
def f(a, b, c, d, e, f, g, h):
if a < 0: a = 0
if b <= 0: b = 0
if c >= 0:
pass
else:
c = 0
if d < a: d = a
if e <= b: e = 1
if c > f: f = 2
if d >= g: g = 3
if h != a: h = 0
return a, b, c, d, e, f, g, h
a = self.RPythonAnnotator()
s = a.build_types(f, [int]*8)
assert s == annmodel.SomeTuple([annmodel.SomeInteger(nonneg=True)] * 8)
def test_general_nonneg_cleverness(self):
def f(a, b, c, d, e, f, g, h):
if a < 0: a = 0
if b <= 0: b = 0
if c >= 0:
pass
else:
c = 0
if d < a: d = a
if e <= b: e = 1
if c > f: f = 2
if d >= g: g = 3
if h != a: h = 0
return a, b, c, d, e, f, g, h
a = self.RPythonAnnotator()
s = a.build_types(f, [r_longlong]*8)
assert s == annmodel.SomeTuple([annmodel.SomeInteger(nonneg=True, knowntype=r_longlong)] * 8)
def test_more_nonneg_cleverness(self):
def f(start, stop):
assert 0 <= start <= stop
return start, stop
a = self.RPythonAnnotator()
s = a.build_types(f, [int, int])
assert s == annmodel.SomeTuple([annmodel.SomeInteger(nonneg=True)] * 2)
def test_more_general_nonneg_cleverness(self):
def f(start, stop):
assert 0 <= start <= stop
return start, stop
a = self.RPythonAnnotator()
s = a.build_types(f, [r_longlong, r_longlong])
assert s == annmodel.SomeTuple([annmodel.SomeInteger(nonneg=True, knowntype=r_longlong)] * 2)
def test_nonneg_cleverness_is_gentle_with_unsigned(self):
def witness1(x):
pass
def witness2(x):
pass
def f(x):
if 0 < x:
witness1(x)
if x > 0:
witness2(x)
a = self.RPythonAnnotator()
s = a.build_types(f, [annmodel.SomeInteger(unsigned=True)])
wg1 = graphof(a, witness1)
wg2 = graphof(a, witness2)
assert a.binding(wg1.getargs()[0]).unsigned is True
assert a.binding(wg2.getargs()[0]).unsigned is True
def test_general_nonneg_cleverness_is_gentle_with_unsigned(self):
def witness1(x):
pass
def witness2(x):
pass
def f(x):
if 0 < x:
witness1(x)
if x > 0:
witness2(x)
a = self.RPythonAnnotator()
s = a.build_types(f, [annmodel.SomeInteger(knowntype=r_ulonglong)])
wg1 = graphof(a, witness1)
wg2 = graphof(a, witness2)
assert a.binding(wg1.getargs()[0]).knowntype is r_ulonglong
assert a.binding(wg2.getargs()[0]).knowntype is r_ulonglong
def test_nonneg_cleverness_in_max(self):
def f(x):
return max(x, 0) + max(0, x)
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.nonneg
def test_attr_moving_into_parent(self):
class A: pass
class B(A): pass
a1 = A()
b1 = B()
b1.stuff = a1
a1.stuff = None
def f():
return b1.stuff
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeInstance)
assert not s.can_be_None
assert s.classdef is a.bookkeeper.getuniqueclassdef(A)
def test_class_attribute(self):
class A:
stuff = 42
class B(A):
pass
def f():
b = B()
return b.stuff
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s == a.bookkeeper.immutablevalue(42)
def test_attr_recursive_getvalue(self):
class A: pass
a2 = A()
a2.stuff = None
a1 = A()
a1.stuff = a2
def f():
return a1.stuff
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeInstance)
assert s.can_be_None
assert s.classdef is a.bookkeeper.getuniqueclassdef(A)
def test_long_list_recursive_getvalue(self):
class A: pass
lst = []
for i in range(500):
a1 = A()
a1.stuff = lst
lst.append(a1)
def f():
A().stuff = None
return (A().stuff, lst)[1]
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeList)
s_item = s.listdef.listitem.s_value
assert isinstance(s_item, annmodel.SomeInstance)
def test_immutable_dict(self):
d = {4: "hello",
5: "world"}
def f(n):
return d[n]
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeString)
def test_immutable_recursive_list(self):
l = []
l.append(l)
def f():
return l
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeList)
s_item = s.listdef.listitem.s_value
assert isinstance(s_item, annmodel.SomeList)
assert s_item.listdef.same_as(s.listdef)
def test_defaults_with_list_or_dict(self):
def fn1(a=[]):
return a
def fn2(a={}):
return a
def f():
fn1()
fn2()
return fn1([6, 7]), fn2({2: 3, 4: 5})
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeTuple)
s1, s2 = s.items
assert not s1.is_constant()
assert not s2.is_constant()
assert isinstance(s1.listdef.listitem. s_value, annmodel.SomeInteger)
assert isinstance(s2.dictdef.dictkey. s_value, annmodel.SomeInteger)
assert isinstance(s2.dictdef.dictvalue.s_value, annmodel.SomeInteger)
def test_pbc_union(self):
class A:
def meth(self):
return 12
class B(A):
pass
class C(B):
pass
def f(i):
if i:
f(0)
x = B()
else:
x = C()
return x.meth()
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s == a.bookkeeper.immutablevalue(12)
def test_int(self):
def f(x, s):
return int(x) + int(s) + int(s, 16)
a = self.RPythonAnnotator()
s = a.build_types(f, [int, str])
assert s.knowntype == int
def test_int_nonneg(self):
def f(x, y):
assert x >= 0
return int(x) + int(y == 3)
a = self.RPythonAnnotator()
s = a.build_types(f, [int, int])
assert isinstance(s, annmodel.SomeInteger)
assert s.nonneg
def test_listitem_merge_asymmetry_bug(self):
class K:
pass
def mutr(k, x, i):
k.l2 = [x] + k.l2 # this involves a side-effectful union and unification, with this order
# of arguments some reflowing was missed
k.l2[i] = x
def witness(i):
pass
def trouble(k):
l = k.l1 + k.l2
for i in range(len(l)):
witness(l[i])
def f(flag, k, x, i):
if flag:
k = K()
k.l1 = []
k.l2 = []
trouble(k)
mutr(k, x, i)
a = self.RPythonAnnotator()
a.build_types(f, [bool, K, int, int])
g = graphof(a, witness)
assert a.binding(g.getargs()[0]).knowntype == int
# check RPython static semantics of isinstance(x,bool|int) as needed for wrap
def test_isinstance_int_bool(self):
def f(x):
if isinstance(x, int):
if isinstance(x, bool):
return "bool"
return "int"
return "dontknow"
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert s.const == "bool"
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.const == "int"
a = self.RPythonAnnotator()
s = a.build_types(f, [float])
assert s.const == "dontknow"
def test_hidden_method(self):
class Base:
def method(self):
return ["should be hidden"]
def indirect(self):
return self.method()
class A(Base):
def method(self):
return "visible"
class B(A): # note: it's a chain of subclasses
def method(self):
return None
def f(flag):
if flag:
obj = A()
else:
obj = B()
return obj.indirect()
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert annmodel.SomeString(can_be_None=True).contains(s)
def test_dont_see_AttributeError_clause(self):
class Stuff:
def _freeze_(self):
return True
def createcompiler(self):
try:
return self.default_compiler
except AttributeError:
compiler = "yadda"
self.default_compiler = compiler
return compiler
stuff = Stuff()
stuff.default_compiler = 123
def f():
return stuff.createcompiler()
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s == a.bookkeeper.immutablevalue(123)
def test_class_attribute_is_an_instance_of_itself(self):
class Base:
hello = None
class A(Base):
pass
A.hello = globalA = A()
def f():
return (Base().hello, globalA)
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeTuple)
assert isinstance(s.items[0], annmodel.SomeInstance)
assert s.items[0].classdef is a.bookkeeper.getuniqueclassdef(A)
assert s.items[0].can_be_None
assert s.items[1] == a.bookkeeper.immutablevalue(A.hello)
def test_dict_and_none(self):
def f(i):
if i:
return {}
else:
return None
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.knowntype == annmodel.SomeOrderedDict.knowntype
def test_const_list_and_none(self):
def g(l=None):
return l is None
L = [1,2]
def f():
g()
return g(L)
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.knowntype == bool
assert not s.is_constant()
def test_const_dict_and_none(self):
def g(d=None):
return d is None
D = {1:2}
def f():
g(D)
return g()
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.knowntype == bool
assert not s.is_constant()
def test_issubtype_and_const(self):
class A(object):
pass
class B(object):
pass
class C(A):
pass
b = B()
c = C()
def g(f):
if f == 1:
x = b
elif f == 2:
x = c
else:
x = C()
t = type(x)
return issubclass(t, A)
a = self.RPythonAnnotator()
x = annmodel.SomeInteger()
x.const = 1
s = a.build_types(g, [x])
assert s.const == False
a = self.RPythonAnnotator()
x = annmodel.SomeInteger()
x.const = 2
s = a.build_types(g, [x])
assert s.const == True
def test_reading_also_generalizes(self):
def f1(i):
d = {'c': i}
return d['not-a-char'], d
a = self.RPythonAnnotator()
s = a.build_types(f1, [int])
assert dictkey(s.items[1]).__class__ == annmodel.SomeString
def f2(i):
d = {'c': i}
return d.get('not-a-char', i+1), d
a = self.RPythonAnnotator()
s = a.build_types(f2, [int])
assert dictkey(s.items[1]).__class__ == annmodel.SomeString
def f3(i):
d = {'c': i}
return 'not-a-char' in d, d
a = self.RPythonAnnotator()
s = a.build_types(f3, [int])
assert dictkey(s.items[1]).__class__ == annmodel.SomeString
def f4():
lst = ['a', 'b', 'c']
return 'not-a-char' in lst, lst
a = self.RPythonAnnotator()
s = a.build_types(f4, [])
assert listitem(s.items[1]).__class__ == annmodel.SomeString
def f5():
lst = ['a', 'b', 'c']
return lst.index('not-a-char'), lst
a = self.RPythonAnnotator()
s = a.build_types(f5, [])
assert listitem(s.items[1]).__class__ == annmodel.SomeString
def test_true_str_is_not_none(self):
def f(s):
if s:
return s
else:
return ''
def g(i):
if i:
return f(None)
else:
return f('')
a = self.RPythonAnnotator()
s = a.build_types(g, [int])
assert s.knowntype == str
assert not s.can_be_None
def test_true_func_is_not_none(self):
def a1():
pass
def a2():
pass
def f(a):
if a:
return a
else:
return a2
def g(i):
if i:
return f(None)
else:
return f(a1)
a = self.RPythonAnnotator()
s = a.build_types(g, [int])
assert not s.can_be_None
def test_string_noNUL_canbeNone(self):
def f(a):
if a:
return "abc"
else:
return None
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.can_be_None
assert s.no_nul
def test_unicode_noNUL_canbeNone(self):
def f(a):
if a:
return u"abc"
else:
return None
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.can_be_None
assert s.no_nul
def test_str_or_None(self):
def f(a):
if a:
return "abc"
else:
return None
def g(a):
x = f(a)
if x is None:
return "abcd"
return x
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.can_be_None
assert s.no_nul
def test_unicode_or_None(self):
def f(a):
if a:
return u"abc"
else:
return None
def g(a):
x = f(a)
if x is None:
return u"abcd"
return x
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.can_be_None
assert s.no_nul
def test_emulated_pbc_call_simple(self):
def f(a,b):
return a + b
from rpython.annotator import annrpython
a = annrpython.RPythonAnnotator()
from rpython.annotator import model as annmodel
s_f = a.bookkeeper.immutablevalue(f)
a.bookkeeper.emulate_pbc_call('f', s_f, [annmodel.SomeInteger(), annmodel.SomeInteger()])
a.complete()
a.simplify()
assert a.binding(graphof(a, f).getreturnvar()).knowntype == int
fdesc = a.bookkeeper.getdesc(f)
someint = annmodel.SomeInteger()
assert (fdesc.get_s_signatures((2, (), False))
== [([someint,someint],someint)])
def test_emulated_pbc_call_callback(self):
def f(a,b):
return a + b
from rpython.annotator import annrpython
a = annrpython.RPythonAnnotator()
from rpython.annotator import model as annmodel
memo = []
def callb(ann, graph):
memo.append(annmodel.SomeInteger() == ann.binding(graph.getreturnvar()))
s_f = a.bookkeeper.immutablevalue(f)
s = a.bookkeeper.emulate_pbc_call('f', s_f, [annmodel.SomeInteger(), annmodel.SomeInteger()],
callback=callb)
assert s == annmodel.SomeImpossibleValue()
a.complete()
assert a.binding(graphof(a, f).getreturnvar()).knowntype == int
assert len(memo) >= 1
for t in memo:
assert t
def test_iterator_union(self):
def it(d):
return d.iteritems()
d0 = {1:2}
def f():
it(d0)
return it({1:2})
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeIterator)
assert s.variant == ('items',)
def test_iteritems_str0(self):
def it(d):
return d.iteritems()
def f():
d0 = {'1a': '2a', '3': '4'}
for item in it(d0):
return "%s=%s" % item
raise ValueError
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeString)
assert s.no_nul
def test_iteritems_unicode0(self):
def it(d):
return d.iteritems()
def f():
d0 = {u'1a': u'2a', u'3': u'4'}
for item in it(d0):
return u"%s=%s" % item
raise ValueError
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeUnicodeString)
assert s.no_nul
def test_no_nul_mod(self):
def f(x):
s = "%d" % x
return s
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeString)
assert s.no_nul
def test_no_nul_mod_unicode(self):
def f(x):
s = u"%d" % x
return s
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeUnicodeString)
assert s.no_nul
def test_mul_str0(self):
def f(s):
return s*10
a = self.RPythonAnnotator()
s = a.build_types(f, [annmodel.SomeString(no_nul=True)])
assert isinstance(s, annmodel.SomeString)
assert s.no_nul
a = self.RPythonAnnotator()
s = a.build_types(f, [annmodel.SomeUnicodeString(no_nul=True)])
assert isinstance(s, annmodel.SomeUnicodeString)
assert s.no_nul
def test_reverse_mul_str0(self):
def f(s):
return 10*s
a = self.RPythonAnnotator()
s = a.build_types(f, [annmodel.SomeString(no_nul=True)])
assert isinstance(s, annmodel.SomeString)
assert s.no_nul
a = self.RPythonAnnotator()
s = a.build_types(f, [annmodel.SomeUnicodeString(no_nul=True)])
assert isinstance(s, annmodel.SomeUnicodeString)
assert s.no_nul
def test_getitem_str0(self):
def f(s, n):
if n == 1:
return s[0]
elif n == 2:
return s[1]
elif n == 3:
return s[1:]
return s
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(f, [annmodel.SomeString(no_nul=True),
annmodel.SomeInteger()])
assert isinstance(s, annmodel.SomeString)
assert s.no_nul
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(f, [annmodel.SomeUnicodeString(no_nul=True),
annmodel.SomeInteger()])
assert isinstance(s, annmodel.SomeUnicodeString)
assert s.no_nul
def test_non_none_and_none_with_isinstance(self):
class A(object):
pass
class B(A):
pass
def g(x):
if isinstance(x, A):
return x
return None
def f():
g(B())
return g(None)
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef == a.bookkeeper.getuniqueclassdef(B)
def test_type_is_no_improvement(self):
class B(object):
pass
class C(B):
pass
class D(B):
pass
def f(x):
if type(x) is C:
return x
raise Exception
a = self.RPythonAnnotator()
s = a.build_types(f, [D])
assert s == annmodel.SomeImpossibleValue()
def test_is_constant_instance(self):
class A(object):
pass
prebuilt_instance = A()
def f(x):
if x is prebuilt_instance:
return x
raise Exception
a = self.RPythonAnnotator()
s = a.build_types(f, [A])
assert s.is_constant()
assert s.const is prebuilt_instance
def test_call_memoized_function(self):
fr1 = Freezing()
fr2 = Freezing()
def getorbuild(key):
a = 1
if key is fr1:
result = eval("a+2")
else:
result = eval("a+6")
return result
getorbuild._annspecialcase_ = "specialize:memo"
def f1(i):
if i > 0:
fr = fr1
else:
fr = fr2
return getorbuild(fr)
a = self.RPythonAnnotator()
s = a.build_types(f1, [int])
assert s.knowntype == int
def test_call_memoized_function_with_bools(self):
fr1 = Freezing()
fr2 = Freezing()
def getorbuild(key, flag1, flag2):
a = 1
if key is fr1:
result = eval("a+2")
else:
result = eval("a+6")
if flag1:
result += 100
if flag2:
result += 1000
return result
getorbuild._annspecialcase_ = "specialize:memo"
def f1(i):
if i > 0:
fr = fr1
else:
fr = fr2
return getorbuild(fr, i % 2 == 0, i % 3 == 0)
a = self.RPythonAnnotator()
s = a.build_types(f1, [int])
assert s.knowntype == int
def test_stored_bound_method(self):
# issue 129
class H:
def h(self):
return 42
class C:
def __init__(self, func):
self.f = func
def do(self):
return self.f()
def g():
h = H()
c = C(h.h)
return c.do()
a = self.RPythonAnnotator()
s = a.build_types(g, [])
assert s.is_constant()
assert s.const == 42
def test_stored_bound_method_2(self):
# issue 129
class H:
pass
class H1(H):
def h(self):
return 42
class H2(H):
def h(self):
return 17
class C:
def __init__(self, func):
self.f = func
def do(self):
return self.f()
def g(flag):
if flag:
h = H1()
else:
h = H2()
c = C(h.h)
return c.do()
a = self.RPythonAnnotator()
s = a.build_types(g, [int])
assert s.knowntype == int
assert not s.is_constant()
def test_getorbuild_as_attr(self):
from rpython.rlib.cache import Cache
class SpaceCache(Cache):
def _build(self, callable):
return callable()
class CacheX(Cache):
def _build(self, key):
return key.x
class CacheY(Cache):
def _build(self, key):
return key.y
class X:
def __init__(self, x):
self.x = x
def _freeze_(self):
return True
class Y:
def __init__(self, y):
self.y = y
def _freeze_(self):
return True
X1 = X(1)
Y2 = Y("hello")
fromcache = SpaceCache().getorbuild
def f():
return (fromcache(CacheX).getorbuild(X1),
fromcache(CacheY).getorbuild(Y2))
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.items[0].knowntype == int
assert s.items[1].knowntype == str
def test_constant_bound_method(self):
class C:
def __init__(self, value):
self.value = value
def meth(self):
return self.value
meth = C(1).meth
def f():
return meth()
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.knowntype == int
def test_annotate__del__(self):
class A(object):
def __init__(self):
self.a = 2
def __del__(self):
self.a = 1
def f():
return A().a
a = self.RPythonAnnotator()
t = a.translator
s = a.build_types(f, [])
assert s.knowntype == int
graph = tgraphof(t, A.__del__.im_func)
assert graph.startblock in a.annotated
def test_annotate__del__baseclass(self):
class A(object):
def __init__(self):
self.a = 2
def __del__(self):
self.a = 1
class B(A):
def __init__(self):
self.a = 3
def f():
return B().a
a = self.RPythonAnnotator()
t = a.translator
s = a.build_types(f, [])
assert s.knowntype == int
graph = tgraphof(t, A.__del__.im_func)
assert graph.startblock in a.annotated
def test_annotate_type(self):
class A:
pass
x = [A(), A()]
def witness(t):
return type(t)
def get(i):
return x[i]
def f(i):
witness(None)
return witness(get(i))
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeType)
def test_annotate_iter_empty_container(self):
def f():
n = 0
d = {}
for x in []: n += x
for y in d: n += y
for z in d.iterkeys(): n += z
for s in d.itervalues(): n += s
for t, u in d.items(): n += t * u
for t, u in d.iteritems(): n += t * u
return n
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.is_constant()
assert s.const == 0
def test_mixin(self):
class Mixin(object):
_mixin_ = True
def m(self, v):
return v
class Base(object):
pass
class A(Base, Mixin):
pass
class B(Base, Mixin):
pass
class C(B):
pass
def f():
a = A()
v0 = a.m(2)
b = B()
v1 = b.m('x')
c = C()
v2 = c.m('y')
return v0, v1, v2
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s.items[0], annmodel.SomeInteger)
assert isinstance(s.items[1], annmodel.SomeChar)
assert isinstance(s.items[2], annmodel.SomeChar)
def test_mixin_staticmethod(self):
class Mixin(object):
_mixin_ = True
@staticmethod
def m(v):
return v
class Base(object):
pass
class A(Base, Mixin):
pass
class B(Base, Mixin):
pass
class C(B):
pass
def f():
a = A()
v0 = a.m(2)
b = B()
v1 = b.m('x')
c = C()
v2 = c.m('y')
return v0, v1, v2
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s.items[0], annmodel.SomeInteger)
assert isinstance(s.items[1], annmodel.SomeChar)
assert isinstance(s.items[2], annmodel.SomeChar)
def test_mixin_first(self):
class Mixin(object):
_mixin_ = True
def foo(self): return 4
class Base(object):
def foo(self): return 5
class Concrete(Mixin, Base):
pass
def f():
return Concrete().foo()
assert f() == 4
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == 4
def test_mixin_last(self):
class Mixin(object):
_mixin_ = True
def foo(self): return 4
class Base(object):
def foo(self): return 5
class Concrete(Base, Mixin):
pass
def f():
return Concrete().foo()
assert f() == 5
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == 5
def test_mixin_concrete(self):
class Mixin(object):
_mixin_ = True
def foo(self): return 4
class Concrete(Mixin):
def foo(self): return 5
def f():
return Concrete().foo()
assert f() == 5
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == 5
def test_multiple_mixins_mro(self):
# an obscure situation, but it occurred in module/micronumpy/types.py
class A(object):
_mixin_ = True
def foo(self): return 1
class B(A):
_mixin_ = True
def foo(self): return 2
class C(A):
_mixin_ = True
class D(B, C):
_mixin_ = True
class Concrete(D):
pass
def f():
return Concrete().foo()
assert f() == 2
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == 2
def test_multiple_mixins_mro_2(self):
class A(object):
_mixin_ = True
def foo(self): return 1
class B(A):
_mixin_ = True
def foo(self): return 2
class C(A):
_mixin_ = True
class Concrete(C, B):
pass
def f():
return Concrete().foo()
assert f() == 2
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.const == 2
def test_cannot_use_directly_mixin(self):
class A(object):
_mixin_ = True
#
def f():
return A()
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [])
#
class B(object):
pass
x = B()
def g():
return isinstance(x, A)
py.test.raises(AnnotatorError, a.build_types, g, [])
def test_import_from_mixin(self):
class M(object):
def f(self):
return self.a
class I(object):
objectmodel.import_from_mixin(M)
def __init__(self, i):
self.a = i
class S(object):
objectmodel.import_from_mixin(M)
def __init__(self, s):
self.a = s
def f(n):
return (I(n).f(), S("a" * n).f())
assert f(3) == (3, "aaa")
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s.items[0], annmodel.SomeInteger)
assert isinstance(s.items[1], annmodel.SomeString)
def test___class___attribute(self):
class Base(object): pass
class A(Base): pass
class B(Base): pass
class C(A): pass
def seelater():
C()
def f(n):
if n == 1:
x = A()
else:
x = B()
y = B()
result = x.__class__, y.__class__
seelater()
return result
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s.items[0], annmodel.SomePBC)
assert len(s.items[0].descriptions) == 4
assert isinstance(s.items[1], annmodel.SomePBC)
assert len(s.items[1].descriptions) == 1
def test_slots(self):
# check that the annotator ignores slots instead of being
# confused by them showing up as 'member' objects in the class
class A(object):
__slots__ = ('a', 'b')
def f(x):
a = A()
a.b = x
return a.b
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.knowntype == int
def test_slots_reads(self):
class A(object):
__slots__ = ()
class B(A):
def __init__(self, x):
self.x = x
def f(x):
if x:
a = A()
else:
a = B(x)
return a.x # should explode here
a = self.RPythonAnnotator()
with py.test.raises(NoSuchAttrError) as excinfo:
a.build_types(f, [int])
# this should explode on reading the attribute 'a.x', but it can
# sometimes explode on 'self.x = x', which does not make much sense.
# But it looks hard to fix in general: we don't know yet during 'a.x'
# if the attribute x will be read-only or read-write.
def test_unboxed_value(self):
class A(object):
__slots__ = ()
class C(A, objectmodel.UnboxedValue):
__slots__ = unboxedattrname = 'smallint'
def f(n):
return C(n).smallint
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.knowntype == int
def test_annotate_bool(self):
def f(x):
return ~x
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert s.knowntype == int
def f(x):
return -x
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert s.knowntype == int
def f(x):
return +x
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert s.knowntype == int
def f(x):
return abs(x)
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert s.knowntype == int
def f(x):
return int(x)
a = self.RPythonAnnotator()
s = a.build_types(f, [bool])
assert s.knowntype == int
def f(x, y):
return x + y
a = self.RPythonAnnotator()
s = a.build_types(f, [bool, int])
assert s.knowntype == int
a = self.RPythonAnnotator()
s = a.build_types(f, [int, bool])
assert s.knowntype == int
def test_annotate_rarith(self):
inttypes = [int, r_uint, r_longlong, r_ulonglong]
for inttype in inttypes:
c = inttype()
def f():
return c
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeInteger)
assert s.knowntype == inttype
assert s.unsigned == (inttype(-1) > 0)
for inttype in inttypes:
def f():
return inttype(0)
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeInteger)
assert s.knowntype == inttype
assert s.unsigned == (inttype(-1) > 0)
for inttype in inttypes:
def f(x):
return x
a = self.RPythonAnnotator()
s = a.build_types(f, [inttype])
assert isinstance(s, annmodel.SomeInteger)
assert s.knowntype == inttype
assert s.unsigned == (inttype(-1) > 0)
def test_annotate_rshift(self):
def f(x):
return x >> 2
a = self.RPythonAnnotator()
s = a.build_types(f, [annmodel.SomeInteger(nonneg=True)])
assert isinstance(s, annmodel.SomeInteger)
assert s.nonneg
def test_prebuilt_mutables(self):
class A:
pass
class B:
pass
a1 = A()
a2 = A()
a1.d = {} # this tests confusion between the two '{}', which
a2.d = {} # compare equal
a1.l = []
a2.l = []
b = B()
b.d1 = a1.d
b.d2 = a2.d
b.l1 = a1.l
b.l2 = a2.l
def dmutate(d):
d[123] = 321
def lmutate(l):
l.append(42)
def readout(d, l):
return len(d) + len(l)
def f():
dmutate(b.d1)
dmutate(b.d2)
dmutate(a1.d)
dmutate(a2.d)
lmutate(b.l1)
lmutate(b.l2)
lmutate(a1.l)
lmutate(a2.l)
return readout(a1.d, a1.l) + readout(a2.d, a2.l)
a = self.RPythonAnnotator()
a.build_types(f, [])
v1, v2 = graphof(a, readout).getargs()
assert not a.binding(v1).is_constant()
assert not a.binding(v2).is_constant()
def test_prebuilt_mutables_dont_use_eq(self):
# test that __eq__ is not called during annotation, at least
# when we know that the classes differ anyway
class Base(object):
def __eq__(self, other):
if self is other:
return True
raise ValueError
def __hash__(self):
return 42
class A(Base):
pass
class B(Base):
pass
a1 = A()
a2 = B()
a1.x = 5
a2.x = 6
def f():
return a1.x + a2.x
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert s.knowntype == int
def test_chr_out_of_bounds(self):
def g(n, max):
if n < max:
return chr(n)
else:
return '?'
def fun(max):
v = g(1000, max)
return g(ord(v), max)
a = self.RPythonAnnotator()
s = a.build_types(fun, [int])
assert isinstance(s, annmodel.SomeChar)
def test_range_nonneg(self):
def fun(n, k):
for i in range(n):
if k == 17:
return i
return 0
a = self.RPythonAnnotator()
s = a.build_types(fun, [int, int])
assert isinstance(s, annmodel.SomeInteger)
assert s.nonneg
def test_range_nonneg_variablestep(self):
def get_step(n):
if n == 1:
return 2
else:
return 3
def fun(n, k):
step = get_step(n)
for i in range(0, n, step):
if k == 17:
return i
return 0
a = self.RPythonAnnotator()
s = a.build_types(fun, [int, int])
assert isinstance(s, annmodel.SomeInteger)
assert s.nonneg
def test_reverse_range_nonneg(self):
def fun(n, k):
for i in range(n-1, -1, -1):
if k == 17:
return i
return 0
a = self.RPythonAnnotator()
s = a.build_types(fun, [int, int])
assert isinstance(s, annmodel.SomeInteger)
assert s.nonneg
def test_sig(self):
def fun(x, y):
return x+y
s_nonneg = annmodel.SomeInteger(nonneg=True)
fun._annenforceargs_ = Sig(int, s_nonneg)
a = self.RPythonAnnotator()
s = a.build_types(fun, [s_nonneg, s_nonneg])
assert isinstance(s, annmodel.SomeInteger)
assert not s.nonneg
with py.test.raises(SignatureError):
a.build_types(fun, [int, int])
def test_sig_simpler(self):
def fun(x, y):
return x+y
s_nonneg = annmodel.SomeInteger(nonneg=True)
fun._annenforceargs_ = (int, s_nonneg)
a = self.RPythonAnnotator()
s = a.build_types(fun, [s_nonneg, s_nonneg])
assert isinstance(s, annmodel.SomeInteger)
assert not s.nonneg
with py.test.raises(SignatureError):
a.build_types(fun, [int, int])
def test_sig_lambda(self):
def fun(x, y):
return y
s_nonneg = annmodel.SomeInteger(nonneg=True)
fun._annenforceargs_ = Sig(lambda s1,s2: s1, lambda s1,s2: s1)
# means: the 2nd argument's annotation becomes the 1st argument's
# input annotation
a = self.RPythonAnnotator()
s = a.build_types(fun, [int, s_nonneg])
assert isinstance(s, annmodel.SomeInteger)
assert not s.nonneg
with py.test.raises(SignatureError):
a.build_types(fun, [s_nonneg, int])
def test_sig_bug(self):
def g(x, y=5):
return y == 5
g._annenforceargs_ = (int, int)
def fun(x):
return g(x)
a = self.RPythonAnnotator()
s = a.build_types(fun, [int])
assert s.knowntype is bool
assert s.is_constant()
def test_sig_list(self):
def g(buf):
buf.append(5)
g._annenforceargs_ = ([int],)
def fun():
lst = []
g(lst)
return lst[0]
a = self.RPythonAnnotator()
s = a.build_types(fun, [])
assert s.knowntype is int
assert not s.is_constant()
def test_slots_check(self):
class Base(object):
__slots__ = 'x'
class A(Base):
__slots__ = 'y'
def m(self):
return 65
class C(Base):
__slots__ = 'z'
def m(self):
return 67
for attrname, works in [('x', True),
('y', False),
('z', False),
('t', False)]:
def fun(n):
if n: o = A()
else: o = C()
setattr(o, attrname, 12)
return o.m()
a = self.RPythonAnnotator()
if works:
a.build_types(fun, [int])
else:
with py.test.raises(NoSuchAttrError):
a.build_types(fun, [int])
def test_slots_enforce_attrs(self):
class Superbase(object):
__slots__ = 'x'
class Base(Superbase):
pass
class A(Base):
pass
class B(Base):
pass
def fun(s):
if s is None: # known not to be None in this test
o = B()
o.x = 12
elif len(s) > 5:
o = A()
else:
o = Base()
return o.x
a = self.RPythonAnnotator()
s = a.build_types(fun, [str])
assert s == annmodel.s_ImpossibleValue # but not blocked blocks
def test_enforced_attrs_check(self):
class Base(object):
_attrs_ = 'x'
class A(Base):
_attrs_ = 'y'
def m(self):
return 65
class C(Base):
_attrs_ = 'z'
def m(self):
return 67
for attrname, works in [('x', True),
('y', False),
('z', False),
('t', False)]:
def fun(n):
if n: o = A()
else: o = C()
setattr(o, attrname, 12)
return o.m()
a = self.RPythonAnnotator()
if works:
a.build_types(fun, [int])
else:
py.test.raises(NoSuchAttrError, a.build_types, fun, [int])
def test_attrs_enforce_attrs(self):
class Superbase(object):
_attrs_ = 'x'
class Base(Superbase):
pass
class A(Base):
pass
class B(Base):
pass
def fun(s):
if s is None: # known not to be None in this test
o = B()
o.x = 12
elif len(s) > 5:
o = A()
else:
o = Base()
return o.x
a = self.RPythonAnnotator()
s = a.build_types(fun, [str])
assert s == annmodel.s_ImpossibleValue # but not blocked blocks
def test_pbc_enforce_attrs(self):
class F(object):
_attrs_ = ['foo',]
def _freeze_(self):
return True
p1 = F()
p2 = F()
def g(): pass
def f(x):
if x:
p = p1
else:
p = p2
g()
return p.foo
a = self.RPythonAnnotator()
a.build_types(f, [bool])
def test_float_cmp(self):
def fun(x, y):
return (x < y,
x <= y,
x == y,
x != y,
x > y,
x >= y)
a = self.RPythonAnnotator(policy=AnnotatorPolicy())
s = a.build_types(fun, [float, float])
assert [s_item.knowntype for s_item in s.items] == [bool] * 6
def test_empty_range(self):
def g(lst):
total = 0
for i in range(len(lst)):
total += lst[i]
return total
def fun():
return g([])
a = self.RPythonAnnotator(policy=AnnotatorPolicy())
s = a.build_types(fun, [])
assert s.const == 0
def test_compare_int_bool(self):
def fun(x):
return 50 < x
a = self.RPythonAnnotator(policy=AnnotatorPolicy())
s = a.build_types(fun, [bool])
assert isinstance(s, annmodel.SomeBool)
def test_long_as_intermediate_value(self):
from sys import maxint
from rpython.rlib.rarithmetic import intmask
def fun(x):
if x > 0:
v = maxint
else:
v = -maxint
return intmask(v * 10)
P = AnnotatorPolicy()
a = self.RPythonAnnotator(policy=P)
s = a.build_types(fun, [bool])
assert isinstance(s, annmodel.SomeInteger)
def test_instance_with_flags(self):
from rpython.rlib.jit import hint
class A:
_virtualizable_ = []
class B(A):
def meth(self):
return self
class C(A):
def meth(self):
return self
def f(n):
x = B()
x = hint(x, access_directly=True)
m = x.meth
for i in range(n):
x = C()
m = x.meth
return x, m, m()
a = self.RPythonAnnotator()
s = a.build_types(f, [a.bookkeeper.immutablevalue(0)])
assert isinstance(s.items[0], annmodel.SomeInstance)
assert s.items[0].flags == {'access_directly': True}
assert isinstance(s.items[1], annmodel.SomePBC)
assert len(s.items[1].descriptions) == 1
assert s.items[1].any_description().flags == {'access_directly':
True}
assert isinstance(s.items[2], annmodel.SomeInstance)
assert s.items[2].flags == {'access_directly': True}
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s.items[0], annmodel.SomeInstance)
assert s.items[0].flags == {}
assert isinstance(s.items[1], annmodel.SomePBC)
assert isinstance(s.items[2], annmodel.SomeInstance)
assert s.items[2].flags == {}
@py.test.mark.xfail
def test_no_access_directly_on_heap(self):
from rpython.rlib.jit import hint
class A:
_virtualizable_ = []
class I:
pass
def f():
x = A()
x = hint(x, access_directly=True)
i = I()
i.x = x
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [])
class M:
def __init__(self):
self.l = []
self.d = {}
class C:
def _freeze_(self):
return True
def __init__(self):
self.m = M()
self.l2 = []
c = C()
def f():
x = A()
x = hint(x, access_directly=True)
c.m.l.append(x)
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [])
def f():
x = A()
x = hint(x, access_directly=True)
c.m.d[None] = x
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [])
def f():
x = A()
x = hint(x, access_directly=True)
c.m.d[x] = None
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [])
def test_weakref(self):
import weakref
class A:
pass
class B(A):
pass
class C(A):
pass
def f(n):
if n:
b = B()
b.hello = 42
r = weakref.ref(b)
else:
c = C()
c.hello = 64
r = weakref.ref(c)
return r().hello
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeInteger)
assert not s.is_constant()
def test_float_pow_unsupported(self):
def f(x, y):
x **= y
return x ** y
a = self.RPythonAnnotator()
py.test.raises(FlowingError, a.build_types, f, [int, int])
a = self.RPythonAnnotator()
py.test.raises(FlowingError, a.build_types, f, [float, float])
def test_intcmp_bug(self):
def g(x, y):
return x <= y
def f(x, y):
if g(x, y):
g(x, r_uint(y))
a = self.RPythonAnnotator()
with py.test.raises(UnionError):
a.build_types(f, [int, int])
def test_compare_with_zero(self):
def g():
should_not_see_this
def f(n):
assert n >= 0
if n < 0:
g()
if not (n >= 0):
g()
a = self.RPythonAnnotator()
a.build_types(f, [int])
def test_r_singlefloat(self):
z = r_singlefloat(0.4)
def g(n):
if n > 0:
return r_singlefloat(n * 0.1)
else:
return z
a = self.RPythonAnnotator()
s = a.build_types(g, [int])
assert isinstance(s, annmodel.SomeSingleFloat)
def test_unicode_simple(self):
def f():
return u'xxx'
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeUnicodeString)
def test_unicode(self):
def g(n):
if n > 0:
return unichr(1234)
else:
return u"x\xe4x"
def f(n):
x = g(0)
return x[n]
a = self.RPythonAnnotator()
s = a.build_types(g, [int])
assert isinstance(s, annmodel.SomeUnicodeString)
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeUnicodeCodePoint)
def test_unicode_from_string(self):
def f(x):
return unicode(x)
a = self.RPythonAnnotator()
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeUnicodeString)
def test_unicode_add(self):
def f(x):
return unicode(x) + unichr(1234)
def g(x):
return unichr(x) + unichr(2)
a = self.RPythonAnnotator()
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeUnicodeString)
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeUnicodeString)
def test_unicode_startswith(self):
def f(x):
return u'xxxx'.replace(x, u'z')
a = self.RPythonAnnotator()
s = a.build_types(f, [unicode])
assert isinstance(s, annmodel.SomeUnicodeString)
def test_unicode_buildtypes(self):
def f(x):
return x
a = self.RPythonAnnotator()
s = a.build_types(f, [unicode])
assert isinstance(s, annmodel.SomeUnicodeString)
def test_replace_annotations(self):
def f(x):
return 'a'.replace(x, 'b')
a = self.RPythonAnnotator()
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeString)
assert s.no_nul
def f(x):
return u'a'.replace(x, u'b')
a = self.RPythonAnnotator()
s = a.build_types(f, [unicode])
assert isinstance(s, annmodel.SomeUnicodeString)
assert s.no_nul
def test_unicode_char(self):
def f(x, i):
for c in x:
if c == i:
return c
return 'x'
a = self.RPythonAnnotator()
s = a.build_types(f, [unicode, str])
assert isinstance(s, annmodel.SomeUnicodeCodePoint)
def test_strformatting_unicode(self):
def f(x):
return '%s' % unichr(x)
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [int])
def f(x):
return '%s' % (unichr(x) * 3)
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [int])
def f(x):
return '%s%s' % (1, unichr(x))
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [int])
def f(x):
return '%s%s' % (1, unichr(x) * 15)
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, a.build_types, f, [int])
def test_strformatting_tuple(self):
"""
A function which returns the result of interpolating a tuple of a
single str into a str format string should be annotated as returning
SomeString.
"""
def f(x):
return '%s' % (x,)
a = self.RPythonAnnotator()
s = a.build_types(f, [str])
assert isinstance(s, annmodel.SomeString)
def test_unicodeformatting(self):
def f(x):
return u'%s' % x
a = self.RPythonAnnotator()
s = a.build_types(f, [unicode])
assert isinstance(s, annmodel.SomeUnicodeString)
def test_unicodeformatting_tuple(self):
def f(x):
return u'%s' % (x,)
a = self.RPythonAnnotator()
s = a.build_types(f, [unicode])
assert isinstance(s, annmodel.SomeUnicodeString)
def test_extended_slice(self):
a = self.RPythonAnnotator()
def f(start, end, step):
return [1, 2, 3][start:end:step]
with py.test.raises(AnnotatorError):
a.build_types(f, [int, int, int])
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True)])
def f(x):
return x[::-1]
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [str])
def f(x):
return x[::2]
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [str])
def f(x):
return x[1:2:1]
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [str])
def test_negative_slice(self):
def f(s, e):
return [1, 2, 3][s:e]
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, "a.build_types(f, [int, int])")
a.build_types(f, [annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True)])
def f(x):
return x[:-1]
a.build_types(f, [str])
def test_negative_number_find(self):
def f(s, e):
return "xyz".find("x", s, e)
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError, "a.build_types(f, [int, int])")
a.build_types(f, [annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True)])
def f(s, e):
return "xyz".rfind("x", s, e)
py.test.raises(AnnotatorError, "a.build_types(f, [int, int])")
a.build_types(f, [annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True)])
def f(s, e):
return "xyz".count("x", s, e)
py.test.raises(AnnotatorError, "a.build_types(f, [int, int])")
a.build_types(f, [annmodel.SomeInteger(nonneg=True),
annmodel.SomeInteger(nonneg=True)])
def test_setslice(self):
def f():
lst = [2, 5, 7]
lst[1:2] = [4]
return lst
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeList)
assert s.listdef.listitem.resized
assert not s.listdef.listitem.immutable
assert s.listdef.listitem.mutated
def test_delslice(self):
def f():
lst = [2, 5, 7]
del lst[1:2]
return lst
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeList)
assert s.listdef.listitem.resized
def test_varargs(self):
def f(*args):
return args[0] + 42
a = self.RPythonAnnotator()
s = a.build_types(f, [int, int])
assert isinstance(s, annmodel.SomeInteger)
def test_listitem_no_mutating(self):
from rpython.rlib.debug import check_annotation
called = []
def checker(ann, bk):
called.append(True)
assert not ann.listdef.listitem.mutated
ann.listdef.never_resize()
def f():
l = [1,2,3]
check_annotation(l, checker)
return l
def g():
l = f()
l.append(4)
a = self.RPythonAnnotator()
py.test.raises(ListChangeUnallowed, a.build_types, g, [])
assert called
def test_listitem_no_mutating2(self):
from rpython.rlib.debug import make_sure_not_resized
def f():
return make_sure_not_resized([1,2,3])
def g():
l = [1,2,3]
l.append(4)
return l
def fn(i):
if i:
func = f
else:
func = g
return func()
a = self.RPythonAnnotator()
a.translator.config.translation.list_comprehension_operations = True
py.test.raises(ListChangeUnallowed, a.build_types, fn, [int])
def test_listitem_never_resize(self):
from rpython.rlib.debug import check_annotation
def checker(ann, bk):
ann.listdef.never_resize()
def f():
l = [1,2,3]
l.append(4)
check_annotation(l, checker)
a = self.RPythonAnnotator()
py.test.raises(ListChangeUnallowed, a.build_types, f, [])
def test_len_of_empty_list(self):
class X:
pass
def f(n):
x = X()
x.lst = None
if n < 0: # to showcase a failure of the famous "assert contains"
return len(x.lst)
x.lst = []
return len(x.lst)
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.const == 0
def test_hash_sideeffect(self):
class X:
pass
x1 = X()
x2 = X()
x3 = X()
d = {(2, x1): 5, (3, x2): 7}
def f(n, m):
if m == 1: x = x1
elif m == 2: x = x2
else: x = x3
return d[n, x]
a = self.RPythonAnnotator()
s = a.build_types(f, [int, int])
assert s.knowntype == int
assert hasattr(x1, '__precomputed_identity_hash')
assert hasattr(x2, '__precomputed_identity_hash')
assert not hasattr(x3, '__precomputed_identity_hash')
def test_contains_of_empty_dict(self):
class A(object):
def meth(self):
return 1
def g(x, y):
d1 = {}
for i in range(y):
if x in d1:
return d1[x].meth()
d1[i+1] = A()
return 0
a = self.RPythonAnnotator()
s = a.build_types(g, [int, int])
assert s.knowntype is int
def f(x):
d0 = {}
if x in d0:
d0[x].meth()
return x+1
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.knowntype is int
def test_relax(self):
def f(*args):
return args[0] + args[1]
f.relax_sig_check = True
def g(x):
return f(x, x - x)
a = self.RPythonAnnotator()
s = a.build_types(g, [int])
assert a.bookkeeper.getdesc(f).getuniquegraph()
def test_cannot_raise_ll_exception(self):
from rpython.rtyper.annlowlevel import cast_instance_to_base_ptr
#
def f():
e = OverflowError()
lle = cast_instance_to_base_ptr(e)
raise Exception(lle)
# ^^^ instead, must cast back from a base ptr to an instance
a = self.RPythonAnnotator()
with py.test.raises(AssertionError):
a.build_types(f, [])
def test_enumerate(self):
def f():
for i, x in enumerate(['a', 'b', 'c', 'd']):
if i == 2:
return x
return '?'
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeChar)
def test_context_manager(self):
class C:
def __init__(self):
pass
def __enter__(self):
self.x = 1
def __exit__(self, *args):
self.x = 3
def f():
c = C()
with c:
pass
return c.x
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeInteger)
# not a constant: both __enter__ and __exit__ have been annotated
assert not s.is_constant()
def test_make_sure_not_resized(self):
from rpython.rlib.debug import make_sure_not_resized
def pycode(consts):
make_sure_not_resized(consts)
def build1():
return pycode(consts=[1])
def build2():
return pycode(consts=[0])
def fn():
build1()
build2()
a = self.RPythonAnnotator()
a.translator.config.translation.list_comprehension_operations = True
a.build_types(fn, [])
# assert did not raise ListChangeUnallowed
def test_return_immutable_list(self):
class A:
_immutable_fields_ = ['lst[*]']
def f(n):
a = A()
l1 = [n, 0]
l1[1] = n+1
a.lst = l1
return a.lst
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.listdef.listitem.immutable
def test_return_immutable_list_quasiimmut_field(self):
class A:
_immutable_fields_ = ['lst?[*]']
def f(n):
a = A()
l1 = [n, 0]
l1[1] = n+1
a.lst = l1
return a.lst
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.listdef.listitem.immutable
def test_immutable_list_is_actually_resized(self):
class A:
_immutable_fields_ = ['lst[*]']
def f(n):
a = A()
l1 = [n]
l1.append(n+1)
a.lst = l1
return a.lst
a = self.RPythonAnnotator()
py.test.raises(ListChangeUnallowed, a.build_types, f, [int])
def test_immutable_list_is_assigned_a_resizable_list(self):
class A:
_immutable_fields_ = ['lst[*]']
def f(n):
a = A()
foo = []
foo.append(n)
a.lst = foo
a = self.RPythonAnnotator()
py.test.raises(ListChangeUnallowed, a.build_types, f, [int])
def test_can_merge_immutable_list_with_regular_list(self):
class A:
_immutable_fields_ = ['lst[*]']
def foo(lst):
pass
def f(n):
a = A()
l1 = [n, 0]
l1[1] = n+1
a.lst = l1
if n > 0:
foo(a.lst)
else:
lst = [0]
lst[0] = n
foo(lst)
a = self.RPythonAnnotator()
a.build_types(f, [int])
def f(n):
a = A()
l1 = [n, 0]
l1[1] = n+1
a.lst = l1
if n > 0:
lst = [0]
lst[0] = n
foo(lst)
else:
foo(a.lst)
a = self.RPythonAnnotator()
a.build_types(f, [int])
def test_immutable_field_subclass(self):
class Root:
pass
class A(Root):
_immutable_fields_ = ['_my_lst[*]']
def __init__(self, lst):
self._my_lst = lst
def foo(x):
return len(x._my_lst)
def f(n):
foo(A([2, n]))
foo(Root())
a = self.RPythonAnnotator()
e = py.test.raises(Exception, a.build_types, f, [int])
assert "field '_my_lst' was migrated" in str(e.value)
def test_range_variable_step(self):
def g(n):
return range(0, 10, n)
def f(n):
r = g(1) # constant step, at first
s = g(n) # but it becomes a variable step
return r
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert s.listdef.listitem.range_step == 0
def test_specialize_arg_memo(self):
@objectmodel.specialize.memo()
def g(n):
return n
@objectmodel.specialize.arg(0)
def f(i):
return g(i)
def main(i):
if i == 2:
return f(2)
elif i == 3:
return f(3)
else:
raise NotImplementedError
a = self.RPythonAnnotator()
s = a.build_types(main, [int])
assert isinstance(s, annmodel.SomeInteger)
def test_join_none_and_nonnull(self):
from rpython.rlib.rstring import assert_str0
def f(i):
a = str(i)
a = assert_str0(a)
return a.join([None])
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeString)
assert not s.can_be_None
def test_contains_no_nul(self):
def f(i):
if "\0" in i:
return None
else:
return i
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(f, [annmodel.SomeString(no_nul=False)])
assert isinstance(s, annmodel.SomeString)
assert s.can_be_None
assert s.no_nul
def test_contains_no_nul_unicode(self):
def f(i):
if u"\0" in i:
return None
else:
return i
a = self.RPythonAnnotator()
a.translator.config.translation.check_str_without_nul = True
s = a.build_types(f, [annmodel.SomeUnicodeString(no_nul=False)])
assert isinstance(s, annmodel.SomeUnicodeString)
assert s.can_be_None
assert s.no_nul
def test_no___call__(self):
class X(object):
def __call__(self):
xxx
x = X()
def f():
return x
a = self.RPythonAnnotator()
e = py.test.raises(Exception, a.build_types, f, [])
assert 'object with a __call__ is not RPython' in str(e.value)
def test_os_getcwd(self):
import os
def fn():
return os.getcwd()
a = self.RPythonAnnotator()
s = a.build_types(fn, [])
assert isinstance(s, annmodel.SomeString)
assert s.no_nul
def test_os_getenv(self):
import os
def fn():
return os.environ.get('PATH')
a = self.RPythonAnnotator()
s = a.build_types(fn, [])
assert isinstance(s, annmodel.SomeString)
assert s.no_nul
def test_base_iter(self):
class A(object):
def __iter__(self):
return self
def fn():
return iter(A())
a = self.RPythonAnnotator()
s = a.build_types(fn, [])
assert isinstance(s, annmodel.SomeInstance)
assert s.classdef.name.endswith('.A')
def test_iter_next(self):
class A(object):
def __iter__(self):
return self
def next(self):
return 1
def fn():
s = 0
for x in A():
s += x
return s
a = self.RPythonAnnotator()
s = a.build_types(fn, [])
assert len(a.translator.graphs) == 3 # fn, __iter__, next
assert isinstance(s, annmodel.SomeInteger)
def test_next_function(self):
def fn(n):
x = [0, 1, n]
i = iter(x)
return next(i) + next(i)
a = self.RPythonAnnotator()
s = a.build_types(fn, [int])
assert isinstance(s, annmodel.SomeInteger)
def test_instance_getitem(self):
class A(object):
def __getitem__(self, i):
return i * i
def fn(i):
a = A()
return a[i]
a = self.RPythonAnnotator()
s = a.build_types(fn, [int])
assert len(a.translator.graphs) == 2 # fn, __getitem__
assert isinstance(s, annmodel.SomeInteger)
def test_instance_setitem(self):
class A(object):
def __setitem__(self, i, v):
self.value = i * v
def fn(i, v):
a = A()
a[i] = v
return a.value
a = self.RPythonAnnotator()
s = a.build_types(fn, [int, int])
assert len(a.translator.graphs) == 2 # fn, __setitem__
assert isinstance(s, annmodel.SomeInteger)
def test_instance_getslice(self):
class A(object):
def __getslice__(self, stop, start):
return "Test"[stop:start]
def fn():
a = A()
return a[0:2]
a = self.RPythonAnnotator()
s = a.build_types(fn, [])
assert len(a.translator.graphs) == 2 # fn, __getslice__
assert isinstance(s, annmodel.SomeString)
def test_instance_setslice(self):
class A(object):
def __setslice__(self, stop, start, value):
self.value = value
def fn():
a = A()
a[0:2] = '00'
return a.value
a = self.RPythonAnnotator()
s = a.build_types(fn, [])
assert len(a.translator.graphs) == 2 # fn, __setslice__
assert isinstance(s, annmodel.SomeString)
def test_instance_len(self):
class A(object):
def __len__(self):
return 0
def fn():
a = A()
return len(a)
a = self.RPythonAnnotator()
s = a.build_types(fn, [])
assert len(a.translator.graphs) == 2 # fn, __len__
assert isinstance(s, annmodel.SomeInteger)
def test_reversed(self):
def fn(n):
for elem in reversed([1, 2, 3, 4, 5]):
return elem
return n
a = self.RPythonAnnotator()
s = a.build_types(fn, [int])
assert isinstance(s, annmodel.SomeInteger)
def test_no_attr_on_common_exception_classes(self):
for cls in [ValueError, Exception]:
def fn():
e = cls()
e.foo = "bar"
a = self.RPythonAnnotator()
with py.test.raises(NoSuchAttrError):
a.build_types(fn, [])
def test_lower_char(self):
def fn(c):
return c.lower()
a = self.RPythonAnnotator()
s = a.build_types(fn, [annmodel.SomeChar()])
assert s == annmodel.SomeChar()
def test_isinstance_double_const(self):
class X(object):
def _freeze_(self):
return True
x = X()
def f(i):
if i:
x1 = x
else:
x1 = None
print "hello" # this is to force the merge of blocks
return isinstance(x1, X)
a = self.RPythonAnnotator()
s = a.build_types(f, [annmodel.SomeInteger()])
assert isinstance(s, annmodel.SomeBool)
def test_object_init(self):
class A(object):
pass
class B(A):
def __init__(self):
A.__init__(self)
def f():
B()
a = self.RPythonAnnotator()
a.build_types(f, []) # assert did not explode
def test_bytearray(self):
def f():
return bytearray("xyz")
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeByteArray)
assert not s.is_constant() # never a constant!
def test_bytearray_add(self):
def f(a):
return a + bytearray("xyz")
a = self.RPythonAnnotator()
assert isinstance(a.build_types(f, [annmodel.SomeByteArray()]),
annmodel.SomeByteArray)
a = self.RPythonAnnotator()
assert isinstance(a.build_types(f, [str]),
annmodel.SomeByteArray)
a = self.RPythonAnnotator()
assert isinstance(a.build_types(f, [annmodel.SomeChar()]),
annmodel.SomeByteArray)
def test_bytearray_setitem_getitem(self):
def f(b, i, c):
b[i] = c
return b[i + 1]
a = self.RPythonAnnotator()
assert isinstance(a.build_types(f, [annmodel.SomeByteArray(),
int, int]),
annmodel.SomeInteger)
def test_constant_startswith_endswith(self):
def f():
return "abc".startswith("ab") and "abc".endswith("bc")
a = self.RPythonAnnotator()
assert a.build_types(f, []).const is True
def test_specific_attributes(self):
class A(object):
pass
class B(A):
def __init__(self, x):
assert x >= 0
self.x = x
def fn(i):
if i % 2:
a = A()
else:
a = B(3)
if i % 3:
a.x = -3
if isinstance(a, B):
return a.x
return 0
a = self.RPythonAnnotator()
assert not a.build_types(fn, [int]).nonneg
def test_unionerror_attrs(self):
def f(x):
if x < 10:
return 1
else:
return "bbb"
a = self.RPythonAnnotator()
with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
the_exc = exc.value
s_objs = set([type(the_exc.s_obj1), type(the_exc.s_obj2)])
assert s_objs == set([annmodel.SomeInteger, annmodel.SomeString])
def test_unionerror_tuple_size(self):
def f(x):
if x < 10:
return (1, )
else:
return (1, 2)
a = self.RPythonAnnotator()
with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
assert "RPython cannot unify tuples of different length: 2 versus 1" in exc.value.msg
def test_unionerror_signedness(self):
def f(x):
if x < 10:
return r_uint(99)
else:
return -1
a = self.RPythonAnnotator()
with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
assert ("RPython cannot prove that these integers are of the "
"same signedness" in exc.value.msg)
def test_unionerror_instance(self):
class A(object): pass
class B(object): pass
def f(x):
if x < 10:
return A()
else:
return B()
a = self.RPythonAnnotator()
with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
assert ("RPython cannot unify instances with no common base class"
in exc.value.msg)
def test_unionerror_iters(self):
def f(x):
d = { 1 : "a", 2 : "b" }
if x < 10:
return d.iterkeys()
else:
return d.itervalues()
a = self.RPythonAnnotator()
with py.test.raises(UnionError) as exc:
a.build_types(f, [int])
assert ("RPython cannot unify incompatible iterator variants" in
exc.value.msg)
def test_variable_getattr(self):
class A(object): pass
def f(y):
a = A()
return getattr(a, y)
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError) as exc:
a.build_types(f, [str])
assert ("variable argument to getattr" in exc.value.msg)
def test_bad_call(self):
def f(x):
return x()
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError) as exc:
a.build_types(f, [str])
assert ("Cannot prove that the object is callable" in exc.value.msg)
def test_UnionError_on_PBC(self):
l = ['a', 1]
def f(x):
l.append(x)
a = self.RPythonAnnotator()
with py.test.raises(UnionError) as excinfo:
a.build_types(f, [int])
assert 'Happened at file' in excinfo.value.source
assert 'Known variable annotations:' in excinfo.value.source
def test_str_format_error(self):
def f(s, x):
return s.format(x)
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError) as exc:
a.build_types(f, [str, str])
assert ("format() is not RPython" in exc.value.msg)
def test_prebuilt_ordered_dict(self):
d = OrderedDict([("aa", 1)])
def f():
return d
a = self.RPythonAnnotator()
assert isinstance(a.build_types(f, []), annmodel.SomeOrderedDict)
def test_enumerate_none(self):
# enumerate(None) can occur as an intermediate step during a full
# annotation, because the None will be generalized later to
# None-or-list for example
def f(flag):
if flag:
x = None
else:
x = [42]
return enumerate(x).next()
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeTuple)
assert s.items[1].const == 42
def test_unpack_none_gets_a_blocked_block(self):
def f(x):
a, b = x
a = self.RPythonAnnotator()
py.test.raises(AnnotatorError,
a.build_types, f, [annmodel.s_None])
def test_class___name__(self):
class Abc(object):
pass
def f():
return Abc().__class__.__name__
a = self.RPythonAnnotator()
s = a.build_types(f, [])
assert isinstance(s, annmodel.SomeString)
def test_isinstance_str_1(self):
def g():
pass
def f(n):
if n > 5:
s = "foo"
else:
s = None
g()
return isinstance(s, str)
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeBool)
assert not s.is_constant()
def test_isinstance_str_2(self):
def g():
pass
def f(n):
if n > 5:
s = "foo"
else:
s = None
g()
if isinstance(s, str):
return s
return ""
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeString)
assert not s.can_be_none()
def test_property_getter(self):
class O1(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
def f(n):
o = O1(n)
return o.x + getattr(o, 'x')
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
assert isinstance(s, annmodel.SomeInteger)
op = list(graphof(a, f).iterblocks())[0].operations
i = 0
c = 0
while i < len(op):
if op[i].opname == 'getattr':
c += 1
assert op[i].args[1].value == 'x__getter__'
i += 1
assert i < len(op) and op[i].opname == 'simple_call' and \
op[i].args[0] == op[i - 1].result
i += 1
assert c == 2
def test_property_setter(self):
class O2(object):
def __init__(self):
self._x = 0
def set_x(self, v):
self._x = v
x = property(fset=set_x)
def f(n):
o = O2()
o.x = n
setattr(o, 'x', n)
a = self.RPythonAnnotator()
s = a.build_types(f, [int])
op = list(graphof(a, f).iterblocks())[0].operations
i = 0
c = 0
while i < len(op):
if op[i].opname == 'getattr':
c += 1
assert op[i].args[1].value == 'x__setter__'
i += 1
assert i < len(op) and op[i].opname == 'simple_call' and \
op[i].args[0] == op[i - 1].result and len(op[i].args) == 2
i += 1
assert c == 2
def test_property_unionerr(self):
class O1(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
class O2(O1):
def set_x(self, v):
self._x = v
x = property(fset=set_x)
def f1(n):
o = O2(n)
return o.x
def f2(n):
o = O2(n)
o.x = 20
a = self.RPythonAnnotator()
with py.test.raises(UnionError) as exc:
a.build_types(f1, [int])
a = self.RPythonAnnotator()
with py.test.raises(UnionError) as exc:
a.build_types(f2, [int])
@py.test.mark.xfail(reason="May produce garbage annotations instead of "
"raising AnnotatorError, depending on annotation order")
def test_property_union_2(self):
class Base(object):
pass
class A(Base):
def __init__(self):
pass
@property
def x(self):
return 42
class B(Base):
def __init__(self, x):
self.x = x
def f(n):
if n < 0:
obj = A()
else:
obj = B(n)
return obj.x
a = self.RPythonAnnotator()
# Ideally, this should translate to something sensible,
# but for now, AnnotatorError is better than silently mistranslating.
with py.test.raises(AnnotatorError):
a.build_types(f, [int])
@py.test.mark.xfail(reason="May produce garbage annotations instead of "
"raising AnnotatorError, depending on annotation order")
def test_property_union_3(self):
class Base(object):
pass
class A(Base):
@property
def x(self):
return 42
class B(Base):
x = 43
def f(n):
if n < 0:
obj = A()
else:
obj = B()
return obj.x
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [int])
def test_dict_can_be_none_ordering_issue(self):
def g(d):
return 42 in d
def f(n):
g(None)
g({})
a = self.RPythonAnnotator()
a.build_types(f, [int])
def test_numbers_dont_have_len(self):
def f(x):
return len(x)
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [int])
with py.test.raises(AnnotatorError):
a.build_types(f, [float])
def test_numbers_dont_contain(self):
def f(x):
return 1 in x
a = self.RPythonAnnotator()
with py.test.raises(AnnotatorError):
a.build_types(f, [int])
with py.test.raises(AnnotatorError):
a.build_types(f, [float])
def test_Ellipsis_not_rpython(self):
def f():
return Ellipsis
a = self.RPythonAnnotator()
e = py.test.raises(Exception, a.build_types, f, [])
assert str(e.value) == "Don't know how to represent Ellipsis"
def test_must_be_light_finalizer(self):
from rpython.rlib import rgc
@rgc.must_be_light_finalizer
class A(object):
pass
class B(A):
def __del__(self):
pass
class C(A):
@rgc.must_be_light_finalizer
def __del__(self):
pass
class D(object):
def __del__(self):
pass
def fb():
B()
def fc():
C()
def fd():
D()
a = self.RPythonAnnotator()
a.build_types(fc, [])
a.build_types(fd, [])
py.test.raises(AnnotatorError, a.build_types, fb, [])
def test_annotate_generator_with_unreachable_yields(self):
def f(n):
if n < 0:
yield 42
yield n
yield n
def main(n):
for x in f(abs(n)):
pass
#
a = self.RPythonAnnotator()
a.build_types(main, [int])
def test_string_mod_nonconstant(self):
def f(x):
return x % 5
a = self.RPythonAnnotator()
e = py.test.raises(AnnotatorError, a.build_types, f, [str])
assert ('string formatting requires a constant string/unicode'
in str(e.value))
def g(n):
return [0, 1, 2, n]
def f_calls_g(n):
total = 0
lst = g(n)
i = 0
while i < len(lst):
total += i
i += 1
return total
constant_unsigned_five = r_uint(5)
class Freezing:
def _freeze_(self):
return True
|