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
|
/*
* simplecpp - A simple and high-fidelity C/C++ preprocessor library
* Copyright (C) 2016-2023 simplecpp team
*/
#if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
#define SIMPLECPP_WINDOWS
#define NOMINMAX
#endif
#include "simplecpp.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <climits>
#include <cstddef> // IWYU pragma: keep
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <exception>
#include <fstream>
#include <iostream>
#include <istream>
#include <limits>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#if __cplusplus >= 201103L
#ifdef SIMPLECPP_WINDOWS
#include <mutex>
#endif
#include <unordered_map>
#endif
#include <utility>
#include <vector>
#ifdef SIMPLECPP_WINDOWS
#include <windows.h>
#undef ERROR
#endif
#if __cplusplus >= 201103L
#define OVERRIDE override
#define EXPLICIT explicit
#else
#define OVERRIDE
#define EXPLICIT
#endif
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#define nullptr NULL
#endif
static bool isHex(const std::string &s)
{
return s.size()>2 && (s.compare(0,2,"0x")==0 || s.compare(0,2,"0X")==0);
}
static bool isOct(const std::string &s)
{
return s.size()>1 && (s[0]=='0') && (s[1] >= '0') && (s[1] < '8');
}
// TODO: added an undercore since this conflicts with a function of the same name in utils.h from Cppcheck source when building Cppcheck with MSBuild
static bool isStringLiteral_(const std::string &s)
{
return s.size() > 1 && (s[0]=='\"') && (*s.rbegin()=='\"');
}
// TODO: added an undercore since this conflicts with a function of the same name in utils.h from Cppcheck source when building Cppcheck with MSBuild
static bool isCharLiteral_(const std::string &s)
{
// char literal patterns can include 'a', '\t', '\000', '\xff', 'abcd', and maybe ''
// This only checks for the surrounding '' but doesn't parse the content.
return s.size() > 1 && (s[0]=='\'') && (*s.rbegin()=='\'');
}
static const simplecpp::TokenString DEFINE("define");
static const simplecpp::TokenString UNDEF("undef");
static const simplecpp::TokenString INCLUDE("include");
static const simplecpp::TokenString ERROR("error");
static const simplecpp::TokenString WARNING("warning");
static const simplecpp::TokenString IF("if");
static const simplecpp::TokenString IFDEF("ifdef");
static const simplecpp::TokenString IFNDEF("ifndef");
static const simplecpp::TokenString DEFINED("defined");
static const simplecpp::TokenString ELSE("else");
static const simplecpp::TokenString ELIF("elif");
static const simplecpp::TokenString ENDIF("endif");
static const simplecpp::TokenString PRAGMA("pragma");
static const simplecpp::TokenString ONCE("once");
static const simplecpp::TokenString HAS_INCLUDE("__has_include");
template<class T> static std::string toString(T t)
{
// NOLINTNEXTLINE(misc-const-correctness) - false positive
std::ostringstream ostr;
ostr << t;
return ostr.str();
}
#ifdef SIMPLECPP_DEBUG_MACRO_EXPANSION
static std::string locstring(const simplecpp::Location &loc)
{
std::ostringstream ostr;
ostr << '[' << loc.file() << ':' << loc.line << ':' << loc.col << ']';
return ostr.str();
}
#endif
static long long stringToLL(const std::string &s)
{
long long ret;
const bool hex = isHex(s);
const bool oct = isOct(s);
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
if (hex)
istr >> std::hex;
else if (oct)
istr >> std::oct;
istr >> ret;
return ret;
}
static unsigned long long stringToULL(const std::string &s)
{
unsigned long long ret;
const bool hex = isHex(s);
const bool oct = isOct(s);
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
if (hex)
istr >> std::hex;
else if (oct)
istr >> std::oct;
istr >> ret;
return ret;
}
static bool endsWith(const std::string &s, const std::string &e)
{
return (s.size() >= e.size()) && std::equal(e.rbegin(), e.rend(), s.rbegin());
}
static bool sameline(const simplecpp::Token *tok1, const simplecpp::Token *tok2)
{
return tok1 && tok2 && tok1->location.sameline(tok2->location);
}
static bool isAlternativeBinaryOp(const simplecpp::Token *tok, const std::string &alt)
{
return (tok->name &&
tok->str() == alt &&
tok->previous &&
tok->next &&
(tok->previous->number || tok->previous->name || tok->previous->op == ')') &&
(tok->next->number || tok->next->name || tok->next->op == '('));
}
static bool isAlternativeUnaryOp(const simplecpp::Token *tok, const std::string &alt)
{
return ((tok->name && tok->str() == alt) &&
(!tok->previous || tok->previous->op == '(') &&
(tok->next && (tok->next->name || tok->next->number)));
}
static std::string replaceAll(std::string s, const std::string& from, const std::string& to)
{
for (size_t pos = s.find(from); pos != std::string::npos; pos = s.find(from, pos + to.size()))
s.replace(pos, from.size(), to);
return s;
}
const std::string simplecpp::Location::emptyFileName;
void simplecpp::Location::adjust(const std::string &str)
{
if (strpbrk(str.c_str(), "\r\n") == nullptr) {
col += str.size();
return;
}
for (std::size_t i = 0U; i < str.size(); ++i) {
col++;
if (str[i] == '\n' || str[i] == '\r') {
col = 1;
line++;
if (str[i] == '\r' && (i+1)<str.size() && str[i+1]=='\n')
++i;
}
}
}
bool simplecpp::Token::isOneOf(const char ops[]) const
{
return (op != '\0') && (std::strchr(ops, op) != nullptr);
}
bool simplecpp::Token::startsWithOneOf(const char c[]) const
{
return std::strchr(c, string[0]) != nullptr;
}
bool simplecpp::Token::endsWithOneOf(const char c[]) const
{
return std::strchr(c, string[string.size() - 1U]) != nullptr;
}
void simplecpp::Token::printAll() const
{
const Token *tok = this;
while (tok->previous)
tok = tok->previous;
for (; tok; tok = tok->next) {
if (tok->previous) {
std::cout << (sameline(tok, tok->previous) ? ' ' : '\n');
}
std::cout << tok->str();
}
std::cout << std::endl;
}
void simplecpp::Token::printOut() const
{
for (const Token *tok = this; tok; tok = tok->next) {
if (tok != this) {
std::cout << (sameline(tok, tok->previous) ? ' ' : '\n');
}
std::cout << tok->str();
}
std::cout << std::endl;
}
// cppcheck-suppress noConstructor - we call init() in the inherited to initialize the private members
class simplecpp::TokenList::Stream {
public:
virtual ~Stream() {}
virtual int get() = 0;
virtual int peek() = 0;
virtual void unget() = 0;
virtual bool good() = 0;
unsigned char readChar() {
unsigned char ch = static_cast<unsigned char>(get());
// For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
// character is non-ASCII character then replace it with 0xff
if (isUtf16) {
const unsigned char ch2 = static_cast<unsigned char>(get());
const int ch16 = makeUtf16Char(ch, ch2);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16));
}
// Handling of newlines..
if (ch == '\r') {
ch = '\n';
int ch2 = get();
if (isUtf16) {
const int c2 = get();
ch2 = makeUtf16Char(ch2, c2);
}
if (ch2 != '\n')
ungetChar();
}
return ch;
}
unsigned char peekChar() {
unsigned char ch = static_cast<unsigned char>(peek());
// For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
// character is non-ASCII character then replace it with 0xff
if (isUtf16) {
(void)get();
const unsigned char ch2 = static_cast<unsigned char>(peek());
unget();
const int ch16 = makeUtf16Char(ch, ch2);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16));
}
// Handling of newlines..
if (ch == '\r')
ch = '\n';
return ch;
}
void ungetChar() {
unget();
if (isUtf16)
unget();
}
protected:
void init() {
// initialize since we use peek() in getAndSkipBOM()
isUtf16 = false;
bom = getAndSkipBOM();
isUtf16 = (bom == 0xfeff || bom == 0xfffe);
}
private:
inline int makeUtf16Char(const unsigned char ch, const unsigned char ch2) const {
return (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
}
unsigned short getAndSkipBOM() {
const int ch1 = peek();
// The UTF-16 BOM is 0xfffe or 0xfeff.
if (ch1 >= 0xfe) {
(void)get();
const unsigned short byte = (static_cast<unsigned char>(ch1) << 8);
if (peek() >= 0xfe)
return byte | static_cast<unsigned char>(get());
unget();
return 0;
}
// Skip UTF-8 BOM 0xefbbbf
if (ch1 == 0xef) {
(void)get();
if (peek() == 0xbb) {
(void)get();
if (peek() == 0xbf) {
(void)get();
return 0;
}
unget();
}
unget();
}
return 0;
}
unsigned short bom;
protected:
bool isUtf16;
};
class StdIStream : public simplecpp::TokenList::Stream {
public:
// cppcheck-suppress uninitDerivedMemberVar - we call Stream::init() to initialize the private members
EXPLICIT StdIStream(std::istream &istr)
: istr(istr) {
assert(istr.good());
init();
}
virtual int get() OVERRIDE {
return istr.get();
}
virtual int peek() OVERRIDE {
return istr.peek();
}
virtual void unget() OVERRIDE {
istr.unget();
}
virtual bool good() OVERRIDE {
return istr.good();
}
private:
std::istream &istr;
};
class StdCharBufStream : public simplecpp::TokenList::Stream {
public:
// cppcheck-suppress uninitDerivedMemberVar - we call Stream::init() to initialize the private members
StdCharBufStream(const unsigned char* str, std::size_t size)
: str(str)
, size(size)
, pos(0)
, lastStatus(0) {
init();
}
virtual int get() OVERRIDE {
if (pos >= size)
return lastStatus = EOF;
return str[pos++];
}
virtual int peek() OVERRIDE {
if (pos >= size)
return lastStatus = EOF;
return str[pos];
}
virtual void unget() OVERRIDE {
--pos;
}
virtual bool good() OVERRIDE {
return lastStatus != EOF;
}
private:
const unsigned char *str;
const std::size_t size;
std::size_t pos;
int lastStatus;
};
class FileStream : public simplecpp::TokenList::Stream {
public:
// cppcheck-suppress uninitDerivedMemberVar - we call Stream::init() to initialize the private members
EXPLICIT FileStream(const std::string &filename, std::vector<std::string> &files)
: file(fopen(filename.c_str(), "rb"))
, lastCh(0)
, lastStatus(0) {
if (!file) {
files.push_back(filename);
throw simplecpp::Output(files, simplecpp::Output::FILE_NOT_FOUND, "File is missing: " + filename);
}
init();
}
~FileStream() OVERRIDE {
fclose(file);
file = nullptr;
}
virtual int get() OVERRIDE {
lastStatus = lastCh = fgetc(file);
return lastCh;
}
virtual int peek() OVERRIDE{
// keep lastCh intact
const int ch = fgetc(file);
unget_internal(ch);
return ch;
}
virtual void unget() OVERRIDE {
unget_internal(lastCh);
}
virtual bool good() OVERRIDE {
return lastStatus != EOF;
}
private:
void unget_internal(int ch) {
if (isUtf16) {
// TODO: use ungetc() as well
// UTF-16 has subsequent unget() calls
fseek(file, -1, SEEK_CUR);
} else
ungetc(ch, file);
}
FileStream(const FileStream&);
FileStream &operator=(const FileStream&);
FILE *file;
int lastCh;
int lastStatus;
};
simplecpp::TokenList::TokenList(std::vector<std::string> &filenames) : frontToken(nullptr), backToken(nullptr), files(filenames) {}
simplecpp::TokenList::TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
StdIStream stream(istr);
readfile(stream,filename,outputList);
}
simplecpp::TokenList::TokenList(const unsigned char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
StdCharBufStream stream(data, size);
readfile(stream,filename,outputList);
}
simplecpp::TokenList::TokenList(const char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
StdCharBufStream stream(reinterpret_cast<const unsigned char*>(data), size);
readfile(stream,filename,outputList);
}
simplecpp::TokenList::TokenList(const std::string &filename, std::vector<std::string> &filenames, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
try {
FileStream stream(filename, filenames);
readfile(stream,filename,outputList);
} catch (const simplecpp::Output & e) { // TODO handle extra type of errors
outputList->push_back(e);
}
}
simplecpp::TokenList::TokenList(const TokenList &other) : frontToken(nullptr), backToken(nullptr), files(other.files)
{
*this = other;
}
#if __cplusplus >= 201103L
simplecpp::TokenList::TokenList(TokenList &&other) : frontToken(nullptr), backToken(nullptr), files(other.files)
{
*this = std::move(other);
}
#endif
simplecpp::TokenList::~TokenList()
{
clear();
}
simplecpp::TokenList &simplecpp::TokenList::operator=(const TokenList &other)
{
if (this != &other) {
clear();
files = other.files;
for (const Token *tok = other.cfront(); tok; tok = tok->next)
push_back(new Token(*tok));
sizeOfType = other.sizeOfType;
}
return *this;
}
#if __cplusplus >= 201103L
simplecpp::TokenList &simplecpp::TokenList::operator=(TokenList &&other)
{
if (this != &other) {
clear();
frontToken = other.frontToken;
other.frontToken = nullptr;
backToken = other.backToken;
other.backToken = nullptr;
files = other.files;
sizeOfType = std::move(other.sizeOfType);
}
return *this;
}
#endif
void simplecpp::TokenList::clear()
{
backToken = nullptr;
while (frontToken) {
Token * const next = frontToken->next;
delete frontToken;
frontToken = next;
}
sizeOfType.clear();
}
void simplecpp::TokenList::push_back(Token *tok)
{
if (!frontToken)
frontToken = tok;
else
backToken->next = tok;
tok->previous = backToken;
backToken = tok;
}
void simplecpp::TokenList::dump() const
{
std::cout << stringify() << std::endl;
}
std::string simplecpp::TokenList::stringify() const
{
std::ostringstream ret;
Location loc(files);
for (const Token *tok = cfront(); tok; tok = tok->next) {
if (tok->location.line < loc.line || tok->location.fileIndex != loc.fileIndex) {
ret << "\n#line " << tok->location.line << " \"" << tok->location.file() << "\"\n";
loc = tok->location;
}
while (tok->location.line > loc.line) {
ret << '\n';
loc.line++;
}
if (sameline(tok->previous, tok))
ret << ' ';
ret << tok->str();
loc.adjust(tok->str());
}
return ret.str();
}
static bool isNameChar(unsigned char ch)
{
return std::isalnum(ch) || ch == '_' || ch == '$';
}
static std::string escapeString(const std::string &str)
{
std::ostringstream ostr;
ostr << '\"';
for (std::size_t i = 1U; i < str.size() - 1; ++i) {
const char c = str[i];
if (c == '\\' || c == '\"' || c == '\'')
ostr << '\\';
ostr << c;
}
ostr << '\"';
return ostr.str();
}
static void portabilityBackslash(simplecpp::OutputList *outputList, const std::vector<std::string> &files, const simplecpp::Location &location)
{
if (!outputList)
return;
simplecpp::Output err(files);
err.type = simplecpp::Output::PORTABILITY_BACKSLASH;
err.location = location;
err.msg = "Combination 'backslash space newline' is not portable.";
outputList->push_back(err);
}
static bool isStringLiteralPrefix(const std::string &str)
{
return str == "u" || str == "U" || str == "L" || str == "u8" ||
str == "R" || str == "uR" || str == "UR" || str == "LR" || str == "u8R";
}
void simplecpp::TokenList::lineDirective(unsigned int fileIndex, unsigned int line, Location *location)
{
if (fileIndex != location->fileIndex || line >= location->line) {
location->fileIndex = fileIndex;
location->line = line;
return;
}
if (line + 2 >= location->line) {
location->line = line;
while (cback()->op != '#')
deleteToken(back());
deleteToken(back());
return;
}
}
static const std::string COMMENT_END("*/");
void simplecpp::TokenList::readfile(Stream &stream, const std::string &filename, OutputList *outputList)
{
std::stack<simplecpp::Location> loc;
unsigned int multiline = 0U;
const Token *oldLastToken = nullptr;
Location location(files);
location.fileIndex = fileIndex(filename);
location.line = 1U;
location.col = 1U;
while (stream.good()) {
unsigned char ch = stream.readChar();
if (!stream.good())
break;
if (ch >= 0x80) {
if (outputList) {
simplecpp::Output err(files);
err.type = simplecpp::Output::UNHANDLED_CHAR_ERROR;
err.location = location;
std::ostringstream s;
s << static_cast<int>(ch);
err.msg = "The code contains unhandled character(s) (character code=" + s.str() + "). Neither unicode nor extended ascii is supported.";
outputList->push_back(err);
}
clear();
return;
}
if (ch == '\n') {
if (cback() && cback()->op == '\\') {
if (location.col > cback()->location.col + 1U)
portabilityBackslash(outputList, files, cback()->location);
++multiline;
deleteToken(back());
} else {
location.line += multiline + 1;
multiline = 0U;
}
if (!multiline)
location.col = 1;
if (oldLastToken != cback()) {
oldLastToken = cback();
if (!isLastLinePreprocessor())
continue;
const std::string lastline(lastLine());
if (lastline == "# file %str%") {
const Token *strtok = cback();
while (strtok->comment)
strtok = strtok->previous;
loc.push(location);
location.fileIndex = fileIndex(strtok->str().substr(1U, strtok->str().size() - 2U));
location.line = 1U;
} else if (lastline == "# line %num%") {
const Token *numtok = cback();
while (numtok->comment)
numtok = numtok->previous;
lineDirective(location.fileIndex, std::atol(numtok->str().c_str()), &location);
} else if (lastline == "# %num% %str%" || lastline == "# line %num% %str%") {
const Token *strtok = cback();
while (strtok->comment)
strtok = strtok->previous;
const Token *numtok = strtok->previous;
while (numtok->comment)
numtok = numtok->previous;
lineDirective(fileIndex(replaceAll(strtok->str().substr(1U, strtok->str().size() - 2U),"\\\\","\\")),
std::atol(numtok->str().c_str()), &location);
}
// #endfile
else if (lastline == "# endfile" && !loc.empty()) {
location = loc.top();
loc.pop();
}
}
continue;
}
if (ch <= ' ') {
location.col++;
continue;
}
TokenString currentToken;
if (cback() && cback()->location.line == location.line && cback()->previous && cback()->previous->op == '#') {
const Token* const llTok = lastLineTok();
if (llTok && llTok->op == '#' && llTok->next && (llTok->next->str() == "error" || llTok->next->str() == "warning")) {
char prev = ' ';
while (stream.good() && (prev == '\\' || (ch != '\r' && ch != '\n'))) {
currentToken += ch;
prev = ch;
ch = stream.readChar();
}
stream.ungetChar();
push_back(new Token(currentToken, location));
location.adjust(currentToken);
continue;
}
}
// number or name
if (isNameChar(ch)) {
const bool num = std::isdigit(ch);
while (stream.good() && isNameChar(ch)) {
currentToken += ch;
ch = stream.readChar();
if (num && ch=='\'' && isNameChar(stream.peekChar()))
ch = stream.readChar();
}
stream.ungetChar();
}
// comment
else if (ch == '/' && stream.peekChar() == '/') {
while (stream.good() && ch != '\r' && ch != '\n') {
currentToken += ch;
ch = stream.readChar();
}
const std::string::size_type pos = currentToken.find_last_not_of(" \t");
if (pos < currentToken.size() - 1U && currentToken[pos] == '\\')
portabilityBackslash(outputList, files, location);
if (currentToken[currentToken.size() - 1U] == '\\') {
++multiline;
currentToken.erase(currentToken.size() - 1U);
} else {
stream.ungetChar();
}
}
// comment
else if (ch == '/' && stream.peekChar() == '*') {
currentToken = "/*";
(void)stream.readChar();
ch = stream.readChar();
while (stream.good()) {
currentToken += ch;
if (currentToken.size() >= 4U && endsWith(currentToken, COMMENT_END))
break;
ch = stream.readChar();
}
// multiline..
std::string::size_type pos = 0;
while ((pos = currentToken.find("\\\n",pos)) != std::string::npos) {
currentToken.erase(pos,2);
++multiline;
}
if (multiline || isLastLinePreprocessor()) {
pos = 0;
while ((pos = currentToken.find('\n',pos)) != std::string::npos) {
currentToken.erase(pos,1);
++multiline;
}
}
}
// string / char literal
else if (ch == '\"' || ch == '\'') {
std::string prefix;
if (cback() && cback()->name && isStringLiteralPrefix(cback()->str()) &&
((cback()->location.col + cback()->str().size()) == location.col) &&
(cback()->location.line == location.line)) {
prefix = cback()->str();
}
// C++11 raw string literal
if (ch == '\"' && !prefix.empty() && *cback()->str().rbegin() == 'R') {
std::string delim;
currentToken = ch;
prefix.resize(prefix.size() - 1);
ch = stream.readChar();
while (stream.good() && ch != '(' && ch != '\n') {
delim += ch;
ch = stream.readChar();
}
if (!stream.good() || ch == '\n') {
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = "Invalid newline in raw string delimiter.";
outputList->push_back(err);
}
return;
}
const std::string endOfRawString(')' + delim + currentToken);
while (stream.good() && !(endsWith(currentToken, endOfRawString) && currentToken.size() > 1))
currentToken += stream.readChar();
if (!endsWith(currentToken, endOfRawString)) {
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = "Raw string missing terminating delimiter.";
outputList->push_back(err);
}
return;
}
currentToken.erase(currentToken.size() - endOfRawString.size(), endOfRawString.size() - 1U);
currentToken = escapeString(currentToken);
currentToken.insert(0, prefix);
back()->setstr(currentToken);
location.adjust(currentToken);
if (currentToken.find_first_of("\r\n") == std::string::npos)
location.col += 2 + 2 * delim.size();
else
location.col += 1 + delim.size();
continue;
}
currentToken = readUntil(stream,location,ch,ch,outputList);
if (currentToken.size() < 2U)
// Error is reported by readUntil()
return;
std::string s = currentToken;
std::string::size_type pos;
int newlines = 0;
while ((pos = s.find_first_of("\r\n")) != std::string::npos) {
s.erase(pos,1);
newlines++;
}
if (prefix.empty())
push_back(new Token(s, location, std::isspace(stream.peekChar()))); // push string without newlines
else
back()->setstr(prefix + s);
if (newlines > 0) {
const Token * const llTok = lastLineTok();
if (llTok && llTok->op == '#' && llTok->next && (llTok->next->str() == "define" || llTok->next->str() == "pragma") && llTok->next->next) {
multiline += newlines;
location.adjust(s);
continue;
}
}
location.adjust(currentToken);
continue;
}
else {
currentToken += ch;
}
if (*currentToken.begin() == '<') {
const Token * const llTok = lastLineTok();
if (llTok && llTok->op == '#' && llTok->next && llTok->next->str() == "include") {
currentToken = readUntil(stream, location, '<', '>', outputList);
if (currentToken.size() < 2U)
return;
}
}
push_back(new Token(currentToken, location, std::isspace(stream.peekChar())));
if (multiline)
location.col += currentToken.size();
else
location.adjust(currentToken);
}
combineOperators();
}
void simplecpp::TokenList::constFold()
{
while (cfront()) {
// goto last '('
Token *tok = back();
while (tok && tok->op != '(')
tok = tok->previous;
// no '(', goto first token
if (!tok)
tok = front();
// Constant fold expression
constFoldUnaryNotPosNeg(tok);
constFoldMulDivRem(tok);
constFoldAddSub(tok);
constFoldShift(tok);
constFoldComparison(tok);
constFoldBitwise(tok);
constFoldLogicalOp(tok);
constFoldQuestionOp(&tok);
// If there is no '(' we are done with the constant folding
if (tok->op != '(')
break;
if (!tok->next || !tok->next->next || tok->next->next->op != ')')
break;
tok = tok->next;
deleteToken(tok->previous);
deleteToken(tok->next);
}
}
static bool isFloatSuffix(const simplecpp::Token *tok)
{
if (!tok || tok->str().size() != 1U)
return false;
const char c = std::tolower(tok->str()[0]);
return c == 'f' || c == 'l';
}
void simplecpp::TokenList::combineOperators()
{
std::stack<bool> executableScope;
executableScope.push(false);
for (Token *tok = front(); tok; tok = tok->next) {
if (tok->op == '{') {
if (executableScope.top()) {
executableScope.push(true);
continue;
}
const Token *prev = tok->previous;
while (prev && prev->isOneOf(";{}()"))
prev = prev->previous;
executableScope.push(prev && prev->op == ')');
continue;
}
if (tok->op == '}') {
if (executableScope.size() > 1)
executableScope.pop();
continue;
}
if (tok->op == '.') {
// ellipsis ...
if (tok->next && tok->next->op == '.' && tok->next->location.col == (tok->location.col + 1) &&
tok->next->next && tok->next->next->op == '.' && tok->next->next->location.col == (tok->location.col + 2)) {
tok->setstr("...");
deleteToken(tok->next);
deleteToken(tok->next);
continue;
}
// float literals..
if (tok->previous && tok->previous->number && sameline(tok->previous, tok) && tok->previous->str().find_first_of("._") == std::string::npos) {
tok->setstr(tok->previous->str() + '.');
deleteToken(tok->previous);
if (sameline(tok, tok->next) && (isFloatSuffix(tok->next) || (tok->next && tok->next->startsWithOneOf("AaBbCcDdEeFfPp")))) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
if (tok->next && tok->next->number) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
// match: [0-9.]+E [+-] [0-9]+
const char lastChar = tok->str()[tok->str().size() - 1];
if (tok->number && !isOct(tok->str()) &&
((!isHex(tok->str()) && (lastChar == 'E' || lastChar == 'e')) ||
(isHex(tok->str()) && (lastChar == 'P' || lastChar == 'p'))) &&
tok->next && tok->next->isOneOf("+-") && tok->next->next && tok->next->next->number) {
tok->setstr(tok->str() + tok->next->op + tok->next->next->str());
deleteToken(tok->next);
deleteToken(tok->next);
}
if (tok->op == '\0' || !tok->next || tok->next->op == '\0')
continue;
if (!sameline(tok,tok->next))
continue;
if (tok->location.col + 1U != tok->next->location.col)
continue;
if (tok->next->op == '=' && tok->isOneOf("=!<>+-*/%&|^")) {
if (tok->op == '&' && !executableScope.top()) {
// don't combine &= if it is a anonymous reference parameter with default value:
// void f(x&=2)
int indentlevel = 0;
const Token *start = tok;
while (indentlevel >= 0 && start) {
if (start->op == ')')
++indentlevel;
else if (start->op == '(')
--indentlevel;
else if (start->isOneOf(";{}"))
break;
start = start->previous;
}
if (indentlevel == -1 && start) {
const Token * const ftok = start;
bool isFuncDecl = ftok->name;
while (isFuncDecl) {
if (!start->name && start->str() != "::" && start->op != '*' && start->op != '&')
isFuncDecl = false;
if (!start->previous)
break;
if (start->previous->isOneOf(";{}:"))
break;
start = start->previous;
}
isFuncDecl &= start != ftok && start->name;
if (isFuncDecl) {
// TODO: we could loop through the parameters here and check if they are correct.
continue;
}
}
}
tok->setstr(tok->str() + "=");
deleteToken(tok->next);
} else if ((tok->op == '|' || tok->op == '&') && tok->op == tok->next->op) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if (tok->op == ':' && tok->next->op == ':') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if (tok->op == '-' && tok->next->op == '>') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if ((tok->op == '<' || tok->op == '>') && tok->op == tok->next->op) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
if (tok->next && tok->next->op == '=' && tok->next->next && tok->next->next->op != '=') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
} else if ((tok->op == '+' || tok->op == '-') && tok->op == tok->next->op) {
if (tok->location.col + 1U != tok->next->location.col)
continue;
if (tok->previous && tok->previous->number)
continue;
if (tok->next->next && tok->next->next->number)
continue;
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
}
static const std::string COMPL("compl");
static const std::string NOT("not");
void simplecpp::TokenList::constFoldUnaryNotPosNeg(simplecpp::Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
// "not" might be !
if (isAlternativeUnaryOp(tok, NOT))
tok->op = '!';
// "compl" might be ~
else if (isAlternativeUnaryOp(tok, COMPL))
tok->op = '~';
if (tok->op == '!' && tok->next && tok->next->number) {
tok->setstr(tok->next->str() == "0" ? "1" : "0");
deleteToken(tok->next);
} else if (tok->op == '~' && tok->next && tok->next->number) {
tok->setstr(toString(~stringToLL(tok->next->str())));
deleteToken(tok->next);
} else {
if (tok->previous && (tok->previous->number || tok->previous->name))
continue;
if (!tok->next || !tok->next->number)
continue;
switch (tok->op) {
case '+':
tok->setstr(tok->next->str());
deleteToken(tok->next);
break;
case '-':
tok->setstr(tok->op + tok->next->str());
deleteToken(tok->next);
break;
}
}
}
}
void simplecpp::TokenList::constFoldMulDivRem(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->op == '*')
result = (stringToLL(tok->previous->str()) * stringToLL(tok->next->str()));
else if (tok->op == '/' || tok->op == '%') {
const long long rhs = stringToLL(tok->next->str());
if (rhs == 0)
throw std::overflow_error("division/modulo by zero");
const long long lhs = stringToLL(tok->previous->str());
if (rhs == -1 && lhs == std::numeric_limits<long long>::min())
throw std::overflow_error("division overflow");
if (tok->op == '/')
result = (lhs / rhs);
else
result = (lhs % rhs);
} else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldAddSub(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->op == '+')
result = stringToLL(tok->previous->str()) + stringToLL(tok->next->str());
else if (tok->op == '-')
result = stringToLL(tok->previous->str()) - stringToLL(tok->next->str());
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldShift(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->str() == "<<")
result = stringToLL(tok->previous->str()) << stringToLL(tok->next->str());
else if (tok->str() == ">>")
result = stringToLL(tok->previous->str()) >> stringToLL(tok->next->str());
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
static const std::string NOTEQ("not_eq");
void simplecpp::TokenList::constFoldComparison(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (isAlternativeBinaryOp(tok,NOTEQ))
tok->setstr("!=");
if (!tok->startsWithOneOf("<>=!"))
continue;
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
int result;
if (tok->str() == "==")
result = (stringToLL(tok->previous->str()) == stringToLL(tok->next->str()));
else if (tok->str() == "!=")
result = (stringToLL(tok->previous->str()) != stringToLL(tok->next->str()));
else if (tok->str() == ">")
result = (stringToLL(tok->previous->str()) > stringToLL(tok->next->str()));
else if (tok->str() == ">=")
result = (stringToLL(tok->previous->str()) >= stringToLL(tok->next->str()));
else if (tok->str() == "<")
result = (stringToLL(tok->previous->str()) < stringToLL(tok->next->str()));
else if (tok->str() == "<=")
result = (stringToLL(tok->previous->str()) <= stringToLL(tok->next->str()));
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
static const std::string BITAND("bitand");
static const std::string BITOR("bitor");
static const std::string XOR("xor");
void simplecpp::TokenList::constFoldBitwise(Token *tok)
{
Token * const tok1 = tok;
for (const char *op = "&^|"; *op; op++) {
const std::string* alternativeOp;
if (*op == '&')
alternativeOp = &BITAND;
else if (*op == '|')
alternativeOp = &BITOR;
else
alternativeOp = &XOR;
for (tok = tok1; tok && tok->op != ')'; tok = tok->next) {
if (tok->op != *op && !isAlternativeBinaryOp(tok, *alternativeOp))
continue;
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (*op == '&')
result = (stringToLL(tok->previous->str()) & stringToLL(tok->next->str()));
else if (*op == '^')
result = (stringToLL(tok->previous->str()) ^ stringToLL(tok->next->str()));
else /*if (*op == '|')*/
result = (stringToLL(tok->previous->str()) | stringToLL(tok->next->str()));
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
}
static const std::string AND("and");
static const std::string OR("or");
void simplecpp::TokenList::constFoldLogicalOp(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (tok->name) {
if (isAlternativeBinaryOp(tok,AND))
tok->setstr("&&");
else if (isAlternativeBinaryOp(tok,OR))
tok->setstr("||");
}
if (tok->str() != "&&" && tok->str() != "||")
continue;
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
int result;
if (tok->str() == "||")
result = (stringToLL(tok->previous->str()) || stringToLL(tok->next->str()));
else /*if (tok->str() == "&&")*/
result = (stringToLL(tok->previous->str()) && stringToLL(tok->next->str()));
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldQuestionOp(Token **tok1)
{
bool gotoTok1 = false;
for (Token *tok = *tok1; tok && tok->op != ')'; tok = gotoTok1 ? *tok1 : tok->next) {
gotoTok1 = false;
if (tok->str() != "?")
continue;
if (!tok->previous || !tok->next || !tok->next->next)
throw std::runtime_error("invalid expression");
if (!tok->previous->number)
continue;
if (tok->next->next->op != ':')
continue;
Token * const condTok = tok->previous;
Token * const trueTok = tok->next;
Token * const falseTok = trueTok->next->next;
if (!falseTok)
throw std::runtime_error("invalid expression");
if (condTok == *tok1)
*tok1 = (condTok->str() != "0" ? trueTok : falseTok);
deleteToken(condTok->next); // ?
deleteToken(trueTok->next); // :
deleteToken(condTok->str() == "0" ? trueTok : falseTok);
deleteToken(condTok);
gotoTok1 = true;
}
}
void simplecpp::TokenList::removeComments()
{
Token *tok = frontToken;
while (tok) {
Token * const tok1 = tok;
tok = tok->next;
if (tok1->comment)
deleteToken(tok1);
}
}
std::string simplecpp::TokenList::readUntil(Stream &stream, const Location &location, const char start, const char end, OutputList *outputList)
{
std::string ret;
ret += start;
bool backslash = false;
char ch = 0;
while (ch != end && ch != '\r' && ch != '\n' && stream.good()) {
ch = stream.readChar();
if (backslash && ch == '\n') {
ch = 0;
backslash = false;
continue;
}
backslash = false;
ret += ch;
if (ch == '\\') {
bool update_ch = false;
char next = 0;
do {
next = stream.readChar();
if (next == '\r' || next == '\n') {
ret.erase(ret.size()-1U);
backslash = (next == '\r');
update_ch = false;
} else if (next == '\\')
update_ch = !update_ch;
ret += next;
} while (next == '\\');
if (update_ch)
ch = next;
}
}
if (!stream.good() || ch != end) {
clear();
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = std::string("No pair for character (") + start + "). Can't process file. File is either invalid or unicode, which is currently not supported.";
outputList->push_back(err);
}
return "";
}
return ret;
}
std::string simplecpp::TokenList::lastLine(int maxsize) const
{
std::string ret;
int count = 0;
for (const Token *tok = cback(); ; tok = tok->previous) {
if (!sameline(tok, cback())) {
break;
}
if (tok->comment)
continue;
if (++count > maxsize)
return "";
if (!ret.empty())
ret += ' ';
// add tokens in reverse for performance reasons
if (tok->str()[0] == '\"')
ret += "%rts%"; // %str%
else if (tok->number)
ret += "%mun%"; // %num%
else {
ret += tok->str();
std::reverse(ret.end() - tok->str().length(), ret.end());
}
}
std::reverse(ret.begin(), ret.end());
return ret;
}
const simplecpp::Token* simplecpp::TokenList::lastLineTok(int maxsize) const
{
const Token* prevTok = nullptr;
int count = 0;
for (const Token *tok = cback(); ; tok = tok->previous) {
if (!sameline(tok, cback()))
break;
if (tok->comment)
continue;
if (++count > maxsize)
return nullptr;
prevTok = tok;
}
return prevTok;
}
bool simplecpp::TokenList::isLastLinePreprocessor(int maxsize) const
{
const Token * const prevTok = lastLineTok(maxsize);
return prevTok && prevTok->op == '#';
}
unsigned int simplecpp::TokenList::fileIndex(const std::string &filename)
{
for (unsigned int i = 0; i < files.size(); ++i) {
if (files[i] == filename)
return i;
}
files.push_back(filename);
return files.size() - 1U;
}
namespace simplecpp {
class Macro;
#if __cplusplus >= 201103L
using MacroMap = std::unordered_map<TokenString,Macro>;
#else
typedef std::map<TokenString,Macro> MacroMap;
#endif
class Macro {
public:
explicit Macro(std::vector<std::string> &f) : nameTokDef(nullptr), valueToken(nullptr), endToken(nullptr), files(f), tokenListDefine(f), variadic(false), valueDefinedInCode_(false) {}
Macro(const Token *tok, std::vector<std::string> &f) : nameTokDef(nullptr), files(f), tokenListDefine(f), valueDefinedInCode_(true) {
if (sameline(tok->previousSkipComments(), tok))
throw std::runtime_error("bad macro syntax");
if (tok->op != '#')
throw std::runtime_error("bad macro syntax");
const Token * const hashtok = tok;
tok = tok->next;
if (!tok || tok->str() != DEFINE)
throw std::runtime_error("bad macro syntax");
tok = tok->next;
if (!tok || !tok->name || !sameline(hashtok,tok))
throw std::runtime_error("bad macro syntax");
if (!parseDefine(tok))
throw std::runtime_error("bad macro syntax");
}
Macro(const std::string &name, const std::string &value, std::vector<std::string> &f) : nameTokDef(nullptr), files(f), tokenListDefine(f), valueDefinedInCode_(false) {
const std::string def(name + ' ' + value);
StdCharBufStream stream(reinterpret_cast<const unsigned char*>(def.data()), def.size());
tokenListDefine.readfile(stream);
if (!parseDefine(tokenListDefine.cfront()))
throw std::runtime_error("bad macro syntax. macroname=" + name + " value=" + value);
}
Macro(const Macro &other) : nameTokDef(nullptr), files(other.files), tokenListDefine(other.files), valueDefinedInCode_(other.valueDefinedInCode_) {
*this = other;
}
Macro &operator=(const Macro &other) {
if (this != &other) {
files = other.files;
valueDefinedInCode_ = other.valueDefinedInCode_;
if (other.tokenListDefine.empty())
parseDefine(other.nameTokDef);
else {
tokenListDefine = other.tokenListDefine;
parseDefine(tokenListDefine.cfront());
}
usageList = other.usageList;
}
return *this;
}
bool valueDefinedInCode() const {
return valueDefinedInCode_;
}
/**
* Expand macro. This will recursively expand inner macros.
* @param output destination tokenlist
* @param rawtok macro token
* @param macros list of macros
* @param inputFiles the input files
* @return token after macro
* @throw Can throw wrongNumberOfParameters or invalidHashHash
*/
const Token * expand(TokenList * const output,
const Token * rawtok,
const MacroMap ¯os,
std::vector<std::string> &inputFiles) const {
std::set<TokenString> expandedmacros;
#ifdef SIMPLECPP_DEBUG_MACRO_EXPANSION
std::cout << "expand " << name() << " " << locstring(rawtok->location) << std::endl;
#endif
TokenList output2(inputFiles);
if (functionLike() && rawtok->next && rawtok->next->op == '(') {
// Copy macro call to a new tokenlist with no linebreaks
const Token * const rawtok1 = rawtok;
TokenList rawtokens2(inputFiles);
rawtokens2.push_back(new Token(rawtok->str(), rawtok1->location, rawtok->whitespaceahead));
rawtok = rawtok->next;
rawtokens2.push_back(new Token(rawtok->str(), rawtok1->location, rawtok->whitespaceahead));
rawtok = rawtok->next;
int par = 1;
while (rawtok && par > 0) {
if (rawtok->op == '(')
++par;
else if (rawtok->op == ')')
--par;
else if (rawtok->op == '#' && !sameline(rawtok->previous, rawtok))
throw Error(rawtok->location, "it is invalid to use a preprocessor directive as macro parameter");
rawtokens2.push_back(new Token(rawtok->str(), rawtok1->location, rawtok->whitespaceahead));
rawtok = rawtok->next;
}
if (expand(&output2, rawtok1->location, rawtokens2.cfront(), macros, expandedmacros))
rawtok = rawtok1->next;
} else {
rawtok = expand(&output2, rawtok->location, rawtok, macros, expandedmacros);
}
while (output2.cback() && rawtok) {
unsigned int par = 0;
Token* macro2tok = output2.back();
while (macro2tok) {
if (macro2tok->op == '(') {
if (par==0)
break;
--par;
} else if (macro2tok->op == ')')
++par;
macro2tok = macro2tok->previous;
}
if (macro2tok) { // macro2tok->op == '('
macro2tok = macro2tok->previous;
expandedmacros.insert(name());
} else if (rawtok->op == '(')
macro2tok = output2.back();
if (!macro2tok || !macro2tok->name)
break;
if (output2.cfront() != output2.cback() && macro2tok->str() == this->name())
break;
const MacroMap::const_iterator macro = macros.find(macro2tok->str());
if (macro == macros.end() || !macro->second.functionLike())
break;
TokenList rawtokens2(inputFiles);
const Location loc(macro2tok->location);
while (macro2tok) {
Token * const next = macro2tok->next;
rawtokens2.push_back(new Token(macro2tok->str(), loc));
output2.deleteToken(macro2tok);
macro2tok = next;
}
par = (rawtokens2.cfront() != rawtokens2.cback()) ? 1U : 0U;
const Token *rawtok2 = rawtok;
for (; rawtok2; rawtok2 = rawtok2->next) {
rawtokens2.push_back(new Token(rawtok2->str(), loc));
if (rawtok2->op == '(')
++par;
else if (rawtok2->op == ')') {
if (par <= 1U)
break;
--par;
}
}
if (!rawtok2 || par != 1U)
break;
if (macro->second.expand(&output2, rawtok->location, rawtokens2.cfront(), macros, expandedmacros) != nullptr)
break;
rawtok = rawtok2->next;
}
output->takeTokens(output2);
return rawtok;
}
/** macro name */
const TokenString &name() const {
return nameTokDef->str();
}
/** location for macro definition */
const Location &defineLocation() const {
return nameTokDef->location;
}
/** how has this macro been used so far */
const std::list<Location> &usage() const {
return usageList;
}
/** is this a function like macro */
bool functionLike() const {
return nameTokDef->next &&
nameTokDef->next->op == '(' &&
sameline(nameTokDef, nameTokDef->next) &&
nameTokDef->next->location.col == nameTokDef->location.col + nameTokDef->str().size();
}
/** base class for errors */
struct Error {
Error(const Location &loc, const std::string &s) : location(loc), what(s) {}
const Location location;
const std::string what;
};
/** Struct that is thrown when macro is expanded with wrong number of parameters */
struct wrongNumberOfParameters : public Error {
wrongNumberOfParameters(const Location &loc, const std::string ¯oName) : Error(loc, "Wrong number of parameters for macro \'" + macroName + "\'.") {}
};
/** Struct that is thrown when there is invalid ## usage */
struct invalidHashHash : public Error {
static inline std::string format(const std::string ¯oName, const std::string &message) {
return "Invalid ## usage when expanding \'" + macroName + "\': " + message;
}
invalidHashHash(const Location &loc, const std::string ¯oName, const std::string &message)
: Error(loc, format(macroName, message)) { }
static inline invalidHashHash unexpectedToken(const Location &loc, const std::string ¯oName, const Token *tokenA) {
return invalidHashHash(loc, macroName, "Unexpected token '"+ tokenA->str()+"'");
}
static inline invalidHashHash cannotCombine(const Location &loc, const std::string ¯oName, const Token *tokenA, const Token *tokenB) {
return invalidHashHash(loc, macroName, "Combining '"+ tokenA->str()+ "' and '"+ tokenB->str() + "' yields an invalid token.");
}
static inline invalidHashHash unexpectedNewline(const Location &loc, const std::string ¯oName) {
return invalidHashHash(loc, macroName, "Unexpected newline");
}
static inline invalidHashHash universalCharacterUB(const Location &loc, const std::string ¯oName, const Token* tokenA, const std::string& strAB) {
return invalidHashHash(loc, macroName, "Combining '\\"+ tokenA->str()+ "' and '"+ strAB.substr(tokenA->str().size()) + "' yields universal character '\\" + strAB + "'. This is undefined behavior according to C standard chapter 5.1.1.2, paragraph 4.");
}
};
private:
/** Create new token where Token::macro is set for replaced tokens */
Token *newMacroToken(const TokenString &str, const Location &loc, bool replaced, const Token *expandedFromToken=nullptr) const {
Token *tok = new Token(str,loc);
if (replaced)
tok->macro = nameTokDef->str();
if (expandedFromToken)
tok->setExpandedFrom(expandedFromToken, this);
return tok;
}
bool parseDefine(const Token *nametoken) {
nameTokDef = nametoken;
variadic = false;
if (!nameTokDef) {
valueToken = endToken = nullptr;
args.clear();
return false;
}
// function like macro..
if (functionLike()) {
args.clear();
const Token *argtok = nameTokDef->next->next;
while (sameline(nametoken, argtok) && argtok->op != ')') {
if (argtok->str() == "..." &&
argtok->next && argtok->next->op == ')') {
variadic = true;
if (!argtok->previous->name)
args.push_back("__VA_ARGS__");
argtok = argtok->next; // goto ')'
break;
}
if (argtok->op != ',')
args.push_back(argtok->str());
argtok = argtok->next;
}
if (!sameline(nametoken, argtok)) {
endToken = argtok ? argtok->previous : argtok;
valueToken = nullptr;
return false;
}
valueToken = argtok ? argtok->next : nullptr;
} else {
args.clear();
valueToken = nameTokDef->next;
}
if (!sameline(valueToken, nameTokDef))
valueToken = nullptr;
endToken = valueToken;
while (sameline(endToken, nameTokDef))
endToken = endToken->next;
return true;
}
unsigned int getArgNum(const TokenString &str) const {
unsigned int par = 0;
while (par < args.size()) {
if (str == args[par])
return par;
par++;
}
return ~0U;
}
std::vector<const Token *> getMacroParameters(const Token *nameTokInst, bool calledInDefine) const {
if (!nameTokInst->next || nameTokInst->next->op != '(' || !functionLike())
return std::vector<const Token *>();
std::vector<const Token *> parametertokens;
parametertokens.push_back(nameTokInst->next);
unsigned int par = 0U;
for (const Token *tok = nameTokInst->next->next; calledInDefine ? sameline(tok, nameTokInst) : (tok != nullptr); tok = tok->next) {
if (tok->op == '(')
++par;
else if (tok->op == ')') {
if (par == 0U) {
parametertokens.push_back(tok);
break;
}
--par;
} else if (par == 0U && tok->op == ',' && (!variadic || parametertokens.size() < args.size()))
parametertokens.push_back(tok);
}
return parametertokens;
}
const Token *appendTokens(TokenList *tokens,
const Location &rawloc,
const Token * const lpar,
const MacroMap ¯os,
const std::set<TokenString> &expandedmacros,
const std::vector<const Token*> ¶metertokens) const {
if (!lpar || lpar->op != '(')
return nullptr;
unsigned int par = 0;
const Token *tok = lpar;
while (sameline(lpar, tok)) {
if (tok->op == '#' && sameline(tok,tok->next) && tok->next->op == '#' && sameline(tok,tok->next->next)) {
// A##B => AB
tok = expandHashHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens, false);
} else if (tok->op == '#' && sameline(tok, tok->next) && tok->next->op != '#') {
tok = expandHash(tokens, rawloc, tok, expandedmacros, parametertokens);
} else {
if (!expandArg(tokens, tok, rawloc, macros, expandedmacros, parametertokens)) {
tokens->push_back(new Token(*tok));
if (tok->macro.empty() && (par > 0 || tok->str() != "("))
tokens->back()->macro = name();
}
if (tok->op == '(')
++par;
else if (tok->op == ')') {
--par;
if (par == 0U)
break;
}
tok = tok->next;
}
}
for (Token *tok2 = tokens->front(); tok2; tok2 = tok2->next)
tok2->location = lpar->location;
return sameline(lpar,tok) ? tok : nullptr;
}
const Token * expand(TokenList * const output, const Location &loc, const Token * const nameTokInst, const MacroMap ¯os, std::set<TokenString> expandedmacros) const {
expandedmacros.insert(nameTokInst->str());
#ifdef SIMPLECPP_DEBUG_MACRO_EXPANSION
std::cout << " expand " << name() << " " << locstring(defineLocation()) << std::endl;
#endif
usageList.push_back(loc);
if (nameTokInst->str() == "__FILE__") {
output->push_back(new Token('\"'+loc.file()+'\"', loc));
return nameTokInst->next;
}
if (nameTokInst->str() == "__LINE__") {
output->push_back(new Token(toString(loc.line), loc));
return nameTokInst->next;
}
if (nameTokInst->str() == "__COUNTER__") {
output->push_back(new Token(toString(usageList.size()-1U), loc));
return nameTokInst->next;
}
const bool calledInDefine = (loc.fileIndex != nameTokInst->location.fileIndex ||
loc.line < nameTokInst->location.line);
std::vector<const Token*> parametertokens1(getMacroParameters(nameTokInst, calledInDefine));
if (functionLike()) {
// No arguments => not macro expansion
if (nameTokInst->next && nameTokInst->next->op != '(') {
output->push_back(new Token(nameTokInst->str(), loc));
return nameTokInst->next;
}
// Parse macro-call
if (variadic) {
if (parametertokens1.size() < args.size()) {
throw wrongNumberOfParameters(nameTokInst->location, name());
}
} else {
if (parametertokens1.size() != args.size() + (args.empty() ? 2U : 1U))
throw wrongNumberOfParameters(nameTokInst->location, name());
}
}
// If macro call uses __COUNTER__ then expand that first
TokenList tokensparams(files);
std::vector<const Token *> parametertokens2;
if (!parametertokens1.empty()) {
bool counter = false;
for (const Token *tok = parametertokens1[0]; tok != parametertokens1.back(); tok = tok->next) {
if (tok->str() == "__COUNTER__") {
counter = true;
break;
}
}
const MacroMap::const_iterator m = macros.find("__COUNTER__");
if (!counter || m == macros.end())
parametertokens2.swap(parametertokens1);
else {
const Macro &counterMacro = m->second;
unsigned int par = 0;
for (const Token *tok = parametertokens1[0]; tok && par < parametertokens1.size(); tok = tok->next) {
if (tok->str() == "__COUNTER__") {
tokensparams.push_back(new Token(toString(counterMacro.usageList.size()), tok->location));
counterMacro.usageList.push_back(tok->location);
} else {
tokensparams.push_back(new Token(*tok));
if (tok == parametertokens1[par]) {
parametertokens2.push_back(tokensparams.cback());
par++;
}
}
}
}
}
Token * const output_end_1 = output->back();
// expand
for (const Token *tok = valueToken; tok != endToken;) {
if (tok->op != '#') {
// A##B => AB
if (sameline(tok, tok->next) && tok->next && tok->next->op == '#' && tok->next->next && tok->next->next->op == '#') {
if (!sameline(tok, tok->next->next->next))
throw invalidHashHash::unexpectedNewline(tok->location, name());
if (variadic && tok->op == ',' && tok->next->next->next->str() == args.back()) {
Token *const comma = newMacroToken(tok->str(), loc, isReplaced(expandedmacros), tok);
output->push_back(comma);
tok = expandToken(output, loc, tok->next->next->next, macros, expandedmacros, parametertokens2);
if (output->back() == comma)
output->deleteToken(comma);
continue;
}
TokenList new_output(files);
if (!expandArg(&new_output, tok, parametertokens2))
output->push_back(newMacroToken(tok->str(), loc, isReplaced(expandedmacros), tok));
else if (new_output.empty()) // placemarker token
output->push_back(newMacroToken("", loc, isReplaced(expandedmacros)));
else
for (const Token *tok2 = new_output.cfront(); tok2; tok2 = tok2->next)
output->push_back(newMacroToken(tok2->str(), loc, isReplaced(expandedmacros), tok2));
tok = tok->next;
} else {
tok = expandToken(output, loc, tok, macros, expandedmacros, parametertokens2);
}
continue;
}
int numberOfHash = 1;
const Token *hashToken = tok->next;
while (sameline(tok,hashToken) && hashToken->op == '#') {
hashToken = hashToken->next;
++numberOfHash;
}
if (numberOfHash == 4 && tok->next->location.col + 1 == tok->next->next->location.col) {
// # ## # => ##
output->push_back(newMacroToken("##", loc, isReplaced(expandedmacros)));
tok = hashToken;
continue;
}
if (numberOfHash >= 2 && tok->location.col + 1 < tok->next->location.col) {
output->push_back(new Token(*tok));
tok = tok->next;
continue;
}
tok = tok->next;
if (tok == endToken) {
output->push_back(new Token(*tok->previous));
break;
}
if (tok->op == '#') {
// A##B => AB
tok = expandHashHash(output, loc, tok->previous, macros, expandedmacros, parametertokens2);
} else {
// #123 => "123"
tok = expandHash(output, loc, tok->previous, expandedmacros, parametertokens2);
}
}
if (!functionLike()) {
for (Token *tok = output_end_1 ? output_end_1->next : output->front(); tok; tok = tok->next) {
tok->macro = nameTokInst->str();
}
}
if (!parametertokens1.empty())
parametertokens1.swap(parametertokens2);
return functionLike() ? parametertokens2.back()->next : nameTokInst->next;
}
const Token *recursiveExpandToken(TokenList *output, TokenList &temp, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
output->takeTokens(temp);
return tok->next;
}
if (!sameline(tok, tok->next)) {
output->takeTokens(temp);
return tok->next;
}
const MacroMap::const_iterator it = macros.find(temp.cback()->str());
if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
output->takeTokens(temp);
return tok->next;
}
const Macro &calledMacro = it->second;
if (!calledMacro.functionLike()) {
output->takeTokens(temp);
return tok->next;
}
TokenList temp2(files);
temp2.push_back(new Token(temp.cback()->str(), tok->location));
const Token * const tok2 = appendTokens(&temp2, loc, tok->next, macros, expandedmacros, parametertokens);
if (!tok2)
return tok->next;
output->takeTokens(temp);
output->deleteToken(output->back());
calledMacro.expand(output, loc, temp2.cfront(), macros, expandedmacros);
return tok2->next;
}
const Token *expandToken(TokenList *output, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
// Not name..
if (!tok->name) {
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
// Macro parameter..
{
TokenList temp(files);
if (tok->str() == "__VA_OPT__") {
if (sameline(tok, tok->next) && tok->next->str() == "(") {
tok = tok->next;
int paren = 1;
while (sameline(tok, tok->next)) {
if (tok->next->str() == "(")
++paren;
else if (tok->next->str() == ")")
--paren;
if (paren == 0)
return tok->next->next;
tok = tok->next;
if (parametertokens.size() > args.size() && parametertokens.front()->next->str() != ")")
tok = expandToken(output, loc, tok, macros, expandedmacros, parametertokens)->previous;
}
}
throw Error(tok->location, "Missing parenthesis for __VA_OPT__(content)");
}
if (expandArg(&temp, tok, loc, macros, expandedmacros, parametertokens)) {
if (tok->str() == "__VA_ARGS__" && temp.empty() && output->cback() && output->cback()->str() == "," &&
tok->nextSkipComments() && tok->nextSkipComments()->str() == ")")
output->deleteToken(output->back());
return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros, parametertokens);
}
}
// Macro..
const MacroMap::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
std::set<std::string> expandedmacros2(expandedmacros);
expandedmacros2.insert(tok->str());
const Macro &calledMacro = it->second;
if (!calledMacro.functionLike()) {
TokenList temp(files);
calledMacro.expand(&temp, loc, tok, macros, expandedmacros);
return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros2, parametertokens);
}
if (!sameline(tok, tok->next)) {
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
TokenList tokens(files);
tokens.push_back(new Token(*tok));
const Token * tok2 = nullptr;
if (tok->next->op == '(')
tok2 = appendTokens(&tokens, loc, tok->next, macros, expandedmacros, parametertokens);
else if (expandArg(&tokens, tok->next, loc, macros, expandedmacros, parametertokens)) {
tokens.front()->location = loc;
if (tokens.cfront()->next && tokens.cfront()->next->op == '(')
tok2 = tok->next;
}
if (!tok2) {
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
TokenList temp(files);
calledMacro.expand(&temp, loc, tokens.cfront(), macros, expandedmacros);
return recursiveExpandToken(output, temp, loc, tok2, macros, expandedmacros, parametertokens);
}
if (tok->str() == DEFINED) {
const Token * const tok2 = tok->next;
const Token * const tok3 = tok2 ? tok2->next : nullptr;
const Token * const tok4 = tok3 ? tok3->next : nullptr;
const Token *defToken = nullptr;
const Token *lastToken = nullptr;
if (sameline(tok, tok4) && tok2->op == '(' && tok3->name && tok4->op == ')') {
defToken = tok3;
lastToken = tok4;
} else if (sameline(tok,tok2) && tok2->name) {
defToken = lastToken = tok2;
}
if (defToken) {
std::string macroName = defToken->str();
if (defToken->next && defToken->next->op == '#' && defToken->next->next && defToken->next->next->op == '#' && defToken->next->next->next && defToken->next->next->next->name && sameline(defToken,defToken->next->next->next)) {
TokenList temp(files);
if (expandArg(&temp, defToken, parametertokens))
macroName = temp.cback()->str();
if (expandArg(&temp, defToken->next->next->next, parametertokens))
macroName += temp.cback() ? temp.cback()->str() : "";
else
macroName += defToken->next->next->next->str();
lastToken = defToken->next->next->next;
}
const bool def = (macros.find(macroName) != macros.end());
output->push_back(newMacroToken(def ? "1" : "0", loc, true));
return lastToken->next;
}
}
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
bool expandArg(TokenList *output, const Token *tok, const std::vector<const Token*> ¶metertokens) const {
if (!tok->name)
return false;
const unsigned int argnr = getArgNum(tok->str());
if (argnr >= args.size())
return false;
// empty variadic parameter
if (variadic && argnr + 1U >= parametertokens.size())
return true;
for (const Token *partok = parametertokens[argnr]->next; partok != parametertokens[argnr + 1U]; partok = partok->next)
output->push_back(new Token(*partok));
return true;
}
bool expandArg(TokenList *output, const Token *tok, const Location &loc, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
if (!tok->name)
return false;
const unsigned int argnr = getArgNum(tok->str());
if (argnr >= args.size())
return false;
if (variadic && argnr + 1U >= parametertokens.size()) // empty variadic parameter
return true;
for (const Token *partok = parametertokens[argnr]->next; partok != parametertokens[argnr + 1U];) {
const MacroMap::const_iterator it = macros.find(partok->str());
if (it != macros.end() && !partok->isExpandedFrom(&it->second) && (partok->str() == name() || expandedmacros.find(partok->str()) == expandedmacros.end())) {
std::set<TokenString> expandedmacros2(expandedmacros); // temporary amnesia to allow reexpansion of currently expanding macros during argument evaluation
expandedmacros2.erase(name());
partok = it->second.expand(output, loc, partok, macros, expandedmacros2);
} else {
output->push_back(newMacroToken(partok->str(), loc, isReplaced(expandedmacros), partok));
output->back()->macro = partok->macro;
partok = partok->next;
}
}
if (tok->whitespaceahead && output->back())
output->back()->whitespaceahead = true;
return true;
}
/**
* Expand #X => "X"
* @param output destination tokenlist
* @param loc location for expanded token
* @param tok The # token
* @param expandedmacros set with expanded macros, with this macro
* @param parametertokens parameters given when expanding this macro
* @return token after the X
*/
const Token *expandHash(TokenList *output, const Location &loc, const Token *tok, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
TokenList tokenListHash(files);
const MacroMap macros2; // temporarily bypass macro expansion
tok = expandToken(&tokenListHash, loc, tok->next, macros2, expandedmacros, parametertokens);
std::ostringstream ostr;
ostr << '\"';
for (const Token *hashtok = tokenListHash.cfront(), *next; hashtok; hashtok = next) {
next = hashtok->next;
ostr << hashtok->str();
if (next && hashtok->whitespaceahead)
ostr << ' ';
}
ostr << '\"';
output->push_back(newMacroToken(escapeString(ostr.str()), loc, isReplaced(expandedmacros)));
return tok;
}
/**
* Expand A##B => AB
* The A should already be expanded. Call this when you reach the first # token
* @param output destination tokenlist
* @param loc location for expanded token
* @param tok first # token
* @param macros all macros
* @param expandedmacros set with expanded macros, with this macro
* @param parametertokens parameters given when expanding this macro
* @param expandResult expand ## result i.e. "AB"?
* @return token after B
*/
const Token *expandHashHash(TokenList *output, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens, bool expandResult=true) const {
Token *A = output->back();
if (!A)
throw invalidHashHash(tok->location, name(), "Missing first argument");
if (!sameline(tok, tok->next) || !sameline(tok, tok->next->next))
throw invalidHashHash::unexpectedNewline(tok->location, name());
const bool canBeConcatenatedWithEqual = A->isOneOf("+-*/%&|^") || A->str() == "<<" || A->str() == ">>";
const bool canBeConcatenatedStringOrChar = isStringLiteral_(A->str()) || isCharLiteral_(A->str());
const bool unexpectedA = (!A->name && !A->number && !A->str().empty() && !canBeConcatenatedWithEqual && !canBeConcatenatedStringOrChar);
Token * const B = tok->next->next;
if (!B->name && !B->number && B->op && !B->isOneOf("#="))
throw invalidHashHash::unexpectedToken(tok->location, name(), B);
if ((canBeConcatenatedWithEqual && B->op != '=') ||
(!canBeConcatenatedWithEqual && B->op == '='))
throw invalidHashHash::cannotCombine(tok->location, name(), A, B);
// Superficial check; more in-depth would in theory be possible _after_ expandArg
if (canBeConcatenatedStringOrChar && (B->number || !B->name))
throw invalidHashHash::cannotCombine(tok->location, name(), A, B);
TokenList tokensB(files);
const Token *nextTok = B->next;
if (canBeConcatenatedStringOrChar) {
if (unexpectedA)
throw invalidHashHash::unexpectedToken(tok->location, name(), A);
// It seems clearer to handle this case separately even though the code is similar-ish, but we don't want to merge here.
// TODO The question is whether the ## or varargs may still apply, and how to provoke?
if (expandArg(&tokensB, B, parametertokens)) {
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
} else {
tokensB.push_back(new Token(*B));
tokensB.back()->location = loc;
}
output->takeTokens(tokensB);
} else {
std::string strAB;
const bool varargs = variadic && !args.empty() && B->str() == args[args.size()-1U];
if (expandArg(&tokensB, B, parametertokens)) {
if (tokensB.empty())
strAB = A->str();
else if (varargs && A->op == ',')
strAB = ",";
else if (varargs && unexpectedA)
throw invalidHashHash::unexpectedToken(tok->location, name(), A);
else {
strAB = A->str() + tokensB.cfront()->str();
tokensB.deleteToken(tokensB.front());
}
} else {
if (unexpectedA)
throw invalidHashHash::unexpectedToken(tok->location, name(), A);
strAB = A->str() + B->str();
}
// producing universal character is undefined behavior
if (A->previous && A->previous->str() == "\\") {
if (strAB[0] == 'u' && strAB.size() == 5)
throw invalidHashHash::universalCharacterUB(tok->location, name(), A, strAB);
if (strAB[0] == 'U' && strAB.size() == 9)
throw invalidHashHash::universalCharacterUB(tok->location, name(), A, strAB);
}
if (varargs && tokensB.empty() && tok->previous->str() == ",")
output->deleteToken(A);
else if (strAB != "," && macros.find(strAB) == macros.end()) {
A->setstr(strAB);
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
output->takeTokens(tokensB);
} else if (sameline(B, nextTok) && sameline(B, nextTok->next) && nextTok->op == '#' && nextTok->next->op == '#') {
TokenList output2(files);
output2.push_back(new Token(strAB, tok->location));
nextTok = expandHashHash(&output2, loc, nextTok, macros, expandedmacros, parametertokens);
output->deleteToken(A);
output->takeTokens(output2);
} else {
output->deleteToken(A);
TokenList tokens(files);
tokens.push_back(new Token(strAB, tok->location));
// for function like macros, push the (...)
if (tokensB.empty() && sameline(B,B->next) && B->next->op=='(') {
const MacroMap::const_iterator it = macros.find(strAB);
if (it != macros.end() && expandedmacros.find(strAB) == expandedmacros.end() && it->second.functionLike()) {
const Token * const tok2 = appendTokens(&tokens, loc, B->next, macros, expandedmacros, parametertokens);
if (tok2)
nextTok = tok2->next;
}
}
if (expandResult)
expandToken(output, loc, tokens.cfront(), macros, expandedmacros, parametertokens);
else
output->takeTokens(tokens);
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
output->takeTokens(tokensB);
}
}
return nextTok;
}
static bool isReplaced(const std::set<std::string> &expandedmacros) {
// return true if size > 1
std::set<std::string>::const_iterator it = expandedmacros.begin();
if (it == expandedmacros.end())
return false;
++it;
return (it != expandedmacros.end());
}
/** name token in definition */
const Token *nameTokDef;
/** arguments for macro */
std::vector<TokenString> args;
/** first token in replacement string */
const Token *valueToken;
/** token after replacement string */
const Token *endToken;
/** files */
std::vector<std::string> &files;
/** this is used for -D where the definition is not seen anywhere in code */
TokenList tokenListDefine;
/** usage of this macro */
mutable std::list<Location> usageList;
/** is macro variadic? */
bool variadic;
/** was the value of this macro actually defined in the code? */
bool valueDefinedInCode_;
};
}
namespace simplecpp {
#ifdef __CYGWIN__
bool startsWith(const std::string &str, const std::string &s)
{
return (str.size() >= s.size() && str.compare(0, s.size(), s) == 0);
}
std::string convertCygwinToWindowsPath(const std::string &cygwinPath)
{
std::string windowsPath;
std::string::size_type pos = 0;
if (cygwinPath.size() >= 11 && startsWith(cygwinPath, "/cygdrive/")) {
const unsigned char driveLetter = cygwinPath[10];
if (std::isalpha(driveLetter)) {
if (cygwinPath.size() == 11) {
windowsPath = toupper(driveLetter);
windowsPath += ":\\"; // volume root directory
pos = 11;
} else if (cygwinPath[11] == '/') {
windowsPath = toupper(driveLetter);
windowsPath += ":";
pos = 11;
}
}
}
for (; pos < cygwinPath.size(); ++pos) {
unsigned char c = cygwinPath[pos];
if (c == '/')
c = '\\';
windowsPath += c;
}
return windowsPath;
}
#endif
}
#ifdef SIMPLECPP_WINDOWS
#if __cplusplus >= 201103L
using MyMutex = std::mutex;
template<class T>
using MyLock = std::lock_guard<T>;
#else
class MyMutex {
public:
MyMutex() {
InitializeCriticalSection(&m_criticalSection);
}
~MyMutex() {
DeleteCriticalSection(&m_criticalSection);
}
CRITICAL_SECTION* lock() {
return &m_criticalSection;
}
private:
CRITICAL_SECTION m_criticalSection;
};
template<typename T>
class MyLock {
public:
explicit MyLock(T& m)
: m_mutex(m) {
EnterCriticalSection(m_mutex.lock());
}
~MyLock() {
LeaveCriticalSection(m_mutex.lock());
}
private:
MyLock& operator=(const MyLock&);
MyLock(const MyLock&);
T& m_mutex;
};
#endif
class RealFileNameMap {
public:
RealFileNameMap() {}
bool getCacheEntry(const std::string& path, std::string& returnPath) {
MyLock<MyMutex> lock(m_mutex);
const std::map<std::string, std::string>::iterator it = m_fileMap.find(path);
if (it != m_fileMap.end()) {
returnPath = it->second;
return true;
}
return false;
}
void addToCache(const std::string& path, const std::string& actualPath) {
MyLock<MyMutex> lock(m_mutex);
m_fileMap[path] = actualPath;
}
private:
std::map<std::string, std::string> m_fileMap;
MyMutex m_mutex;
};
static RealFileNameMap realFileNameMap;
static bool realFileName(const std::string &f, std::string &result)
{
// are there alpha characters in last subpath?
bool alpha = false;
for (std::string::size_type pos = 1; pos <= f.size(); ++pos) {
const unsigned char c = f[f.size() - pos];
if (c == '/' || c == '\\')
break;
if (std::isalpha(c)) {
alpha = true;
break;
}
}
// do not convert this path if there are no alpha characters (either pointless or cause wrong results for . and ..)
if (!alpha)
return false;
// Lookup filename or foldername on file system
if (!realFileNameMap.getCacheEntry(f, result)) {
WIN32_FIND_DATAA FindFileData;
#ifdef __CYGWIN__
const std::string fConverted = simplecpp::convertCygwinToWindowsPath(f);
const HANDLE hFind = FindFirstFileExA(fConverted.c_str(), FindExInfoBasic, &FindFileData, FindExSearchNameMatch, NULL, 0);
#else
HANDLE hFind = FindFirstFileExA(f.c_str(), FindExInfoBasic, &FindFileData, FindExSearchNameMatch, NULL, 0);
#endif
if (INVALID_HANDLE_VALUE == hFind)
return false;
result = FindFileData.cFileName;
realFileNameMap.addToCache(f, result);
FindClose(hFind);
}
return true;
}
static RealFileNameMap realFilePathMap;
/** Change case in given path to match filesystem */
static std::string realFilename(const std::string &f)
{
std::string ret;
ret.reserve(f.size()); // this will be the final size
if (realFilePathMap.getCacheEntry(f, ret))
return ret;
// Current subpath
std::string subpath;
for (std::string::size_type pos = 0; pos < f.size(); ++pos) {
const unsigned char c = f[pos];
// Separator.. add subpath and separator
if (c == '/' || c == '\\') {
// if subpath is empty just add separator
if (subpath.empty()) {
ret += c;
continue;
}
const bool isDriveSpecification =
(pos == 2 && subpath.size() == 2 && std::isalpha(subpath[0]) && subpath[1] == ':');
// Append real filename (proper case)
std::string f2;
if (!isDriveSpecification && realFileName(f.substr(0, pos), f2))
ret += f2;
else
ret += subpath;
subpath.clear();
// Append separator
ret += c;
} else {
subpath += c;
}
}
if (!subpath.empty()) {
std::string f2;
if (realFileName(f,f2))
ret += f2;
else
ret += subpath;
}
realFilePathMap.addToCache(f, ret);
return ret;
}
static bool isAbsolutePath(const std::string &path)
{
if (path.length() >= 3 && path[0] > 0 && std::isalpha(path[0]) && path[1] == ':' && (path[2] == '\\' || path[2] == '/'))
return true;
return path.length() > 1U && (path[0] == '/' || path[0] == '\\');
}
#else
#define realFilename(f) f
static bool isAbsolutePath(const std::string &path)
{
return path.length() > 1U && path[0] == '/';
}
#endif
namespace simplecpp {
/**
* perform path simplifications for . and ..
*/
std::string simplifyPath(std::string path)
{
if (path.empty())
return path;
std::string::size_type pos;
// replace backslash separators
std::replace(path.begin(), path.end(), '\\', '/');
const bool unc(path.compare(0,2,"//") == 0);
// replace "//" with "/"
pos = 0;
while ((pos = path.find("//",pos)) != std::string::npos) {
path.erase(pos,1);
}
// remove "./"
pos = 0;
while ((pos = path.find("./",pos)) != std::string::npos) {
if (pos == 0 || path[pos - 1U] == '/')
path.erase(pos,2);
else
pos += 2;
}
// remove trailing dot if path ends with "/."
if (endsWith(path,"/."))
path.erase(path.size()-1);
// simplify ".."
pos = 1; // don't simplify ".." if path starts with that
while ((pos = path.find("/..", pos)) != std::string::npos) {
// not end of path, then string must be "/../"
if (pos + 3 < path.size() && path[pos + 3] != '/') {
++pos;
continue;
}
// get previous subpath
std::string::size_type pos1 = path.rfind('/', pos - 1U);
if (pos1 == std::string::npos) {
pos1 = 0;
} else {
pos1 += 1U;
}
const std::string previousSubPath = path.substr(pos1, pos - pos1);
if (previousSubPath == "..") {
// don't simplify
++pos;
} else {
// remove previous subpath and ".."
path.erase(pos1, pos - pos1 + 4);
if (path.empty())
path = ".";
// update pos
pos = (pos1 == 0) ? 1 : (pos1 - 1);
}
}
// Remove trailing '/'?
//if (path.size() > 1 && endsWith(path, "/"))
// path.erase(path.size()-1);
if (unc)
path = '/' + path;
// cppcheck-suppress duplicateExpressionTernary - platform-dependent implementation
return strpbrk(path.c_str(), "*?") == nullptr ? realFilename(path) : path;
}
}
/** Evaluate sizeof(type) */
static void simplifySizeof(simplecpp::TokenList &expr, const std::map<std::string, std::size_t> &sizeOfType)
{
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->str() != "sizeof")
continue;
simplecpp::Token *tok1 = tok->next;
if (!tok1) {
throw std::runtime_error("missing sizeof argument");
}
simplecpp::Token *tok2 = tok1->next;
if (!tok2) {
throw std::runtime_error("missing sizeof argument");
}
if (tok1->op == '(') {
tok1 = tok1->next;
while (tok2->op != ')') {
tok2 = tok2->next;
if (!tok2) {
throw std::runtime_error("invalid sizeof expression");
}
}
}
std::string type;
for (simplecpp::Token *typeToken = tok1; typeToken != tok2; typeToken = typeToken->next) {
if ((typeToken->str() == "unsigned" || typeToken->str() == "signed") && typeToken->next->name)
continue;
if (typeToken->str() == "*" && type.find('*') != std::string::npos)
continue;
if (!type.empty())
type += ' ';
type += typeToken->str();
}
const std::map<std::string, std::size_t>::const_iterator it = sizeOfType.find(type);
if (it != sizeOfType.end())
tok->setstr(toString(it->second));
else
continue;
tok2 = tok2->next;
while (tok->next != tok2)
expr.deleteToken(tok->next);
}
}
/** Evaluate __has_include(file) */
static bool isCpp17OrLater(const simplecpp::DUI &dui)
{
const std::string std_ver = simplecpp::getCppStdString(dui.std);
return !std_ver.empty() && (std_ver >= "201703L");
}
static std::string openHeader(std::ifstream &f, const simplecpp::DUI &dui, const std::string &sourcefile, const std::string &header, bool systemheader);
static void simplifyHasInclude(simplecpp::TokenList &expr, const simplecpp::DUI &dui)
{
if (!isCpp17OrLater(dui))
return;
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->str() != HAS_INCLUDE)
continue;
simplecpp::Token *tok1 = tok->next;
if (!tok1) {
throw std::runtime_error("missing __has_include argument");
}
simplecpp::Token *tok2 = tok1->next;
if (!tok2) {
throw std::runtime_error("missing __has_include argument");
}
if (tok1->op == '(') {
tok1 = tok1->next;
while (tok2->op != ')') {
tok2 = tok2->next;
if (!tok2) {
throw std::runtime_error("invalid __has_include expression");
}
}
}
const std::string &sourcefile = tok->location.file();
const bool systemheader = (tok1 && tok1->op == '<');
std::string header;
if (systemheader) {
simplecpp::Token *tok3 = tok1->next;
if (!tok3) {
throw std::runtime_error("missing __has_include closing angular bracket");
}
while (tok3->op != '>') {
tok3 = tok3->next;
if (!tok3) {
throw std::runtime_error("invalid __has_include expression");
}
}
for (simplecpp::Token *headerToken = tok1->next; headerToken != tok3; headerToken = headerToken->next)
header += headerToken->str();
// cppcheck-suppress selfAssignment - platform-dependent implementation
header = realFilename(header);
} else {
header = realFilename(tok1->str().substr(1U, tok1->str().size() - 2U));
}
std::ifstream f;
const std::string header2 = openHeader(f,dui,sourcefile,header,systemheader);
tok->setstr(header2.empty() ? "0" : "1");
tok2 = tok2->next;
while (tok->next != tok2)
expr.deleteToken(tok->next);
}
}
static const char * const altopData[] = {"and","or","bitand","bitor","compl","not","not_eq","xor"};
static const std::set<std::string> altop(&altopData[0], &altopData[8]);
static void simplifyName(simplecpp::TokenList &expr)
{
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->name) {
if (altop.find(tok->str()) != altop.end()) {
bool alt;
if (tok->str() == "not" || tok->str() == "compl") {
alt = isAlternativeUnaryOp(tok,tok->str());
} else {
alt = isAlternativeBinaryOp(tok,tok->str());
}
if (alt)
continue;
}
tok->setstr("0");
}
}
}
/*
* Reads at least minlen and at most maxlen digits (inc. prefix) in base base
* from s starting at position pos and converts them to a
* unsigned long long value, updating pos to point to the first
* unused element of s.
* Returns ULLONG_MAX if the result is not representable and
* throws if the above requirements were not possible to satisfy.
*/
static unsigned long long stringToULLbounded(
const std::string& s,
std::size_t& pos,
int base = 0,
std::ptrdiff_t minlen = 1,
std::size_t maxlen = std::string::npos
)
{
const std::string sub = s.substr(pos, maxlen);
const char * const start = sub.c_str();
char* end;
const unsigned long long value = std::strtoull(start, &end, base);
pos += end - start;
if (end - start < minlen)
throw std::runtime_error("expected digit");
return value;
}
/* Converts character literal (including prefix, but not ud-suffix)
* to long long value.
*
* Assumes ASCII-compatible single-byte encoded str for narrow literals
* and UTF-8 otherwise.
*
* For target assumes
* - execution character set encoding matching str
* - UTF-32 execution wide-character set encoding
* - requirements for __STDC_UTF_16__, __STDC_UTF_32__ and __STDC_ISO_10646__ satisfied
* - char16_t is 16bit wide
* - char32_t is 32bit wide
* - wchar_t is 32bit wide and unsigned
* - matching char signedness to host
* - matching sizeof(int) to host
*
* For host assumes
* - ASCII-compatible execution character set
*
* For host and target assumes
* - CHAR_BIT == 8
* - two's complement
*
* Implements multi-character narrow literals according to GCC's behavior,
* except multi code unit universal character names are not supported.
* Multi-character wide literals are not supported.
* Limited support of universal character names for non-UTF-8 execution character set encodings.
*/
long long simplecpp::characterLiteralToLL(const std::string& str)
{
// default is wide/utf32
bool narrow = false;
bool utf8 = false;
bool utf16 = false;
std::size_t pos;
if (!str.empty() && str[0] == '\'') {
narrow = true;
pos = 1;
} else if (str.size() >= 2 && str[0] == 'u' && str[1] == '\'') {
utf16 = true;
pos = 2;
} else if (str.size() >= 3 && str[0] == 'u' && str[1] == '8' && str[2] == '\'') {
utf8 = true;
pos = 3;
} else if (str.size() >= 2 && (str[0] == 'L' || str[0] == 'U') && str[1] == '\'') {
pos = 2;
} else
throw std::runtime_error("expected a character literal");
unsigned long long multivalue = 0;
std::size_t nbytes = 0;
while (pos + 1 < str.size()) {
if (str[pos] == '\'' || str[pos] == '\n')
throw std::runtime_error("raw single quotes and newlines not allowed in character literals");
if (nbytes >= 1 && !narrow)
throw std::runtime_error("multiple characters only supported in narrow character literals");
unsigned long long value;
if (str[pos] == '\\') {
pos++;
const char escape = str[pos++];
if (pos >= str.size())
throw std::runtime_error("unexpected end of character literal");
switch (escape) {
// obscure GCC extensions
case '%':
case '(':
case '[':
case '{':
// standard escape sequences
case '\'':
case '"':
case '?':
case '\\':
value = static_cast<unsigned char>(escape);
break;
case 'a':
value = static_cast<unsigned char>('\a');
break;
case 'b':
value = static_cast<unsigned char>('\b');
break;
case 'f':
value = static_cast<unsigned char>('\f');
break;
case 'n':
value = static_cast<unsigned char>('\n');
break;
case 'r':
value = static_cast<unsigned char>('\r');
break;
case 't':
value = static_cast<unsigned char>('\t');
break;
case 'v':
value = static_cast<unsigned char>('\v');
break;
// GCC extension for ESC character
case 'e':
case 'E':
value = static_cast<unsigned char>('\x1b');
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
// octal escape sequences consist of 1 to 3 digits
value = stringToULLbounded(str, --pos, 8, 1, 3);
break;
case 'x':
// hexadecimal escape sequences consist of at least 1 digit
value = stringToULLbounded(str, pos, 16);
break;
case 'u':
case 'U': {
// universal character names have exactly 4 or 8 digits
const std::size_t ndigits = (escape == 'u' ? 4 : 8);
value = stringToULLbounded(str, pos, 16, ndigits, ndigits);
// UTF-8 encodes code points above 0x7f in multiple code units
// code points above 0x10ffff are not allowed
if (((narrow || utf8) && value > 0x7f) || (utf16 && value > 0xffff) || value > 0x10ffff)
throw std::runtime_error("code point too large");
if (value >= 0xd800 && value <= 0xdfff)
throw std::runtime_error("surrogate code points not allowed in universal character names");
break;
}
default:
throw std::runtime_error("invalid escape sequence");
}
} else {
value = static_cast<unsigned char>(str[pos++]);
if (!narrow && value >= 0x80) {
// Assuming this is a UTF-8 encoded code point.
// This decoder may not completely validate the input.
// Noncharacters are neither rejected nor replaced.
int additional_bytes;
if (value >= 0xf5) // higher values would result in code points above 0x10ffff
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
if (value >= 0xf0)
additional_bytes = 3;
else if (value >= 0xe0)
additional_bytes = 2;
else if (value >= 0xc2) // 0xc0 and 0xc1 are always overlong 2-bytes encodings
additional_bytes = 1;
else
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
value &= (1 << (6 - additional_bytes)) - 1;
while (additional_bytes--) {
if (pos + 1 >= str.size())
throw std::runtime_error("assumed UTF-8 encoded source, but character literal ends unexpectedly");
const unsigned char c = str[pos++];
if (((c >> 6) != 2) // ensure c has form 0xb10xxxxxx
|| (!value && additional_bytes == 1 && c < 0xa0) // overlong 3-bytes encoding
|| (!value && additional_bytes == 2 && c < 0x90)) // overlong 4-bytes encoding
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
value = (value << 6) | (c & ((1 << 7) - 1));
}
if (value >= 0xd800 && value <= 0xdfff)
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
if ((utf8 && value > 0x7f) || (utf16 && value > 0xffff) || value > 0x10ffff)
throw std::runtime_error("code point too large");
}
}
if (((narrow || utf8) && value > std::numeric_limits<unsigned char>::max()) || (utf16 && value >> 16) || value >> 32)
throw std::runtime_error("numeric escape sequence too large");
multivalue <<= CHAR_BIT;
multivalue |= value;
nbytes++;
}
if (pos + 1 != str.size() || str[pos] != '\'')
throw std::runtime_error("missing closing quote in character literal");
if (!nbytes)
throw std::runtime_error("empty character literal");
// ordinary narrow character literal's value is determined by (possibly signed) char
if (narrow && nbytes == 1)
return static_cast<char>(multivalue);
// while multi-character literal's value is determined by (signed) int
if (narrow)
return static_cast<int>(multivalue);
// All other cases are unsigned. Since long long is at least 64bit wide,
// while the literals at most 32bit wide, the conversion preserves all values.
return multivalue;
}
static void simplifyNumbers(simplecpp::TokenList &expr)
{
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->str().size() == 1U)
continue;
if (tok->str().compare(0,2,"0x") == 0)
tok->setstr(toString(stringToULL(tok->str())));
else if (!tok->number && tok->str().find('\'') != std::string::npos)
tok->setstr(toString(simplecpp::characterLiteralToLL(tok->str())));
}
}
static void simplifyComments(simplecpp::TokenList &expr)
{
for (simplecpp::Token *tok = expr.front(); tok;) {
simplecpp::Token * const d = tok;
tok = tok->next;
if (d->comment)
expr.deleteToken(d);
}
}
static long long evaluate(simplecpp::TokenList &expr, const simplecpp::DUI &dui, const std::map<std::string, std::size_t> &sizeOfType)
{
simplifyComments(expr);
simplifySizeof(expr, sizeOfType);
simplifyHasInclude(expr, dui);
simplifyName(expr);
simplifyNumbers(expr);
expr.constFold();
// TODO: handle invalid expressions
return expr.cfront() && expr.cfront() == expr.cback() && expr.cfront()->number ? stringToLL(expr.cfront()->str()) : 0LL;
}
static const simplecpp::Token *gotoNextLine(const simplecpp::Token *tok)
{
const unsigned int line = tok->location.line;
const unsigned int file = tok->location.fileIndex;
while (tok && tok->location.line == line && tok->location.fileIndex == file)
tok = tok->next;
return tok;
}
#ifdef SIMPLECPP_WINDOWS
class NonExistingFilesCache {
public:
NonExistingFilesCache() {}
bool contains(const std::string& path) {
MyLock<MyMutex> lock(m_mutex);
return (m_pathSet.find(path) != m_pathSet.end());
}
void add(const std::string& path) {
MyLock<MyMutex> lock(m_mutex);
m_pathSet.insert(path);
}
void clear() {
MyLock<MyMutex> lock(m_mutex);
m_pathSet.clear();
}
private:
std::set<std::string> m_pathSet;
MyMutex m_mutex;
};
static NonExistingFilesCache nonExistingFilesCache;
#endif
static std::string openHeader(std::ifstream &f, const std::string &path)
{
std::string simplePath = simplecpp::simplifyPath(path);
#ifdef SIMPLECPP_WINDOWS
if (nonExistingFilesCache.contains(simplePath))
return ""; // file is known not to exist, skip expensive file open call
#endif
f.open(simplePath.c_str());
if (f.is_open())
return simplePath;
#ifdef SIMPLECPP_WINDOWS
nonExistingFilesCache.add(simplePath);
#endif
return "";
}
static std::string getRelativeFileName(const std::string &sourcefile, const std::string &header)
{
if (sourcefile.find_first_of("\\/") != std::string::npos)
return simplecpp::simplifyPath(sourcefile.substr(0, sourcefile.find_last_of("\\/") + 1U) + header);
return simplecpp::simplifyPath(header);
}
static std::string openHeaderRelative(std::ifstream &f, const std::string &sourcefile, const std::string &header)
{
return openHeader(f, getRelativeFileName(sourcefile, header));
}
static std::string getIncludePathFileName(const std::string &includePath, const std::string &header)
{
std::string path = includePath;
if (!path.empty() && path[path.size()-1U]!='/' && path[path.size()-1U]!='\\')
path += '/';
return path + header;
}
static std::string openHeaderIncludePath(std::ifstream &f, const simplecpp::DUI &dui, const std::string &header)
{
for (std::list<std::string>::const_iterator it = dui.includePaths.begin(); it != dui.includePaths.end(); ++it) {
std::string simplePath = openHeader(f, getIncludePathFileName(*it, header));
if (!simplePath.empty())
return simplePath;
}
return "";
}
static std::string openHeader(std::ifstream &f, const simplecpp::DUI &dui, const std::string &sourcefile, const std::string &header, bool systemheader)
{
if (isAbsolutePath(header))
return openHeader(f, header);
std::string ret;
if (systemheader) {
ret = openHeaderIncludePath(f, dui, header);
return ret;
}
ret = openHeaderRelative(f, sourcefile, header);
if (ret.empty())
return openHeaderIncludePath(f, dui, header);
return ret;
}
static std::string getFileName(const std::map<std::string, simplecpp::TokenList *> &filedata, const std::string &sourcefile, const std::string &header, const simplecpp::DUI &dui, bool systemheader)
{
if (filedata.empty()) {
return "";
}
if (isAbsolutePath(header)) {
return (filedata.find(header) != filedata.end()) ? simplecpp::simplifyPath(header) : "";
}
if (!systemheader) {
const std::string relativeFilename = getRelativeFileName(sourcefile, header);
if (filedata.find(relativeFilename) != filedata.end())
return relativeFilename;
}
for (std::list<std::string>::const_iterator it = dui.includePaths.begin(); it != dui.includePaths.end(); ++it) {
std::string s = simplecpp::simplifyPath(getIncludePathFileName(*it, header));
if (filedata.find(s) != filedata.end())
return s;
}
if (systemheader && filedata.find(header) != filedata.end())
return header;
return "";
}
static bool hasFile(const std::map<std::string, simplecpp::TokenList *> &filedata, const std::string &sourcefile, const std::string &header, const simplecpp::DUI &dui, bool systemheader)
{
return !getFileName(filedata, sourcefile, header, dui, systemheader).empty();
}
std::map<std::string, simplecpp::TokenList*> simplecpp::load(const simplecpp::TokenList &rawtokens, std::vector<std::string> &filenames, const simplecpp::DUI &dui, simplecpp::OutputList *outputList)
{
#ifdef SIMPLECPP_WINDOWS
if (dui.clearIncludeCache)
nonExistingFilesCache.clear();
#endif
std::map<std::string, simplecpp::TokenList*> ret;
std::list<const Token *> filelist;
// -include files
for (std::list<std::string>::const_iterator it = dui.includes.begin(); it != dui.includes.end(); ++it) {
const std::string &filename = realFilename(*it);
if (ret.find(filename) != ret.end())
continue;
std::ifstream fin(filename.c_str());
if (!fin.is_open()) {
if (outputList) {
simplecpp::Output err(filenames);
err.type = simplecpp::Output::EXPLICIT_INCLUDE_NOT_FOUND;
err.location = Location(filenames);
err.msg = "Can not open include file '" + filename + "' that is explicitly included.";
outputList->push_back(err);
}
continue;
}
fin.close();
TokenList *tokenlist = new TokenList(filename, filenames, outputList);
if (!tokenlist->front()) {
delete tokenlist;
continue;
}
if (dui.removeComments)
tokenlist->removeComments();
ret[filename] = tokenlist;
filelist.push_back(tokenlist->front());
}
for (const Token *rawtok = rawtokens.cfront(); rawtok || !filelist.empty(); rawtok = rawtok ? rawtok->next : nullptr) {
if (rawtok == nullptr) {
rawtok = filelist.back();
filelist.pop_back();
}
if (rawtok->op != '#' || sameline(rawtok->previousSkipComments(), rawtok))
continue;
rawtok = rawtok->nextSkipComments();
if (!rawtok || rawtok->str() != INCLUDE)
continue;
const std::string &sourcefile = rawtok->location.file();
const Token * const htok = rawtok->nextSkipComments();
if (!sameline(rawtok, htok))
continue;
const bool systemheader = (htok->str()[0] == '<');
const std::string header(realFilename(htok->str().substr(1U, htok->str().size() - 2U)));
if (hasFile(ret, sourcefile, header, dui, systemheader))
continue;
std::ifstream f;
const std::string header2 = openHeader(f,dui,sourcefile,header,systemheader);
if (!f.is_open())
continue;
f.close();
TokenList *tokens = new TokenList(header2, filenames, outputList);
if (dui.removeComments)
tokens->removeComments();
ret[header2] = tokens;
if (tokens->front())
filelist.push_back(tokens->front());
}
return ret;
}
static bool preprocessToken(simplecpp::TokenList &output, const simplecpp::Token **tok1, simplecpp::MacroMap ¯os, std::vector<std::string> &files, simplecpp::OutputList *outputList)
{
const simplecpp::Token * const tok = *tok1;
const simplecpp::MacroMap::const_iterator it = macros.find(tok->str());
if (it != macros.end()) {
simplecpp::TokenList value(files);
try {
*tok1 = it->second.expand(&value, tok, macros, files);
} catch (simplecpp::Macro::Error &err) {
if (outputList) {
simplecpp::Output out(files);
out.type = simplecpp::Output::SYNTAX_ERROR;
out.location = err.location;
out.msg = "failed to expand \'" + tok->str() + "\', " + err.what;
outputList->push_back(out);
}
return false;
}
output.takeTokens(value);
} else {
if (!tok->comment)
output.push_back(new simplecpp::Token(*tok));
*tok1 = tok->next;
}
return true;
}
static void getLocaltime(struct tm <ime)
{
time_t t;
time(&t);
#ifndef _WIN32
// NOLINTNEXTLINE(misc-include-cleaner) - false positive
localtime_r(&t, <ime);
#else
localtime_s(<ime, &t);
#endif
}
static std::string getDateDefine(const struct tm *timep)
{
char buf[] = "??? ?? ????";
strftime(buf, sizeof(buf), "%b %d %Y", timep);
return std::string("\"").append(buf).append("\"");
}
static std::string getTimeDefine(const struct tm *timep)
{
char buf[] = "??:??:??";
strftime(buf, sizeof(buf), "%T", timep);
return std::string("\"").append(buf).append("\"");
}
void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenList &rawtokens, std::vector<std::string> &files, std::map<std::string, simplecpp::TokenList *> &filedata, const simplecpp::DUI &dui, simplecpp::OutputList *outputList, std::list<simplecpp::MacroUsage> *macroUsage, std::list<simplecpp::IfCond> *ifCond)
{
#ifdef SIMPLECPP_WINDOWS
if (dui.clearIncludeCache)
nonExistingFilesCache.clear();
#endif
std::map<std::string, std::size_t> sizeOfType(rawtokens.sizeOfType);
sizeOfType.insert(std::make_pair("char", sizeof(char)));
sizeOfType.insert(std::make_pair("short", sizeof(short)));
sizeOfType.insert(std::make_pair("short int", sizeOfType["short"]));
sizeOfType.insert(std::make_pair("int", sizeof(int)));
sizeOfType.insert(std::make_pair("long", sizeof(long)));
sizeOfType.insert(std::make_pair("long int", sizeOfType["long"]));
sizeOfType.insert(std::make_pair("long long", sizeof(long long)));
sizeOfType.insert(std::make_pair("float", sizeof(float)));
sizeOfType.insert(std::make_pair("double", sizeof(double)));
sizeOfType.insert(std::make_pair("long double", sizeof(long double)));
sizeOfType.insert(std::make_pair("char *", sizeof(char *)));
sizeOfType.insert(std::make_pair("short *", sizeof(short *)));
sizeOfType.insert(std::make_pair("short int *", sizeOfType["short *"]));
sizeOfType.insert(std::make_pair("int *", sizeof(int *)));
sizeOfType.insert(std::make_pair("long *", sizeof(long *)));
sizeOfType.insert(std::make_pair("long int *", sizeOfType["long *"]));
sizeOfType.insert(std::make_pair("long long *", sizeof(long long *)));
sizeOfType.insert(std::make_pair("float *", sizeof(float *)));
sizeOfType.insert(std::make_pair("double *", sizeof(double *)));
sizeOfType.insert(std::make_pair("long double *", sizeof(long double *)));
// use a dummy vector for the macros because as this is not part of the file and would add an empty entry - e.g. /usr/include/poll.h
std::vector<std::string> dummy;
const bool hasInclude = isCpp17OrLater(dui);
MacroMap macros;
for (std::list<std::string>::const_iterator it = dui.defines.begin(); it != dui.defines.end(); ++it) {
const std::string ¯ostr = *it;
const std::string::size_type eq = macrostr.find('=');
const std::string::size_type par = macrostr.find('(');
const std::string macroname = macrostr.substr(0, std::min(eq,par));
if (dui.undefined.find(macroname) != dui.undefined.end())
continue;
const std::string lhs(macrostr.substr(0,eq));
const std::string rhs(eq==std::string::npos ? std::string("1") : macrostr.substr(eq+1));
const Macro macro(lhs, rhs, dummy);
macros.insert(std::pair<TokenString,Macro>(macro.name(), macro));
}
macros.insert(std::make_pair("__FILE__", Macro("__FILE__", "__FILE__", dummy)));
macros.insert(std::make_pair("__LINE__", Macro("__LINE__", "__LINE__", dummy)));
macros.insert(std::make_pair("__COUNTER__", Macro("__COUNTER__", "__COUNTER__", dummy)));
struct tm ltime = {};
getLocaltime(ltime);
macros.insert(std::make_pair("__DATE__", Macro("__DATE__", getDateDefine(<ime), dummy)));
macros.insert(std::make_pair("__TIME__", Macro("__TIME__", getTimeDefine(<ime), dummy)));
if (!dui.std.empty()) {
const cstd_t c_std = simplecpp::getCStd(dui.std);
if (c_std != CUnknown) {
const std::string std_def = simplecpp::getCStdString(c_std);
if (!std_def.empty())
macros.insert(std::make_pair("__STDC_VERSION__", Macro("__STDC_VERSION__", std_def, dummy)));
} else {
const cppstd_t cpp_std = simplecpp::getCppStd(dui.std);
if (cpp_std == CPPUnknown) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::DUI_ERROR;
err.msg = "unknown standard specified: '" + dui.std + "'";
outputList->push_back(err);
}
output.clear();
return;
}
const std::string std_def = simplecpp::getCppStdString(cpp_std);
if (!std_def.empty())
macros.insert(std::make_pair("__cplusplus", Macro("__cplusplus", std_def, dummy)));
}
}
// True => code in current #if block should be kept
// ElseIsTrue => code in current #if block should be dropped. the code in the #else should be kept.
// AlwaysFalse => drop all code in #if and #else
enum IfState { True, ElseIsTrue, AlwaysFalse };
std::stack<int> ifstates;
ifstates.push(True);
std::stack<const Token *> includetokenstack;
std::set<std::string> pragmaOnce;
includetokenstack.push(rawtokens.cfront());
for (std::list<std::string>::const_iterator it = dui.includes.begin(); it != dui.includes.end(); ++it) {
const std::map<std::string, TokenList*>::const_iterator f = filedata.find(*it);
if (f != filedata.end())
includetokenstack.push(f->second->cfront());
}
std::map<std::string, std::list<Location> > maybeUsedMacros;
for (const Token *rawtok = nullptr; rawtok || !includetokenstack.empty();) {
if (rawtok == nullptr) {
rawtok = includetokenstack.top();
includetokenstack.pop();
continue;
}
if (rawtok->op == '#' && !sameline(rawtok->previousSkipComments(), rawtok)) {
if (!sameline(rawtok, rawtok->next)) {
rawtok = rawtok->next;
continue;
}
rawtok = rawtok->next;
if (!rawtok->name) {
rawtok = gotoNextLine(rawtok);
continue;
}
if (ifstates.size() <= 1U && (rawtok->str() == ELIF || rawtok->str() == ELSE || rawtok->str() == ENDIF)) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = rawtok->location;
err.msg = "#" + rawtok->str() + " without #if";
outputList->push_back(err);
}
output.clear();
return;
}
if (ifstates.top() == True && (rawtok->str() == ERROR || rawtok->str() == WARNING)) {
if (outputList) {
simplecpp::Output err(rawtok->location.files);
err.type = rawtok->str() == ERROR ? Output::ERROR : Output::WARNING;
err.location = rawtok->location;
for (const Token *tok = rawtok->next; tok && sameline(rawtok,tok); tok = tok->next) {
if (!err.msg.empty() && isNameChar(tok->str()[0]))
err.msg += ' ';
err.msg += tok->str();
}
err.msg = '#' + rawtok->str() + ' ' + err.msg;
outputList->push_back(err);
}
if (rawtok->str() == ERROR) {
output.clear();
return;
}
}
if (rawtok->str() == DEFINE) {
if (ifstates.top() != True)
continue;
try {
const Macro ¯o = Macro(rawtok->previous, files);
if (dui.undefined.find(macro.name()) == dui.undefined.end()) {
const MacroMap::iterator it = macros.find(macro.name());
if (it == macros.end())
macros.insert(std::pair<TokenString, Macro>(macro.name(), macro));
else
it->second = macro;
}
} catch (const std::runtime_error &) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = rawtok->location;
err.msg = "Failed to parse #define";
outputList->push_back(err);
}
output.clear();
return;
}
} else if (ifstates.top() == True && rawtok->str() == INCLUDE) {
TokenList inc1(files);
for (const Token *inctok = rawtok->next; sameline(rawtok,inctok); inctok = inctok->next) {
if (!inctok->comment)
inc1.push_back(new Token(*inctok));
}
TokenList inc2(files);
if (!inc1.empty() && inc1.cfront()->name) {
const Token *inctok = inc1.cfront();
if (!preprocessToken(inc2, &inctok, macros, files, outputList)) {
output.clear();
return;
}
} else {
inc2.takeTokens(inc1);
}
if (!inc1.empty() && !inc2.empty() && inc2.cfront()->op == '<' && inc2.cback()->op == '>') {
TokenString hdr;
// TODO: Sometimes spaces must be added in the string
// Somehow preprocessToken etc must be told that the location should be source location not destination location
for (const Token *tok = inc2.cfront(); tok; tok = tok->next) {
hdr += tok->str();
}
inc2.clear();
inc2.push_back(new Token(hdr, inc1.cfront()->location));
inc2.front()->op = '<';
}
if (inc2.empty() || inc2.cfront()->str().size() <= 2U) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = rawtok->location;
err.msg = "No header in #include";
outputList->push_back(err);
}
output.clear();
return;
}
const Token * const inctok = inc2.cfront();
const bool systemheader = (inctok->str()[0] == '<');
const std::string header(realFilename(inctok->str().substr(1U, inctok->str().size() - 2U)));
std::string header2 = getFileName(filedata, rawtok->location.file(), header, dui, systemheader);
if (header2.empty()) {
// try to load file..
std::ifstream f;
header2 = openHeader(f, dui, rawtok->location.file(), header, systemheader);
if (f.is_open()) {
f.close();
TokenList * const tokens = new TokenList(header2, files, outputList);
if (dui.removeComments)
tokens->removeComments();
filedata[header2] = tokens;
}
}
if (header2.empty()) {
if (outputList) {
simplecpp::Output out(files);
out.type = Output::MISSING_HEADER;
out.location = rawtok->location;
out.msg = "Header not found: " + inctok->str();
outputList->push_back(out);
}
} else if (includetokenstack.size() >= 400) {
if (outputList) {
simplecpp::Output out(files);
out.type = Output::INCLUDE_NESTED_TOO_DEEPLY;
out.location = rawtok->location;
out.msg = "#include nested too deeply";
outputList->push_back(out);
}
} else if (pragmaOnce.find(header2) == pragmaOnce.end()) {
includetokenstack.push(gotoNextLine(rawtok));
const TokenList * const includetokens = filedata.find(header2)->second;
rawtok = includetokens ? includetokens->cfront() : nullptr;
continue;
}
} else if (rawtok->str() == IF || rawtok->str() == IFDEF || rawtok->str() == IFNDEF || rawtok->str() == ELIF) {
if (!sameline(rawtok,rawtok->next)) {
if (outputList) {
simplecpp::Output out(files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "Syntax error in #" + rawtok->str();
outputList->push_back(out);
}
output.clear();
return;
}
bool conditionIsTrue;
if (ifstates.top() == AlwaysFalse || (ifstates.top() == ElseIsTrue && rawtok->str() != ELIF))
conditionIsTrue = false;
else if (rawtok->str() == IFDEF) {
conditionIsTrue = (macros.find(rawtok->next->str()) != macros.end() || (hasInclude && rawtok->next->str() == HAS_INCLUDE));
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
} else if (rawtok->str() == IFNDEF) {
conditionIsTrue = (macros.find(rawtok->next->str()) == macros.end() && !(hasInclude && rawtok->next->str() == HAS_INCLUDE));
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
} else { /*if (rawtok->str() == IF || rawtok->str() == ELIF)*/
TokenList expr(files);
for (const Token *tok = rawtok->next; tok && tok->location.sameline(rawtok->location); tok = tok->next) {
if (!tok->name) {
expr.push_back(new Token(*tok));
continue;
}
if (tok->str() == DEFINED) {
tok = tok->next;
const bool par = (tok && tok->op == '(');
if (par)
tok = tok->next;
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
if (tok) {
if (macros.find(tok->str()) != macros.end())
expr.push_back(new Token("1", tok->location));
else if (hasInclude && tok->str() == HAS_INCLUDE)
expr.push_back(new Token("1", tok->location));
else
expr.push_back(new Token("0", tok->location));
}
if (par)
tok = tok ? tok->next : nullptr;
if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')')) {
if (outputList) {
Output out(rawtok->location.files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "failed to evaluate " + std::string(rawtok->str() == IF ? "#if" : "#elif") + " condition";
outputList->push_back(out);
}
output.clear();
return;
}
continue;
}
if (hasInclude && tok->str() == HAS_INCLUDE) {
tok = tok->next;
const bool par = (tok && tok->op == '(');
if (par)
tok = tok->next;
bool closingAngularBracket = false;
if (tok) {
const std::string &sourcefile = rawtok->location.file();
const bool systemheader = (tok && tok->op == '<');
std::string header;
if (systemheader) {
while ((tok = tok->next) && tok->op != '>')
header += tok->str();
// cppcheck-suppress selfAssignment - platform-dependent implementation
header = realFilename(header);
if (tok && tok->op == '>')
closingAngularBracket = true;
} else {
header = realFilename(tok->str().substr(1U, tok->str().size() - 2U));
closingAngularBracket = true;
}
std::ifstream f;
const std::string header2 = openHeader(f,dui,sourcefile,header,systemheader);
expr.push_back(new Token(header2.empty() ? "0" : "1", tok->location));
}
if (par)
tok = tok ? tok->next : nullptr;
if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')') || (!closingAngularBracket)) {
if (outputList) {
Output out(rawtok->location.files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "failed to evaluate " + std::string(rawtok->str() == IF ? "#if" : "#elif") + " condition";
outputList->push_back(out);
}
output.clear();
return;
}
continue;
}
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
const Token *tmp = tok;
if (!preprocessToken(expr, &tmp, macros, files, outputList)) {
output.clear();
return;
}
if (!tmp)
break;
tok = tmp->previous;
}
try {
if (ifCond) {
std::string E;
for (const simplecpp::Token *tok = expr.cfront(); tok; tok = tok->next)
E += (E.empty() ? "" : " ") + tok->str();
const long long result = evaluate(expr, dui, sizeOfType);
conditionIsTrue = (result != 0);
ifCond->push_back(IfCond(rawtok->location, E, result));
} else {
const long long result = evaluate(expr, dui, sizeOfType);
conditionIsTrue = (result != 0);
}
} catch (const std::exception &e) {
if (outputList) {
Output out(rawtok->location.files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "failed to evaluate " + std::string(rawtok->str() == IF ? "#if" : "#elif") + " condition";
if (e.what() && *e.what())
out.msg += std::string(", ") + e.what();
outputList->push_back(out);
}
output.clear();
return;
}
}
if (rawtok->str() != ELIF) {
// push a new ifstate..
if (ifstates.top() != True)
ifstates.push(AlwaysFalse);
else
ifstates.push(conditionIsTrue ? True : ElseIsTrue);
} else if (ifstates.top() == True) {
ifstates.top() = AlwaysFalse;
} else if (ifstates.top() == ElseIsTrue && conditionIsTrue) {
ifstates.top() = True;
}
} else if (rawtok->str() == ELSE) {
ifstates.top() = (ifstates.top() == ElseIsTrue) ? True : AlwaysFalse;
} else if (rawtok->str() == ENDIF) {
ifstates.pop();
} else if (rawtok->str() == UNDEF) {
if (ifstates.top() == True) {
const Token *tok = rawtok->next;
while (sameline(rawtok,tok) && tok->comment)
tok = tok->next;
if (sameline(rawtok, tok))
macros.erase(tok->str());
}
} else if (ifstates.top() == True && rawtok->str() == PRAGMA && rawtok->next && rawtok->next->str() == ONCE && sameline(rawtok,rawtok->next)) {
pragmaOnce.insert(rawtok->location.file());
}
rawtok = gotoNextLine(rawtok);
continue;
}
if (ifstates.top() != True) {
// drop code
rawtok = gotoNextLine(rawtok);
continue;
}
bool hash=false, hashhash=false;
if (rawtok->op == '#' && sameline(rawtok,rawtok->next)) {
if (rawtok->next->op != '#') {
hash = true;
rawtok = rawtok->next; // skip '#'
} else if (sameline(rawtok,rawtok->next->next)) {
hashhash = true;
rawtok = rawtok->next->next; // skip '#' '#'
}
}
const Location loc(rawtok->location);
TokenList tokens(files);
if (!preprocessToken(tokens, &rawtok, macros, files, outputList)) {
output.clear();
return;
}
if (hash || hashhash) {
std::string s;
for (const Token *hashtok = tokens.cfront(); hashtok; hashtok = hashtok->next)
s += hashtok->str();
if (hash)
output.push_back(new Token('\"' + s + '\"', loc));
else if (output.back())
output.back()->setstr(output.cback()->str() + s);
else
output.push_back(new Token(s, loc));
} else {
output.takeTokens(tokens);
}
}
if (macroUsage) {
for (simplecpp::MacroMap::const_iterator macroIt = macros.begin(); macroIt != macros.end(); ++macroIt) {
const Macro ¯o = macroIt->second;
std::list<Location> usage = macro.usage();
const std::list<Location>& temp = maybeUsedMacros[macro.name()];
usage.insert(usage.end(), temp.begin(), temp.end());
for (std::list<Location>::const_iterator usageIt = usage.begin(); usageIt != usage.end(); ++usageIt) {
MacroUsage mu(usageIt->files, macro.valueDefinedInCode());
mu.macroName = macro.name();
mu.macroLocation = macro.defineLocation();
mu.useLocation = *usageIt;
macroUsage->push_back(mu);
}
}
}
}
void simplecpp::cleanup(std::map<std::string, TokenList*> &filedata)
{
for (std::map<std::string, TokenList*>::iterator it = filedata.begin(); it != filedata.end(); ++it)
delete it->second;
filedata.clear();
}
simplecpp::cstd_t simplecpp::getCStd(const std::string &std)
{
if (std == "c90" || std == "c89" || std == "iso9899:1990" || std == "iso9899:199409" || std == "gnu90" || std == "gnu89")
return C89;
if (std == "c99" || std == "c9x" || std == "iso9899:1999" || std == "iso9899:199x" || std == "gnu99"|| std == "gnu9x")
return C99;
if (std == "c11" || std == "c1x" || std == "iso9899:2011" || std == "gnu11" || std == "gnu1x")
return C11;
if (std == "c17" || std == "c18" || std == "iso9899:2017" || std == "iso9899:2018" || std == "gnu17"|| std == "gnu18")
return C17;
if (std == "c23" || std == "gnu23" || std == "c2x" || std == "gnu2x")
return C23;
return CUnknown;
}
std::string simplecpp::getCStdString(cstd_t std)
{
switch (std) {
case C89:
// __STDC_VERSION__ is not set for C90 although the macro was added in the 1994 amendments
return "";
case C99:
return "199901L";
case C11:
return "201112L";
case C17:
return "201710L";
case C23:
// supported by GCC 9+ and Clang 9+
// Clang 9, 10, 11, 12, 13 return "201710L"
// Clang 14, 15, 16, 17 return "202000L"
// Clang 9, 10, 11, 12, 13, 14, 15, 16, 17 do not support "c23" and "gnu23"
return "202311L";
case CUnknown:
return "";
}
return "";
}
std::string simplecpp::getCStdString(const std::string &std)
{
return getCStdString(getCStd(std));
}
simplecpp::cppstd_t simplecpp::getCppStd(const std::string &std)
{
if (std == "c++98" || std == "c++03" || std == "gnu++98" || std == "gnu++03")
return CPP03;
if (std == "c++11" || std == "gnu++11" || std == "c++0x" || std == "gnu++0x")
return CPP11;
if (std == "c++14" || std == "c++1y" || std == "gnu++14" || std == "gnu++1y")
return CPP14;
if (std == "c++17" || std == "c++1z" || std == "gnu++17" || std == "gnu++1z")
return CPP17;
if (std == "c++20" || std == "c++2a" || std == "gnu++20" || std == "gnu++2a")
return CPP20;
if (std == "c++23" || std == "c++2b" || std == "gnu++23" || std == "gnu++2b")
return CPP23;
if (std == "c++26" || std == "c++2c" || std == "gnu++26" || std == "gnu++2c")
return CPP26;
return CPPUnknown;
}
std::string simplecpp::getCppStdString(cppstd_t std)
{
switch (std) {
case CPP03:
return "199711L";
case CPP11:
return "201103L";
case CPP14:
return "201402L";
case CPP17:
return "201703L";
case CPP20:
// GCC 10 returns "201703L" - correct in 11+
return "202002L";
case CPP23:
// supported by GCC 11+ and Clang 12+
// GCC 11, 12, 13 return "202100L"
// Clang 12, 13, 14, 15, 16 do not support "c++23" and "gnu++23" and return "202101L"
// Clang 17, 18 return "202302L"
return "202302L";
case CPP26:
// supported by Clang 17+
return "202400L";
case CPPUnknown:
return "";
}
return "";
}
std::string simplecpp::getCppStdString(const std::string &std)
{
return getCppStdString(getCppStd(std));
}
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#undef nullptr
#endif
|