1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650
|
/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cstdarg>
#include <csetjmp>
#include <cctype>
#include <string>
#include "globalincs/safe_strings.h"
#include "globalincs/version.h"
#include "globalincs/vmallocator.h"
#include "localization/fhash.h"
#include "localization/localize.h"
#include "mission/missionparse.h"
#include "parse/encrypt.h"
#include "parse/parselo.h"
#include "parse/sexp.h"
#include "ship/ship.h"
#include "weapon/weapon.h"
#include "mod_table/mod_table.h"
#include "utils/encoding.h"
#include "utils/unicode.h"
#include <stdint.h>
#include <string.h>
#include <utf8.h>
using namespace parse;
#define ERROR_LENGTH 64
#define RS_MAX_TRIES 5
#define SHARP_S (char)-33
// to know that a modular table is currently being parsed
bool Parsing_modular_table = false;
char Current_filename[MAX_PATH_LEN];
char Current_filename_sub[MAX_PATH_LEN]; //Last attempted file to load, don't know if ex or not.
char Error_str[ERROR_LENGTH];
int Warning_count, Error_count;
int fred_parse_flag = 0;
int Token_found_flag;
char *Parse_text = nullptr;
char *Parse_text_raw = nullptr;
char *Mp = NULL, *Mp_save = NULL;
const char *token_found;
SCP_vector<Bookmark> Bookmarks; // Stack of all our previously paused parsing
// text allocation stuff
void allocate_parse_text(size_t size);
static size_t Parse_text_size = 0;
// Return true if this character is white space, else false.
int is_white_space(char ch)
{
return ((ch == ' ') || (ch == '\t') || (ch == EOLN) || (ch == CARRIAGE_RETURN));
}
int is_white_space(unicode::codepoint_t cp)
{
return ((cp == UNICODE_CHAR(' ')) || (cp == UNICODE_CHAR('\t')) || (cp == (unicode::codepoint_t)EOLN) || (cp == (unicode::codepoint_t)CARRIAGE_RETURN));
}
// Returns true if this character is gray space, else false (gray space is white space except for EOLN).
int is_gray_space(char ch)
{
return ((ch == ' ') || (ch == '\t'));
}
bool is_gray_space(unicode::codepoint_t cp) {
return cp == UNICODE_CHAR(' ') || cp == UNICODE_CHAR('\t');
}
bool is_parenthesis(char ch)
{
return ((ch == '(') || (ch == ')'));
}
// Advance global Mp (mission pointer) past all current white space.
// Leaves Mp pointing at first non white space character.
void ignore_white_space(const char **pp)
{
if (pp == nullptr)
pp = const_cast<const char**>(&Mp);
while ((**pp != '\0') && is_white_space(**pp))
(*pp)++;
}
void ignore_gray_space(const char **pp)
{
if (pp == nullptr)
pp = const_cast<const char**>(&Mp);
while ((**pp != '\0') && is_gray_space(**pp))
(*pp)++;
}
// Truncate *str, eliminating all trailing white space.
// Eg: "abc " becomes "abc"
// "abc abc " becomes "abc abc"
// "abc \t" becomes "abc"
void drop_trailing_white_space(char *str)
{
auto len = strlen(str);
if (len == 0)
{
// Nothing to do here
return;
}
auto i = len - 1;
while (i != INVALID_SIZE && is_white_space(str[i]))
{
--i;
}
str[i + 1] = '\0';
}
// Ditto for SCP_string
void drop_trailing_white_space(SCP_string &str)
{
if (str.empty())
{
// Nothing to do here
return;
}
auto i = str.size() - 1;
while (i != INVALID_SIZE && is_white_space(str[i]))
{
--i;
}
str.resize(i + 1);
}
// Eliminate any leading whitespace in str
void drop_leading_white_space(char *str)
{
auto len = strlen(str);
size_t first = 0;
// find first non-whitespace
while ((first < len) && is_white_space(str[first]))
first++;
// quick out
if (first == 0)
return;
memmove(str, str+first, len-first);
str[len-first] = 0;
}
// Ditto for SCP_string
void drop_leading_white_space(SCP_string &str)
{
auto len = str.length();
size_t first = 0;
// find first non-whitespace
while ((first < len) && is_white_space(str[first]))
first++;
// quick out
if (first == 0)
return;
// Assign the found substring to the string
str = str.substr(first, len - first);
}
// eliminates all leading and trailing white space from a string. Returns pointer passed in.
char *drop_white_space(char *str)
{
drop_trailing_white_space(str);
drop_leading_white_space(str);
return str;
}
// ditto for SCP_string
void drop_white_space(SCP_string &str)
{
drop_trailing_white_space(str);
drop_leading_white_space(str);
}
// Advances Mp past current token.
void skip_token()
{
ignore_white_space();
while ((*Mp != '\0') && !is_white_space(*Mp))
Mp++;
}
// Display a diagnostic message if Verbose is set.
// (Verbose is set if -v command line switch is present.)
void diag_printf(const char *format, ...)
{
#ifndef NDEBUG
SCP_string buffer;
va_list args;
va_start(args, format);
vsprintf(buffer, format, args);
va_end(args);
nprintf(("Parse", "%s", buffer.c_str()));
#endif
}
// Grab and return (a pointer to) a bunch of tokens, terminating at
// ERROR_LENGTH chars, or end of line.
char *next_tokens(bool terminate_before_parenthesis_or_comma)
{
int count = 0;
char *pstr = Mp;
char ch;
while (((ch = *pstr++) != EOLN) && (ch != '\0') && (count < ERROR_LENGTH-1))
Error_str[count++] = ch;
if (terminate_before_parenthesis_or_comma && (Error_str[count-1] == ',' || Error_str[count - 1] == ')'))
--count;
Error_str[count] = 0;
return Error_str;
}
// Return the line number given by the current mission pointer, ie Mp.
// A very slow function (scans all processed text), but who cares how long
// an error reporting function takes?
int get_line_num()
{
int count = 1;
bool inquote = false;
int incomment = false;
int multiline = false;
char *p = Parse_text;
char *stoploc = Mp;
// if there is no parse text, then we have some ad-hoc text such as provided in an evaluateSEXP call or in the debug console
if (Parse_text == nullptr)
return count;
while (p < stoploc)
{
if (*p == '\0') {
Warning(LOCATION, "Unexpected end-of-file while looking for line number!");
break;
}
if ( !incomment && (*p == '\"') )
inquote = !inquote;
if ( !incomment && !inquote && (*p == COMMENT_CHAR) )
incomment = true;
if ( !incomment && (*p == '/') && (*(p+1) == '*') ) {
multiline = true;
incomment = true;
}
if ( incomment )
stoploc++;
if ( multiline && (*(p-1) == '*') && (*p == '/') ) {
multiline = false;
incomment = false;
}
if (*p++ == EOLN) {
if ( !multiline && incomment )
incomment = false;
count++;
}
}
return count;
}
// Call this function to display an error message.
// error_level == 0 means this is just a warning.
// !0 means it's an error message.
// Prints line number and other useful information.
extern int Cmdline_noparseerrors;
void error_display(int error_level, const char *format, ...)
{
char type[8];
SCP_string error_text;
va_list args;
if (error_level == 0) {
strcpy_s(type, "Warning");
Warning_count++;
} else {
strcpy_s(type, "Error");
Error_count++;
}
va_start(args, format);
vsprintf(error_text, format, args);
va_end(args);
nprintf((type, "%s(line %i): %s: %s\n", Current_filename, get_line_num(), type, error_text.c_str()));
if(error_level == 0 || Cmdline_noparseerrors)
Warning(LOCATION, "%s(line %i):\n%s: %s", Current_filename, get_line_num(), type, error_text.c_str());
else
Error(LOCATION, "%s(line %i):\n%s: %s", Current_filename, get_line_num(), type, error_text.c_str());
}
// Advance Mp to the next eoln character.
void advance_to_eoln(const char *more_terminators)
{
char terminators[128];
Assert((more_terminators == NULL) || (strlen(more_terminators) < 125));
terminators[0] = EOLN;
terminators[1] = 0;
if (more_terminators != NULL)
strcat_s(terminators, more_terminators);
while (strchr(terminators, *Mp) == NULL)
Mp++;
}
// Advance Mp to the next white space (ignoring white space inside of " marks)
void advance_to_next_white()
{
bool in_quotes = false;
while ((*Mp != EOLN) && (*Mp != '\0')) {
if (*Mp == '\"')
in_quotes = !in_quotes;
if (!in_quotes && is_white_space(*Mp))
break;
if (!in_quotes && is_parenthesis(*Mp))
break;
Mp++;
}
}
// If the parser is at an eoln, move past it
bool skip_eoln()
{
auto old_Mp = Mp;
if (*Mp == '\r')
Mp++;
if (*Mp == '\n')
Mp++;
return old_Mp != Mp;
}
// Search for specified string, skipping everything up to that point. Returns 1 if found,
// 0 if string wasn't found (and hit end of file), or -1 if not found, but end of checking
// block was reached.
int skip_to_string(const char *pstr, const char *end)
{
ignore_white_space();
auto len = strlen(pstr);
size_t len2 = 0;
if (end)
len2 = strlen(end);
while ((*Mp != '\0') && strnicmp(pstr, Mp, len) != 0) {
if (end && *Mp == '#')
return 0;
if (end && !strnicmp(end, Mp, len2))
return -1;
advance_to_eoln(NULL);
ignore_white_space();
}
if (!Mp || *Mp == '\0')
return 0;
Mp += strlen(pstr);
return 1;
}
// Goober5000
// Advance to start of pstr. Return 0 is successful, otherwise return !0
int skip_to_start_of_string(const char *pstr, const char *end)
{
ignore_white_space();
auto len = strlen(pstr);
size_t endlen;
if(end)
endlen = strlen(end);
else
endlen = 0;
while ( (*Mp != '\0') && strnicmp(pstr, Mp, len) != 0 ) {
if (end && *Mp == '#')
return 0;
if (end && !strnicmp(end, Mp, endlen))
return 0;
advance_to_eoln(NULL);
ignore_white_space();
}
if (!Mp || *Mp == '\0')
return 0;
return 1;
}
// Advance to start of either pstr1 or pstr2. Return 0 is successful, otherwise return !0
int skip_to_start_of_string_either(const char *pstr1, const char *pstr2, const char *end)
{
size_t len1, len2, endlen;
ignore_white_space();
len1 = strlen(pstr1);
len2 = strlen(pstr2);
if(end)
endlen = strlen(end);
else
endlen = 0;
while ( (*Mp != '\0') && strnicmp(pstr1, Mp, len1) != 0 && strnicmp(pstr2, Mp, len2) != 0 ) {
if (end && *Mp == '#')
return 0;
if (end && !strnicmp(end, Mp, endlen))
return 0;
advance_to_eoln(NULL);
ignore_white_space();
}
if (!Mp || *Mp == '\0')
return 0;
return 1;
}
int skip_to_start_of_string_one_of(const SCP_vector<SCP_string>& pstr, const char* end) {
size_t endlen;
ignore_white_space();
if (end)
endlen = strlen(end);
else
endlen = 0;
while (*Mp != '\0') {
bool foundStart = false;
for (const SCP_string& pstr_i : pstr) {
if (strnicmp(pstr_i.c_str(), Mp, pstr_i.size()) == 0) {
foundStart = true;
break;
}
}
if (foundStart)
break;
if (end && *Mp == '#')
return 0;
if (end && !strnicmp(end, Mp, endlen))
return 0;
advance_to_eoln(NULL);
ignore_white_space();
}
if (!Mp || *Mp == '\0')
return 0;
return 1;
}
// Find a required string.
// If not found, display an error message, but try up to RS_MAX_TRIES times
// to find the string. (This is the groundwork for ignoring non-understood
// lines.
// If unable to find the required string after RS_MAX_TRIES tries, then
// abort using longjmp to parse_abort.
int required_string(const char *pstr)
{
int count = 0;
ignore_white_space();
while (strnicmp(pstr, Mp, strlen(pstr)) != 0 && (count < RS_MAX_TRIES)) {
error_display(1, "Missing required token: [%s]. Found [%.32s] instead.\n", pstr, next_tokens());
advance_to_eoln(NULL);
ignore_white_space();
count++;
}
if (count == RS_MAX_TRIES) {
throw parse::ParseException("Required string not found");
}
Mp += strlen(pstr);
diag_printf("Found required string [%s]\n", token_found = pstr);
return 1;
}
int check_for_eof_raw()
{
if (*Mp == '\0')
return 1;
return 0;
}
int check_for_eof()
{
ignore_white_space();
return check_for_eof_raw();
}
/**
Returns 1 if it finds a newline character precded by any amount of grayspace.
*/
int check_for_eoln()
{
ignore_gray_space();
if(*Mp == EOLN)
return 1;
else
return 0;
}
// similar to optional_string, but just checks if next token is a match.
// It doesn't advance Mp except to skip past white space.
int check_for_string(const char *pstr)
{
ignore_white_space();
if (!strnicmp(pstr, Mp, strlen(pstr)))
return 1;
return 0;
}
// like check for string, but doesn't skip past any whitespace
int check_for_string_raw(const char *pstr)
{
if (!strnicmp(pstr, Mp, strlen(pstr)))
return 1;
return 0;
}
// Find an optional string.
// If found, return 1, else return 0.
// If found, point past string, else don't update pointer.
int optional_string(const char *pstr)
{
ignore_white_space();
if (!strnicmp(pstr, Mp, strlen(pstr))) {
Mp += strlen(pstr);
return 1;
}
return 0;
}
int optional_string_either(const char *str1, const char *str2, bool advance)
{
ignore_white_space();
if ( !strnicmp(str1, Mp, strlen(str1)) ) {
if(advance)
Mp += strlen(str1);
return 0;
} else if ( !strnicmp(str2, Mp, strlen(str2)) ) {
if (advance)
Mp += strlen(str2);
return 1;
}
return -1;
}
// generic parallel to required_string_one_of
int optional_string_one_of(int arg_count, ...)
{
Assertion(arg_count > 0, "optional_string_one_of() called with arg_count of %d; get a coder!\n", arg_count);
int idx, found = -1;
char *pstr;
va_list vl;
ignore_white_space();
va_start(vl, arg_count);
for (idx = 0; idx < arg_count; idx++)
{
pstr = va_arg(vl, char*);
if ( !strnicmp(pstr, Mp, strlen(pstr)) )
{
Mp += strlen(pstr);
found = idx;
break;
}
}
va_end(vl);
return found;
}
int required_string_fred(const char *pstr, const char *end)
{
char *backup = Mp;
token_found = pstr;
if (fred_parse_flag)
return 0;
ignore_white_space();
while (*Mp != '\0' && strnicmp(pstr, Mp, strlen(pstr)) != 0) {
if ((*Mp == '#') || (end && !strnicmp(end, Mp, strlen(end)))) {
Mp = NULL;
break;
}
advance_to_eoln(NULL);
ignore_white_space();
}
if (!Mp || *Mp == '\0') {
diag_printf("Required string [%s] not found\n", pstr);
Mp = backup;
Token_found_flag = 0;
return 0;
}
Mp += strlen(pstr);
diag_printf("Found required string [%s]\n", pstr);
Token_found_flag = 1;
return 1;
}
// attempt to find token in buffer. It might not exist, however, in which case we don't need
// to do anything. If it is found, then we advance the pointer to just after the token. To
// further complicate things, we should only search to a certain point, since we don't want
// a token that belongs to another section which might match the token we want. Thus, we
// also pass in an ending token, which marks the point we should stop looking at.
int optional_string_fred(const char *pstr, const char *end, const char *end2)
{
char *mp_save = Mp;
token_found = pstr;
if (fred_parse_flag)
return 0;
ignore_white_space();
while ((*Mp != '\0') && strnicmp(pstr, Mp, strlen(pstr)) != 0) {
if ((*Mp == '#') || (end && !strnicmp(end, Mp, strlen(end))) ||
(end2 && !strnicmp(end2, Mp, strlen(end2)))) {
Mp = NULL;
break;
}
advance_to_eoln(NULL);
ignore_white_space();
}
if (!Mp || *Mp == '\0') {
diag_printf("Optional string [%s] not found\n", pstr);
Mp = mp_save;
Token_found_flag = 0;
return 0;
}
Mp += strlen(pstr);
diag_printf("Found optional string [%s]\n", pstr);
Token_found_flag = 1;
return 1;
}
/**
* @brief Checks for one of two required strings
*
* @retval 0 for str1 match
* @retval 1 for str2 match
* @throws parse::ParseException If neither strings were found
*
* @details Advances the Mp until a string is found or exceeds RS_MAX_TRIES. Once a string is found, Mp is located at
* the start of the found string.
*/
int required_string_either(const char *str1, const char *str2)
{
ignore_white_space();
for (int count = 0; count < RS_MAX_TRIES; ++count) {
if (strnicmp(str1, Mp, strlen(str1)) == 0) {
// Mp += strlen(str1);
diag_printf("Found required string [%s]\n", token_found = str1);
return 0;
} else if (strnicmp(str2, Mp, strlen(str2)) == 0) {
// Mp += strlen(str2);
diag_printf("Found required string [%s]\n", token_found = str2);
return 1;
}
error_display(1, "Required token = [%s] or [%s], found [%.32s].\n", str1, str2, next_tokens());
advance_to_eoln(NULL);
ignore_white_space();
}
throw parse::ParseException("Required string not found");
}
/**
* @brief Checks for one of any of the given required strings.
*
* @returns The index number of the found string, if it was found
* @returns -1 if a string was not found
*
* @details By ngld, with some tweaks by MageKing17.
*/
int required_string_one_of(int arg_count, ...)
{
Assertion(arg_count > 0, "required_string_one_of() called with arg_count of %d; get a coder!\n", arg_count);
int count = 0;
int idx;
char *expected;
SCP_string message = "";
va_list vl;
ignore_white_space();
while (count < RS_MAX_TRIES) {
va_start(vl, arg_count);
for (idx = 0; idx < arg_count; idx++) {
expected = va_arg(vl, char*);
if (strnicmp(expected, Mp, strlen(expected)) == 0) {
diag_printf("Found required string [%s]", token_found = expected);
va_end(vl);
return idx;
}
}
va_end(vl);
if (message.empty()) {
va_start(vl, arg_count);
message = "Required token = ";
for (idx = 0; idx < arg_count; idx++) {
message += "[";
message += va_arg(vl, char*);
message += "]";
if (arg_count == 2 && idx == 0) {
message += " or ";
} else if (idx == arg_count - 2) {
message += ", or ";
} else if (idx < arg_count - 2) {
message += ", ";
}
}
va_end(vl);
}
error_display(1, "%s, found [%.32s]\n", message.c_str(), next_tokens());
advance_to_eoln(NULL);
ignore_white_space();
count++;
}
return -1;
}
int required_string_either_fred(const char *str1, const char *str2)
{
ignore_white_space();
while (*Mp != '\0') {
if (!strnicmp(str1, Mp, strlen(str1))) {
// Mp += strlen(str1);
diag_printf("Found required string [%s]\n", token_found = str1);
return fred_parse_flag = 0;
} else if (!strnicmp(str2, Mp, strlen(str2))) {
// Mp += strlen(str2);
diag_printf("Found required string [%s]\n", token_found = str2);
return fred_parse_flag = 1;
}
advance_to_eoln(NULL);
ignore_white_space();
}
if (*Mp == '\0')
diag_printf("Unable to find either required token [%s] or [%s]\n", str1, str2);
return -1;
}
// Copy characters from instr to outstr until eoln is found, or until max
// characters have been copied (including terminator).
void copy_to_eoln(char *outstr, const char *more_terminators, const char *instr, int max)
{
int count = 0;
char ch;
char terminators[128];
Assert((more_terminators == NULL) || (strlen(more_terminators) < 125));
terminators[0] = EOLN;
terminators[1] = 0;
if (more_terminators != NULL)
strcat_s(terminators, more_terminators);
while (((ch = *instr++) != 0) && (strchr(terminators, ch) == NULL) && (count < max)) {
*outstr++ = ch;
count++;
}
if (count >= max)
error_display(0, "Token too long: [%s]. Length = " SIZE_T_ARG ". Max is %i.\n", next_tokens(), strlen(next_tokens()), max);
*outstr = 0;
}
// Ditto for SCP_string.
void copy_to_eoln(SCP_string &outstr, const char *more_terminators, const char *instr)
{
char ch;
char terminators[128];
Assert((more_terminators == NULL) || (strlen(more_terminators) < 125));
terminators[0] = EOLN;
terminators[1] = 0;
if (more_terminators != NULL)
strcat_s(terminators, more_terminators);
outstr = "";
while (((ch = *instr++) != 0) && (strchr(terminators, ch) == NULL)) {
outstr.append(1, ch);
}
}
// Copy characters from instr to outstr until next white space is found, or until max
// characters have been copied (including terminator).
void copy_to_next_white(char *outstr, const char *instr, int max)
{
int count = 0;
bool in_quotes = false;
char ch;
while (((ch = *instr++)>0) && (ch != EOLN) && (ch != '\0') && (count < max)) {
if ( ch == '\"' ) {
in_quotes = !in_quotes;
continue;
}
if ( !in_quotes && is_white_space(ch) ) // not in quotes, white space terminates string
break;
if ( !in_quotes && is_parenthesis(ch) ) // not in quotes, parentheses are important for parsing so we don't want to copy them
break;
*outstr++ = ch;
count++;
}
if (count >= max)
error_display(0, "Token too long: [%s]. Length = " SIZE_T_ARG ". Max is %i.\n", next_tokens(), strlen(next_tokens()), max);
*outstr = 0;
}
// Ditto for SCP_string.
void copy_to_next_white(SCP_string &outstr, const char *instr)
{
bool in_quotes = false;
char ch;
outstr = "";
while (((ch = *instr++)>0) && (ch != EOLN) && (ch != '\0')) {
if ( ch == '\"' ) {
in_quotes = !in_quotes;
continue;
}
if ( !in_quotes && is_white_space(ch) ) // not in quotes, white space terminates string
break;
if ( !in_quotes && is_parenthesis(ch) ) // not in quotes, parentheses are important for parsing so we don't want to copy them
break;
outstr.append(1, ch);
}
}
//Returns a null-terminated character string allocated with vm_malloc() with the data
char* alloc_text_until(const char* instr, const char* endstr)
{
Assert(instr && endstr);
auto foundstr = stristr(instr, endstr);
if(foundstr == NULL)
{
Error(LOCATION, "Missing [%s] in file", endstr);
throw parse::ParseException("End string not found");
}
else
{
if ( (foundstr - instr) <= 0 ) {
Int3(); // since this really shouldn't ever happen
return NULL;
}
char* rstr = NULL;
rstr = (char*) vm_malloc((foundstr - instr + 1)*sizeof(char));
if(rstr != NULL) {
strncpy(rstr, instr, foundstr-instr);
rstr[foundstr-instr] = '\0';
} else {
Error(LOCATION, "Could not allocate enough memory in alloc_text_until");
}
return rstr;
}
}
// Copy text until a certain string is matched.
// For example, this is used to copy mission notes, scanning until $END NOTES:
// is found.
void copy_text_until(char *outstr, const char *instr, const char *endstr, int max_chars)
{
Assert(outstr && instr && endstr);
auto foundstr = stristr(instr, endstr);
if (foundstr == NULL) {
nprintf(("Error", "Error. Looking for [%s], but never found it.\n", endstr));
throw parse::ParseException("End string not found");
}
if (foundstr - instr + strlen(endstr) < (uint) max_chars) {
strncpy(outstr, instr, foundstr - instr);
outstr[foundstr - instr] = 0;
} else {
nprintf(("Error", "Error. Too much text (" SIZE_T_ARG " chars, %i allowed) before %s\n",
foundstr - instr + strlen(endstr), max_chars, endstr));
throw parse::ParseException("Too much text found");
}
diag_printf("Here's the partial wad of text:\n%.30s\n", outstr);
}
// Ditto for SCP_string.
void copy_text_until(SCP_string &outstr, const char *instr, const char *endstr)
{
Assert(instr && endstr);
auto foundstr = stristr(instr, endstr);
if (foundstr == NULL) {
nprintf(("Error", "Error. Looking for [%s], but never found it.\n", endstr));
throw parse::ParseException("End string not found");
}
outstr.assign(instr, foundstr - instr);
diag_printf("Here's the partial wad of text:\n%.30s\n", outstr.c_str());
}
// stuffs a string into a buffer. Can get a string between " marks and stops
// when whitespace is encounted -- not to end of line
void stuff_string_white(char *outstr, int len)
{
if(!len)
len = NAME_LENGTH-1;
ignore_white_space();
copy_to_next_white(outstr, Mp, len);
advance_to_next_white();
}
// ditto for SCP_string
void stuff_string_white(SCP_string &outstr)
{
ignore_white_space();
copy_to_next_white(outstr, Mp);
advance_to_next_white();
}
// Goober5000
void stuff_string_until(char *outstr, const char *endstr, int len)
{
if(!len)
len = NAME_LENGTH-1;
ignore_gray_space();
copy_text_until(outstr, Mp, endstr, len);
Mp += strlen(outstr);
drop_trailing_white_space(outstr);
}
// Goober5000
void stuff_string_until(SCP_string &outstr, const char *endstr)
{
ignore_gray_space();
copy_text_until(outstr, Mp, endstr);
Mp += outstr.length();
drop_trailing_white_space(outstr);
}
//WMC
//Used for allocating large blocks, eg of Python code
//Returns a null-terminated string allocated with vm_malloc(),
//or NULL on failure
//Does depth checks for the start and end strings
//extra_chars indicates extra malloc space that should be allocated.
char* alloc_block(const char* startstr, const char* endstr, int extra_chars)
{
Assert(startstr != NULL && endstr != NULL);
Assert(stricmp(startstr, endstr));
char* rval = NULL;
auto elen = strlen(endstr);
auto slen = strlen(startstr);
size_t flen = 0;
//Skip the opening thing and any extra stuff
required_string(startstr);
ignore_white_space();
//Allocate it
char* pos = Mp;
//Depth checking
int level = 1;
while(*pos != '\0')
{
if(!strnicmp(pos, startstr, slen))
{
level++;
}
else if(!strnicmp(pos, endstr, elen))
{
level--;
}
if(level<=0)
{
break;
}
pos++;
}
//Check that we left the file
if(level > 0)
{
Error(LOCATION, "Unclosed pair of \"%s\" and \"%s\" on line %d in file", startstr, endstr, get_line_num());
throw parse::ParseException("End string not found");
}
else
{
//Set final length for faster calcs
flen = pos-Mp;
//Allocate the memory
//WMC - Don't forget the null character that's added later on.
rval = (char*) vm_malloc((flen + extra_chars + 1)*sizeof(char));
//Copy the text (if memory was allocated)
if(rval != NULL) {
strncpy(rval, Mp, flen);
rval[flen] = '\0';
} else {
return NULL;
}
}
//Skip the copied stuff
Mp += flen;
required_string(endstr);
return rval;
}
// Karajorma - Stuffs the provided char array with either the contents of a quoted string or the name of a string
// variable. Returns PARSING_FOUND_STRING if a string was found or PARSING_FOUND_VARIABLE if a variable was present.
int get_string_or_variable (char *str)
{
int result = -1;
ignore_white_space();
// Variable
if (*Mp == SEXP_VARIABLE_CHAR)
{
auto saved_Mp = Mp;
Mp++;
stuff_string_white(str);
int sexp_variable_index = get_index_sexp_variable_name(str);
// We only want String variables
if (sexp_variable_index >= 0)
result = PARSING_FOUND_VARIABLE;
else
{
Mp = saved_Mp;
stuff_string_white(str);
error_display(1, "Expected \"%s\" to be a variable", str);
}
}
// Quoted string
else if (*Mp == '"')
{
get_string(str);
result = PARSING_FOUND_STRING;
}
else
{
get_string(str);
error_display(1, "Invalid entry \"%s\" found in get_string_or_variable. Must be a quoted string or a string variable name.", str);
}
return result;
}
// ditto for SCP_string
int get_string_or_variable (SCP_string &str)
{
int result = -1;
ignore_white_space();
// Variable
if (*Mp == SEXP_VARIABLE_CHAR)
{
auto saved_Mp = Mp;
Mp++;
stuff_string_white(str);
int sexp_variable_index = get_index_sexp_variable_name(str);
// We only want String variables
if (sexp_variable_index >= 0)
result = PARSING_FOUND_VARIABLE;
else
{
Mp = saved_Mp;
stuff_string_white(str);
error_display(1, "Expected \"%s\" to be a variable", str.c_str());
}
}
// Quoted string
else if (*Mp == '"')
{
get_string(str);
result = PARSING_FOUND_STRING;
}
else
{
get_string(str);
error_display(1, "Invalid entry \"%s\" found in get_string_or_variable. Must be a quoted string or a string variable name.", str.c_str());
}
return result;
}
/**
* Stuff a string (" chars ") into *str, return length.
* Accepts an optional max length parameter. If it is omitted or negative, then no max length is enforced.
*/
int get_string(char *str, int max)
{
auto len = strcspn(Mp + 1, "\"");
if (max >= 0 && len >= (size_t)max)
error_display(0, "String too long. Length = " SIZE_T_ARG ". Max is %i.\n", len, max);
strncpy(str, Mp + 1, len);
str[len] = 0;
Mp += len + 2;
return (int)len;
}
/**
* Stuff a string (" chars ") into str.
*/
void get_string(SCP_string &str)
{
auto len = strcspn(Mp + 1, "\"");
str.assign(Mp + 1, len);
Mp += len + 2;
}
// Stuff a string into a string buffer.
// Supports various FreeSpace primitive types. If 'len' is supplied, it will override
// the default string length if using the F_NAME case.
void stuff_string(char *outstr, int type, int len, const char *terminators)
{
char read_str[PARSE_BUF_SIZE] = "";
int read_len = PARSE_BUF_SIZE;
int final_len = len - 1;
int tag_id;
// make sure we have enough room
Assert( final_len > 0 );
// make sure it's zero'd out
memset( outstr, 0, len );
switch (type) {
case F_RAW:
case F_LNAME:
case F_NAME:
case F_DATE:
case F_FILESPEC:
case F_PATHNAME:
case F_MESSAGE:
ignore_gray_space();
copy_to_eoln(read_str, terminators, Mp, read_len);
drop_trailing_white_space(read_str);
advance_to_eoln(terminators);
break;
case F_NOTES:
ignore_white_space();
copy_text_until(read_str, Mp, "$End Notes:", read_len);
Mp += strlen(read_str);
required_string("$End Notes:");
break;
// F_MULTITEXTOLD keeping for backwards compatability with old missions
// can be deleted once all missions are using new briefing format
case F_MULTITEXTOLD:
ignore_white_space();
copy_text_until(read_str, Mp, "$End Briefing Text:", read_len);
Mp += strlen(read_str);
required_string("$End Briefing Text:");
break;
case F_MULTITEXT:
ignore_white_space();
copy_text_until(read_str, Mp, "$end_multi_text", read_len);
Mp += strlen(read_str);
drop_trailing_white_space(read_str);
required_string("$end_multi_text");
break;
default:
Error(LOCATION, "Unhandled string type %d in stuff_string!", type);
}
if (type == F_FILESPEC) {
// Make sure that the passed string looks like a good filename
if (strlen(read_str) == 0) {
// Empty file name is probably not valid!
error_display(0, "A file name was expected but no name was supplied! This is probably a mistake.");
}
}
// now we want to do any final localization
if(type != F_RAW && type != F_LNAME)
{
lcl_ext_localize(read_str, outstr, final_len, &tag_id);
// if the hash localized text hash table is active and we have a valid external string - hash it
if(fhash_active() && (tag_id > -2)){
fhash_add_str(outstr, tag_id);
}
}
else
{
if ( strlen(read_str) > (uint)final_len )
error_display(0, "Token too long: [%s]. Length = " SIZE_T_ARG ". Max is %i.\n", read_str, strlen(read_str), final_len);
strncpy(outstr, read_str, final_len);
}
diag_printf("Stuffed string = [%.30s]\n", outstr);
}
// Stuff a string into a string buffer.
// Supports various FreeSpace primitive types.
void stuff_string(SCP_string &outstr, int type, const char *terminators)
{
SCP_string read_str;
int tag_id;
// make sure it's zero'd out
outstr = "";
switch (type) {
case F_RAW:
case F_LNAME:
case F_NAME:
case F_DATE:
case F_FILESPEC:
case F_PATHNAME:
case F_MESSAGE:
ignore_gray_space();
copy_to_eoln(read_str, terminators, Mp);
drop_trailing_white_space(read_str);
advance_to_eoln(terminators);
break;
case F_NOTES:
ignore_white_space();
copy_text_until(read_str, Mp, "$End Notes:");
Mp += read_str.length();
required_string("$End Notes:");
break;
// F_MULTITEXTOLD keeping for backwards compatability with old missions
// can be deleted once all missions are using new briefing format
case F_MULTITEXTOLD:
ignore_white_space();
copy_text_until(read_str, Mp, "$End Briefing Text:");
Mp += read_str.length();
required_string("$End Briefing Text:");
break;
case F_MULTITEXT:
ignore_white_space();
copy_text_until(read_str, Mp, "$end_multi_text");
Mp += read_str.length();
drop_trailing_white_space(read_str);
required_string("$end_multi_text");
break;
default:
Error(LOCATION, "Unhandled string type %d in stuff_string!", type);
}
if (type == F_FILESPEC) {
// Make sure that the passed string looks like a good filename
if (read_str.empty()) {
// Empty file name is not valid!
error_display(1, "A file name was expected but no name was supplied!\n");
}
}
// now we want to do any final localization
if(type != F_RAW && type != F_LNAME)
{
lcl_ext_localize(read_str, outstr, &tag_id);
// if the hash localized text hash table is active and we have a valid external string - hash it
if(fhash_active() && (tag_id > -2)){
fhash_add_str(outstr.c_str(), tag_id);
}
}
else
{
outstr = read_str;
}
diag_printf("Stuffed string = [%.30s]\n", outstr.c_str());
}
// stuff a string, but only until the end of a line. don't ignore leading whitespace. close analog of fgets()/cfgets()
void stuff_string_line(char *outstr, int len)
{
char read_str[PARSE_BUF_SIZE] = "";
int read_len = PARSE_BUF_SIZE;
int final_len = len - 1;
int tag_id;
Assert( final_len > 0 );
// read in a line
copy_to_eoln(read_str, "\n", Mp, read_len);
drop_trailing_white_space(read_str);
advance_to_eoln("");
Mp++;
// now we want to do any final localization
lcl_ext_localize(read_str, outstr, final_len, &tag_id);
// if the hash localized text hash table is active and we have a valid external string - hash it
if(fhash_active() && (tag_id > -2)){
fhash_add_str(outstr, tag_id);
}
diag_printf("Stuffed string = [%.30s]\n", outstr);
}
// ditto for SCP_string
void stuff_string_line(SCP_string &outstr)
{
SCP_string read_str;
int tag_id;
// read in a line
copy_to_eoln(read_str, "\n", Mp);
drop_trailing_white_space(read_str);
advance_to_eoln("");
Mp++;
// now we want to do any final localization
lcl_ext_localize(read_str, outstr, &tag_id);
// if the hash localized text hash table is active and we have a valid external string - hash it
if(fhash_active() && (tag_id > -2)){
fhash_add_str(outstr.c_str(), tag_id);
}
diag_printf("Stuffed string = [%.30s]\n", outstr.c_str());
}
// Exactly the same as stuff string only Malloc's the buffer.
// Supports various FreeSpace primitive types. If 'len' is supplied, it will override
// the default string length if using the F_NAME case.
char *stuff_and_malloc_string(int type, const char *terminators)
{
SCP_string tmp_result;
stuff_string(tmp_result, type, terminators);
drop_white_space(tmp_result);
if (tmp_result.empty())
return NULL;
return vm_strdup(tmp_result.c_str());
}
void stuff_malloc_string(char **dest, int type, const char *terminators)
{
Assert(dest != NULL); //wtf?
char *new_val = stuff_and_malloc_string(type, terminators);
if(new_val != NULL)
{
if((*dest) != NULL) {
vm_free(*dest);
}
(*dest) = new_val;
}
}
// After reading a multitext string, you can call this function to convert any newlines into
// spaces, so it's a one paragraph string (i.e. as in MS-Word).
void compact_multitext_string(char *str)
{
auto p_dest = str;
auto p_src = str;
while (*p_src)
{
char ch = *p_src;
// skip CR
// convert LF to space
// copy characters backwards if any CRs previously encountered
if (ch != '\r')
{
if (ch == '\n')
*p_dest = ' ';
else if (p_dest != p_src)
*p_dest = *p_src;
p_dest++;
}
p_src++;
}
if (p_dest != p_src)
*p_dest = 0;
}
// ditto for SCP_string
void compact_multitext_string(SCP_string &str)
{
auto p_dest = str.begin();
auto p_src = str.begin();
while (p_src != str.end())
{
char ch = *p_src;
// skip CR
// convert LF to space
// copy characters backwards if any CRs previously encountered
if (ch != '\r')
{
if (ch == '\n')
*p_dest = ' ';
else if (p_dest != p_src)
*p_dest = *p_src;
p_dest++;
}
p_src++;
}
if (p_dest != p_src)
str.erase(p_dest);
}
// Converts a character from Windows-1252 to CP437.
int maybe_convert_foreign_character(int ch)
{
// time to do some special foreign character conversion
switch (ch) {
case -57:
ch = 128;
break;
case -4:
ch = 129;
break;
case -23:
ch = 130;
break;
case -30:
ch = 131;
break;
case -28:
ch = 132;
break;
case -32:
ch = 133;
break;
case -27:
ch = 134;
break;
case -25:
ch = 135;
break;
case -22:
ch = 136;
break;
case -21:
ch = 137;
break;
case -24:
ch = 138;
break;
case -17:
ch = 139;
break;
case -18:
ch = 140;
break;
case -20:
ch = 141;
break;
case -60:
ch = 142;
break;
case -59:
ch = 143;
break;
case -55:
ch = 144;
break;
case -26:
ch = 145;
break;
case -58:
ch = 146;
break;
case -12:
ch = 147;
break;
case -10:
ch = 148;
break;
case -14:
ch = 149;
break;
case -5:
ch = 150;
break;
case -7:
ch = 151;
break;
case -1:
ch = 152;
break;
case -42:
ch = 153;
break;
case -36:
ch = 154;
break;
case -94:
ch = 155;
break;
case -93:
ch = 156;
break;
case -91:
ch = 157;
break;
case -125:
ch = 159;
break;
case -31:
ch = 160;
break;
case -19:
ch = 161;
break;
case -13:
ch = 162;
break;
case -6:
ch = 163;
break;
case -15:
ch = 164;
break;
case -47:
ch = 165;
break;
case -86:
ch = 166;
break;
case -70:
ch = 167;
break;
case -65:
ch = 168;
break;
case -84:
ch = 170;
break;
case -67:
ch = 171;
break;
case -68:
ch = 172;
break;
case -95:
ch = 173;
break;
case -85:
ch = 174;
break;
case -69:
ch = 175;
break;
case -33:
ch = 225;
break;
case -75:
ch = 230;
break;
case -79:
ch = 241;
break;
case -9:
ch = 246;
break;
case -80:
ch = 248;
break;
case -73:
ch = 250;
break;
case -78:
ch = 253;
break;
case -96:
ch = 255;
break;
}
return ch;
}
// Goober5000
// Yarn - The capacity of out must be at least the value returned by
// get_converted_string_length(in) (plus one if add_null is true).
// Returns the number of characters written to out.
size_t maybe_convert_foreign_characters(const char *in, char *out, bool add_null)
{
if (Fred_running) {
size_t len = strlen(in);
if (add_null) {
strcpy(out, in);
return len + 1;
} else {
strncpy(out, in, len);
return len;
}
} else {
auto inp = in;
auto outp = out;
while (*inp != '\0') {
if (*inp == SHARP_S) {
*outp++ = 's';
*outp++ = 's';
} else if (Lcl_pl) {
*outp++ = *inp;
} else {
*outp++ = (char) maybe_convert_foreign_character(*inp);
}
inp++;
}
if (add_null) {
*outp++ = '\0';
}
return outp - out;
}
}
// Goober5000
void maybe_convert_foreign_characters(SCP_string &text)
{
if (!Fred_running) {
for (SCP_string::iterator ii = text.begin(); ii != text.end(); ++ii) {
text.reserve(get_converted_string_length(text));
if (*ii == SHARP_S) {
text.replace(ii, ii + 1, "ss");
++ii;
} else if (!Lcl_pl) {
*ii = (char) maybe_convert_foreign_character(*ii);
}
}
}
}
// Yarn - Returns what the length of the text will be after it's processed by
// maybe_convert_foreign_characters, not including the null terminator.
size_t get_converted_string_length(const char *text)
{
if (Fred_running) {
return strlen(text);
} else {
size_t count = 0;
auto s = strchr(text, SHARP_S);
while (s != nullptr) {
count++;
s = strchr(s + 1, SHARP_S);
}
return strlen(text) + count;
}
}
// Yarn - Returns what the length of the text will be after it's processed by
// maybe_convert_foreign_characters.
size_t get_converted_string_length(const SCP_string &text)
{
if (Fred_running) {
return text.size();
} else {
size_t count = 0;
for (auto ii = text.begin(); ii != text.end(); ++ii) {
if (*ii == SHARP_S) {
count++;
}
}
return text.size() + count;
}
}
// Goober5000
bool get_number_before_separator(int &number, int &number_chars, const char *text, char separator)
{
char buf[8];
const char *ch = text;
int len = 0;
while (true)
{
// didn't find separator
if (*ch == '\0' || len == 8)
return false;
// found separator
if (*ch == separator)
break;
// found nondigit
if (!isdigit(*ch))
return false;
// copying in progress
buf[len] = *ch;
len++;
ch++;
}
// got an integer
buf[len] = '\0';
number = atoi(buf);
number_chars = len;
return true;
}
// Goober5000
bool get_number_before_separator(int &number, int &number_chars, const SCP_string &text, SCP_string::iterator text_pos, char separator)
{
char buf[8];
SCP_string::iterator ch = text_pos;
int len = 0;
while (true)
{
// didn't find separator
if (ch == text.end() || len == 8)
return false;
// found separator
if (*ch == separator)
break;
// found nondigit
if (!isdigit(*ch))
return false;
// copying in progress
buf[len] = *ch;
len++;
++ch;
}
// got an integer
buf[len] = '\0';
number = atoi(buf);
number_chars = len;
return true;
}
bool matches_version_specific_tag(const char *line_start, bool &compatible_version, int &tag_len)
{
// special version-specific comment
// formatted like e.g. ;;FSO 3.7.0;;
// Should now support anything from ;;FSO 3;; to ;;FSO 3.7.3.20151106;; -MageKing17
if (strnicmp(line_start, ";;FSO ", 6) != 0)
return false;
int major, minor, build, revis;
int s_num = scan_fso_version_string(line_start, &major, &minor, &build, &revis);
if (s_num == 0)
return false;
// hack for releases
if (s_num == 4 && FS_VERSION_REVIS < 1000) {
s_num = 3;
}
const char *ch = line_start + 6;
while ((*ch) != ';') {
Assertion((*ch) != '\0', "String that was already guaranteed to end with semicolons did not end with semicolons; it's possible we have fallen into an alternate universe. Failing string: [%s]\n", line_start);
ch++;
}
ch++;
Assertion((*ch) == ';', "String that was guaranteed to have double semicolons did not; it's possible we have fallen into an alternate universe. Failing string: [%s]\n", line_start);
ch++;
tag_len = (int)(ch - line_start);
compatible_version = true;
// check whether major, minor, and build line up with this version
if (major > FS_VERSION_MAJOR)
{
compatible_version = false;
}
else if (major == FS_VERSION_MAJOR && s_num > 1)
{
if (minor > FS_VERSION_MINOR)
{
compatible_version = false;
}
else if (minor == FS_VERSION_MINOR && s_num > 2)
{
if (build > FS_VERSION_BUILD)
{
compatible_version = false;
}
else if (build == FS_VERSION_BUILD && s_num > 3)
{
if (revis > FS_VERSION_REVIS)
{
compatible_version = false;
}
}
}
}
// true for tag match
return true;
}
// Strip comments from a line of input.
// Goober5000 - rewritten for the second time
void strip_comments(char *line, bool &in_quote, bool &in_multiline_comment_a, bool &in_multiline_comment_b)
{
char *writep = line;
char *readp = line;
// copy all characters from read to write, unless they're commented
while (*readp != '\r' && *readp != '\n' && *readp != '\0')
{
// only check for comments if not quoting
if (!in_quote)
{
bool compatible_version;
int tag_len;
// see what sort of comment characters we recognize
if (!strncmp(readp, "/*", 2))
{
// comment styles are mutually exclusive
if (!in_multiline_comment_b)
in_multiline_comment_a = true;
}
else if (!strncmp(readp, "!*", 2))
{
// comment styles are mutually exclusive
if (!in_multiline_comment_a)
in_multiline_comment_b = true;
}
else if (!strncmp(readp, "*/", 2))
{
if (in_multiline_comment_a)
{
in_multiline_comment_a = false;
readp += 2;
continue;
}
}
else if (!strncmp(readp, "*!", 2))
{
if (in_multiline_comment_b)
{
in_multiline_comment_b = false;
readp += 2;
continue;
}
}
// special version-specific comment
// formatted like e.g. ;;FSO 3.7.0;;
else if (matches_version_specific_tag(readp, compatible_version, tag_len))
{
// comment passes, so advance pass the tag and keep reading
if (compatible_version)
{
readp += tag_len;
continue;
}
// comment does not pass, so ignore the line
else
{
break;
}
}
// standard comment
else if (*readp == ';')
{
break;
}
}
// maybe toggle quoting
if (*readp == '\"')
in_quote = !in_quote;
// if not inside a comment, copy the characters
if (!in_multiline_comment_a && !in_multiline_comment_b)
{
if (writep != readp)
*writep = *readp;
writep++;
}
// read the next character
readp++;
}
// if we moved any characters, or if we haven't reached the end of the string, then mark end-of-line and terminate string
if (writep != readp || *readp != '\0')
{
writep[0] = EOLN;
writep[1] = '\0';
}
}
int parse_get_line(char *lineout, int max_line_len, const char *start, int max_size, const char *cur)
{
char * t = lineout;
int i, num_chars_read=0;
char c;
for ( i = 0; i < max_line_len-1; i++ ) {
do {
if ( (cur - start) >= max_size ) {
*lineout = 0;
if ( lineout > t ) {
return num_chars_read;
} else {
return 0;
}
}
c = *cur++;
num_chars_read++;
} while ( c == 13 );
*lineout++ = c;
if ( c=='\n' ) break;
}
*lineout++ = 0;
return num_chars_read;
}
// Read mission text, stripping comments.
// When a comment is found, it is removed. If an entire line
// consisted of a comment, a blank line is left in the input file.
// Goober5000 - added ability to read somewhere other than Parse_text
void read_file_text(const char *filename, int mode, char *processed_text, char *raw_text)
{
Assertion(filename, "Filename must not be null!");
if (!filename)
throw parse::FileOpenException("Filename must not be null!");
// copy the filename
strcpy_s(Current_filename_sub, filename);
// if we are paused then processed_text and raw_text must not be NULL!!
if ( !Bookmarks.empty() && ((processed_text == NULL) || (raw_text == NULL)) ) {
Error(LOCATION, "ERROR: Neither processed_text nor raw_text may be NULL when parsing is paused!!\n");
}
// read the raw text
read_raw_file_text(filename, mode, raw_text);
if (processed_text == NULL)
processed_text = Parse_text;
if (raw_text == NULL)
raw_text = Parse_text_raw;
// process it (strip comments)
process_raw_file_text(processed_text, raw_text);
}
// Goober5000
void read_file_text_from_default(const default_file& file, char *processed_text, char *raw_text)
{
// we have no filename, so copy a substitute
strcpy_s(Current_filename_sub, "internal default file");
// if we are paused then processed_text and raw_text must not be NULL!!
if ( !Bookmarks.empty() && ((processed_text == NULL) || (raw_text == NULL)) ) {
Error(LOCATION, "ERROR: Neither \"processed_text\" nor \"raw_text\" may be NULL when parsing is paused!!\n");
}
// make sure to do this before anything else
allocate_parse_text(file.size + 1);
// if we have no raw buffer, set it as the default raw text area
if (raw_text == NULL)
raw_text = Parse_text_raw;
auto text = reinterpret_cast<const char*>(file.data);
// copy text in the array (but only if the raw text and the array are not the same)
if (raw_text != file.data)
{
// Copy the file contents into the array and null-terminate it
// We have to make sure to adjust the size if the size of a char is more than 1
strncpy(raw_text, text, file.size / sizeof(char));
raw_text[file.size / sizeof(char)] = '\0';
}
if (processed_text == NULL)
processed_text = Parse_text;
// process the text
process_raw_file_text(processed_text, raw_text);
}
void stop_parse()
{
Assert( Bookmarks.empty() );
if (Parse_text != nullptr) {
vm_free(Parse_text);
Parse_text = nullptr;
}
if (Parse_text_raw != nullptr) {
vm_free(Parse_text_raw);
Parse_text_raw = nullptr;
}
Parse_text_size = 0;
}
void allocate_parse_text(size_t size)
{
Assert( size > 0 );
// Make sure that there is space for the terminating null character
size += 1;
if (size <= Parse_text_size) {
// Make sure that a new parsing session does not use uninitialized data.
memset( Parse_text, 0, sizeof(char) * Parse_text_size );
memset( Parse_text_raw, 0, sizeof(char) * Parse_text_size);
return;
}
static ubyte parse_atexit = 0;
if (!parse_atexit) {
atexit(stop_parse);
parse_atexit = 1;
}
if (Parse_text != nullptr) {
vm_free(Parse_text);
Parse_text = nullptr;
}
if (Parse_text_raw != nullptr) {
vm_free(Parse_text_raw);
Parse_text_raw = nullptr;
}
Parse_text = (char *) vm_malloc(sizeof(char) * size, memory::quiet_alloc);
Parse_text_raw = (char *) vm_malloc(sizeof(char) * size, memory::quiet_alloc);
if ( (Parse_text == nullptr) || (Parse_text_raw == nullptr) ) {
Error(LOCATION, "Unable to allocate enough memory for Parse_text! Aborting...\n");
}
memset( Parse_text, 0, sizeof(char) * size );
memset( Parse_text_raw, 0, sizeof(char) * size);
Parse_text_size = size;
}
// Goober5000
void read_raw_file_text(const char *filename, int mode, char *raw_text)
{
CFILE *mf;
int file_is_encrypted;
Assertion(filename, "Filename must not be null!");
if (!filename)
throw parse::FileOpenException("Filename must not be null!");
mf = cfopen(filename, "rb", CFILE_NORMAL, mode);
if (mf == NULL)
{
nprintf(("Error", "Wokka! Error opening file (%s)!\n", filename));
throw parse::FileOpenException("Failed to open file");
}
// read the entire file in
int file_len = cfilelength(mf);
if(!file_len) {
nprintf(("Error", "Oh noes!! File is empty! (%s)!\n", filename));
throw parse::ParseException("File is empty");
}
// For the possible Latin1 -> UTF-8 conversion we need to reallocate the raw_text at some point and we can only do
// that if we have control over the raw_text pointer which is only the case if it's null.
auto can_reallocate = raw_text == nullptr;
if (raw_text == nullptr) {
// allocate, or reallocate, memory for Parse_text and Parse_text_raw based on size we need now
allocate_parse_text((size_t) (file_len + 1));
// NOTE: this always has to be done *after* the allocate_mission_text() call!!
raw_text = Parse_text_raw;
}
// read first 10 bytes to determine if file is encrypted
cfread(raw_text, MIN(file_len, 10), 1, mf);
file_is_encrypted = is_encrypted(raw_text);
cfseek(mf, 0, CF_SEEK_SET);
file_len = util::check_encoding_and_skip_bom(mf, filename);
if ( file_is_encrypted )
{
int unscrambled_len;
char *scrambled_text;
scrambled_text = (char*)vm_malloc(file_len+1);
Assert(scrambled_text);
cfread(scrambled_text, file_len, 1, mf);
// unscramble text
unencrypt(scrambled_text, file_len, raw_text, &unscrambled_len);
file_len = unscrambled_len;
vm_free(scrambled_text);
}
else
{
cfread(raw_text, file_len, 1, mf);
}
//WMC - Slap a NULL character on here for the odd error where we forgot a #End
raw_text[file_len] = '\0';
if (Unicode_text_mode) {
// Validate the UTF-8 encoding
auto invalid = utf8::find_invalid(raw_text, raw_text + file_len);
if (invalid != raw_text + file_len) {
auto isLatin1 = util::guessLatin1Encoding(raw_text, (size_t) file_len);
// We do the additional can_reallocate check here since we need control over raw_text to reencode the file
if (isLatin1 && can_reallocate) {
// Latin1 is the encoding of retail data and for legacy reasons we convert that to UTF-8.
// We still output a warning though...
Warning(LOCATION, "Found Latin-1 encoded file %s. This file will be automatically converted to UTF-8 but "
"it may cause parsing issues with retail FS2 files since those contained invalid data.\n"
"To silence this warning you must convert the files to UTF-8, e.g. by using a program like iconv.",
filename);
// SDL2 has iconv functionality so we use that to convert from Latin1 to UTF-8
// We need the raw_text as fallback so we first need to copy the current
SCP_string input_str = raw_text;
SCP_string buffer;
bool success = unicode::convert_encoding(buffer, raw_text, unicode::Encoding::Encoding_iso8859_1, unicode::Encoding::Encoding_utf8);
if (Parse_text_size < buffer.length()) {
allocate_parse_text(buffer.length());
}
if (success) {
strncpy(Parse_text_raw, buffer.c_str(), buffer.length());
}
else {
Warning(LOCATION, "File reencoding failed!\n"
"You will probably encounter encoding issues.");
// Copy the original data back to the mission text pointer so that we don't loose any data here
strcpy(Parse_text_raw, input_str.c_str());
}
} else {
Warning(LOCATION, "Found invalid UTF-8 encoding in file %s at position " PTRDIFF_T_ARG "!\n"
"This may cause parsing errors and should be fixed!", filename, invalid - raw_text);
}
}
}
cfclose(mf);
}
// Goober5000, based partly on above iconv usage
void coerce_to_utf8(SCP_string &buffer, const char *str)
{
auto len = strlen(str);
// Validate the UTF-8 encoding
auto invalid = utf8::find_invalid(str, str + len);
if (invalid == str + len)
{
// turns out this is valid UTF-8
buffer.assign(str);
return;
}
bool isLatin1 = util::guessLatin1Encoding(str, len);
// we can convert it
if (isLatin1)
{
unicode::convert_encoding(buffer, str, unicode::Encoding::Encoding_iso8859_1, unicode::Encoding::Encoding_utf8);
}
// unknown encoding, so just truncate
buffer.assign(str, invalid - str);
Warning(LOCATION, "Truncating non-UTF-8 string '%s' to '%s'!\n", str, buffer.c_str());
}
// Goober5000
void process_raw_file_text(char* processed_text, char* raw_text)
{
SCP_string parse_exception_1402;
unicode::convert_encoding(parse_exception_1402, "1402, \"Sie haben IPX-Protokoll als Protokoll ausgew\xE4hlt, aber dieses Protokoll ist auf Ihrer Maschine nicht installiert.\".\"\n", unicode::Encoding::Encoding_iso8859_1);
SCP_string parse_exception_1117;
unicode::convert_encoding(parse_exception_1117, "1117, \"\\r\\n\"Aucun web browser trouva. Del\xE0 isn't on emm\xE9nagea ou if \\r\\non est emm\xE9nagea, ca isn't set pour soient la default browser.\\r\\n\\r\\n\"\n", unicode::Encoding::Encoding_iso8859_1);
SCP_string parse_exception_1337;
unicode::convert_encoding(parse_exception_1337, "1337, \"(fr)Loading\"\n", unicode::Encoding::Encoding_iso8859_1);
SCP_string parse_exception_3966;
unicode::convert_encoding(parse_exception_3966, "3966, \"Es sieht so aus, als habe Staffel Kappa Zugriff auf die GTVA-Zugangscodes f\xFCr das System gehabt. Das ist ein ernstes Sicherheitsleck. Ihre IFF-Kennung erschien als \"verb\xFCndet\", so da\xDF sie sich dem Konvoi ungehindert n\xE4hern konnten. Zum Gl\xFC\x63k flogen Sie und Alpha 2 Geleitschutz und lie\xDF\x65n den Schwindel auffliegen, bevor Kappa ihren Befehl ausf\xFChren konnte.\"\n", unicode::Encoding::Encoding_iso8859_1);
char* mp;
char* mp_raw;
char outbuf[PARSE_BUF_SIZE];
bool in_quote = false;
bool in_multiline_comment_a = false;
bool in_multiline_comment_b = false;
int raw_text_len = (int)strlen(raw_text);
if (processed_text == NULL)
processed_text = Parse_text;
if (raw_text == NULL)
raw_text = Parse_text_raw;
Assert(processed_text != NULL);
Assert(raw_text != NULL);
mp = processed_text;
mp_raw = raw_text;
// strip comments from raw text, reading into file_text
int num_chars_read = 0;
while ((num_chars_read = parse_get_line(outbuf, PARSE_BUF_SIZE, raw_text, raw_text_len, mp_raw)) != 0) {
mp_raw += num_chars_read;
// stupid hacks to make retail data work with fixed parser, per Mantis #3072
if (!strcmp(outbuf, parse_exception_1402.c_str())) {
int offset = Unicode_text_mode ? 1 : 0;
outbuf[121 + offset] = ' ';
outbuf[122 + offset] = ' ';
}
else if (!strcmp(outbuf, parse_exception_1117.c_str())) {
char* ch = &outbuf[11];
do {
*ch = *(ch + 1);
++ch;
} while (*ch);
}
else if (!strcmp(outbuf, parse_exception_1337.c_str())) {
outbuf[3] = '6';
}
else if (!strcmp(outbuf, parse_exception_3966.c_str())) {
int offset = Unicode_text_mode ? 1 : 0;
outbuf[171 + offset] = '\'';
outbuf[181 + offset * 2] = '\'';
}
strip_comments(outbuf, in_quote, in_multiline_comment_a, in_multiline_comment_b);
if (Unicode_text_mode) {
// In unicode mode we simply assume that the text is already properly encoded in UTF-8
// Also, since we don't know how big mp actually is since we get the pointer from the outside we can't use one of
// the "safe" strcpy variants here...
strcpy(mp, outbuf);
mp += strlen(outbuf);
} else {
mp += maybe_convert_foreign_characters(outbuf, mp, false);
}
}
// Make sure the string is terminated properly
*mp = *mp_raw = '\0';
/*
while (cfgets(outbuf, PARSE_BUF_SIZE, mf) != NULL) {
if (strlen(outbuf) >= PARSE_BUF_SIZE-1)
error_display(0, "Input string too long. Max is %i characters.\n%.256s\n", PARSE_BUF_SIZE, outbuf);
// If you hit this assert, it is probably telling you the obvious. The file
// you are trying to read is truly too large. Look at *filename to see the file name.
Assert(mp_raw - file_text_raw + strlen(outbuf) < PARSE_TEXT_SIZE);
strcpy_s(mp_raw, outbuf);
mp_raw += strlen(outbuf);
in_comment = strip_comments(outbuf, in_comment);
strcpy_s(mp, outbuf);
mp += strlen(outbuf);
}
*mp = *mp_raw = EOF_CHAR;
*/
}
void debug_show_mission_text()
{
char *mp = Parse_text;
char ch;
while ((ch = *mp++) != '\0')
printf("%c", ch);
}
// Goober5000
void read_file_bytes(const char *filename, int mode, char *raw_bytes)
{
CFILE *mf;
Assertion(filename, "Filename must not be null!");
if (!filename)
throw parse::FileOpenException("Filename must not be null!");
// copy the filename
strcpy_s(Current_filename_sub, filename);
// if we are paused then raw_bytes must not be NULL!!
if ( !Bookmarks.empty() && (raw_bytes == nullptr) ) {
Error(LOCATION, "ERROR: raw_bytes may not be NULL when parsing is paused!!\n");
}
mf = cfopen(filename, "rb", CFILE_NORMAL, mode);
if (mf == nullptr)
{
nprintf(("Error", "Wokka! Error opening file (%s)!\n", filename));
throw parse::FileOpenException("Failed to open file");
}
// read the entire file in
int file_len = cfilelength(mf);
if(!file_len) {
nprintf(("Error", "Oh noes!! File is empty! (%s)!\n", filename));
throw parse::ParseException("File is empty");
}
if (raw_bytes == nullptr) {
// allocate, or reallocate, memory for Parse_text and Parse_text_raw based on size we need now
allocate_parse_text((size_t) (file_len + 1));
// NOTE: this always has to be done *after* the allocate_mission_text() call!!
raw_bytes = Parse_text_raw;
}
cfread(raw_bytes, file_len, 1, mf);
//WMC - Slap a NULL character on here for the odd error where we forgot a #End
// Goober5000 - for binary files, the equivalent is an EOF
raw_bytes[file_len] = EOF;
cfclose(mf);
}
// Returns whether the first character encountered in str that is not whitespace is the character to look for.
// If so, and if after_ch is non-nullptr, it will be set to point to the first character after the character to look for.
bool check_first_non_whitespace_char(const char *str, char char_to_look_for, char **after_ch)
{
auto active_ch = str;
while (true)
{
if (*active_ch == '\0')
return false;
if (!is_white_space(*active_ch))
break;
active_ch++;
}
if (*active_ch == char_to_look_for)
{
if (after_ch != nullptr)
*after_ch = const_cast<char*>(active_ch + 1); // this is ugly, but strtof and strtod do the same thing
return true;
}
return false;
}
// Do the same thing for grayspace
bool check_first_non_grayspace_char(const char *str, char char_to_look_for, char **after_ch)
{
auto active_ch = str;
while (true)
{
if (*active_ch == '\0')
return false;
if (!is_gray_space(*active_ch))
break;
active_ch++;
}
if (*active_ch == char_to_look_for)
{
if (after_ch != nullptr)
*after_ch = const_cast<char*>(active_ch + 1); // this is ugly, but strtof and strtod do the same thing
return true;
}
return false;
}
bool unexpected_numeric_char(char ch)
{
return (ch != '\0') && (ch != ',') && (ch != ')') && !is_white_space(ch);
}
// Stuff a floating point value pointed at by Mp.
// Advances past float characters.
int stuff_float(float *f, bool optional)
{
char *str_start = Mp;
char *str_end;
// since strtof ignores white space anyway, might as well make it explicit
ignore_white_space();
auto result = strtof(Mp, &str_end);
bool success = false, comma = false;
int retval = 0;
// no float found?
if (result == 0.0f && str_end == Mp)
{
if (!optional)
error_display(1, "Expected float, found [%.32s].\n", next_tokens());
}
else
{
*f = result;
success = true;
}
if (success)
Mp = str_end;
// if an unexpected character is part of the number, warn about it
if (success && unexpected_numeric_char(*Mp))
{
error_display(0, "Expected float, found [%.32s].\n", next_tokens(true));
// Rather than back up to str_start, do what retail did and continue
// merrily parsing along at the next character. (Optional numbers
// will still back up to str_start - c.f. a few lines down.)
if (optional)
success = false;
}
if (check_first_non_grayspace_char(Mp, ',', &Mp))
comma = true;
if (optional && !success)
Mp = str_start;
if (success)
{
retval = 2;
diag_printf("Stuffed float: %f\n", *f);
}
else if (optional)
retval = comma ? 1 : 0;
else
skip_token();
return retval;
}
// Stuff an integer value pointed at by Mp.
// Advances past integer characters.
int stuff_int(int *i, bool optional)
{
char *str_start = Mp;
// since atoi ignores white space anyway, might as well make it explicit
ignore_white_space();
// this is a bit cumbersome
size_t span;
if (*Mp == '+' || *Mp == '-')
{
span = strspn(Mp + 1, "0123456789");
// account for the sign symbol, but not if it's the only valid character
if (span > 0)
++span;
}
else
span = strspn(Mp, "0123456789");
auto result = atoi(Mp);
bool success = false, comma = false;
int retval = 0;
// no int found?
if (result == 0 && span == 0)
{
if (!optional)
error_display(1, "Expected int, found [%.32s].\n", next_tokens());
}
else
{
*i = result;
success = true;
}
if (success)
Mp += span;
// if an unexpected character is part of the number, warn about it
if (success && unexpected_numeric_char(*Mp))
{
error_display(0, "Expected int, found [%.32s].\n", next_tokens(true));
// Rather than back up to str_start, do what retail did and continue
// merrily parsing along at the next character. (Optional numbers
// will still back up to str_start - c.f. a few lines down.)
if (optional)
success = false;
}
if (check_first_non_grayspace_char(Mp, ',', &Mp))
comma = true;
if (optional && !success)
Mp = str_start;
if (success)
{
retval = 2;
diag_printf("Stuffed int: %d\n", *i);
}
else if (optional)
retval = comma ? 1 : 0;
else
skip_token();
return retval;
}
// Stuff a long value pointed at by Mp.
// Advances past integer characters.
int stuff_long(long *l, bool optional)
{
char *str_start = Mp;
// since atol ignores white space anyway, might as well make it explicit
ignore_white_space();
// this is a bit cumbersome
size_t span;
if (*Mp == '+' || *Mp == '-')
{
span = strspn(Mp + 1, "0123456789");
// account for the sign symbol, but not if it's the only valid character
if (span > 0)
++span;
}
else
span = strspn(Mp, "0123456789");
auto result = atol(Mp);
bool success = false, comma = false;
int retval = 0;
// no long found?
if (result == 0 && span == 0)
{
if (!optional)
error_display(1, "Expected long, found [%.32s].\n", next_tokens());
}
else
{
*l = result;
success = true;
}
if (success)
Mp += span;
// if an unexpected character is part of the number, warn about it
if (success && unexpected_numeric_char(*Mp))
{
error_display(0, "Expected long, found [%.32s].\n", next_tokens(true));
// Rather than back up to str_start, do what retail did and continue
// merrily parsing along at the next character. (Optional numbers
// will still back up to str_start - c.f. a few lines down.)
if (optional)
success = false;
}
if (check_first_non_grayspace_char(Mp, ',', &Mp))
comma = true;
if (optional && !success)
Mp = str_start;
if (success)
{
retval = 2;
diag_printf("Stuffed long: %ld\n", *l);
}
else if (optional)
retval = comma ? 1 : 0;
else
skip_token();
return retval;
}
int stuff_float_optional(float *f)
{
return stuff_float(f, true);
}
int stuff_int_optional(int *i)
{
return stuff_int(i, true);
}
// Stuff an integer value pointed at by Mp. If a variable is found instead, stuff the value of that variable and record the
// index of the variable in the following slot.
void stuff_int_or_variable(int *i, int *var_index, bool need_positive_value)
{
if (*Mp == SEXP_VARIABLE_CHAR)
{
int value = -1;
SCP_string str;
auto saved_Mp = Mp;
Mp++;
stuff_string(str, F_NAME);
int index = get_index_sexp_variable_name(str);
if (index > -1 && index < MAX_SEXP_VARIABLES)
{
if (Sexp_variables[index].type & SEXP_VARIABLE_NUMBER)
{
value = atoi(Sexp_variables[index].text);
}
else
{
error_display(1, "Invalid variable type \"%s\" found in mission. Variable must be a number variable!", str.c_str());
}
}
else
{
Mp = saved_Mp;
stuff_string(str, F_NAME);
error_display(1, "Invalid variable name \"%s\" found.", str.c_str());
}
// zero negative values if requested
if (need_positive_value && value < 0)
{
value = 0;
}
// Record the value of the index for FreeSpace
*i = value;
// Record the index itself because we may need it later.
*var_index = index;
}
else
{
stuff_int(i);
// Since we have a numerical value we don't have a SEXP variable index to add for next slot.
*var_index = NOT_SET_BY_SEXP_VARIABLE;
}
}
//Stuffs boolean value.
//Passes things off to stuff_boolean(bool)
void stuff_boolean(int *i, bool a_to_eol)
{
bool tempb;
stuff_boolean(&tempb, a_to_eol);
if(tempb)
*i = 1;
else
*i = 0;
}
void stuff_boolean_flag(int *i, int flag, bool a_to_eol)
{
bool temp;
stuff_boolean(&temp, a_to_eol);
if(temp)
*i |= flag;
else
*i &= ~(flag);
}
// Stuffs a boolean value pointed at by Mp.
// YES/NO (supporting 1/0 now as well)
// Now supports localization :) -WMC
void stuff_boolean(bool *b, bool a_to_eol)
{
char token[NAME_LENGTH];
stuff_string_white(token);
if(a_to_eol)
advance_to_eoln(NULL);
if (!parse_boolean(token, b))
{
*b = false;
error_display(0, "Boolean '%s' type unknown; assuming 'no/false'", token);
}
diag_printf("Stuffed bool: %s\n", (b) ? NOX("true") : NOX("false"));
}
// Parses a token into a boolean value, if the token is recognized. If so, the boolean parameter is assigned the value and the function returns true;
// if not, the boolean parameter is not assigned and the function returns false.
bool parse_boolean(const char *token, bool *b)
{
Assertion(token != nullptr && b != nullptr, "Parameters must not be NULL!");
if(isdigit(token[0]))
{
if(token[0] != '0')
*b = true;
else
*b = false;
return true;
}
else
{
if(!stricmp(token, "yes")
|| !stricmp(token, "true")
|| !stricmp(token, "ja") //German
|| !stricmp(token, "Oui") //French
|| !stricmp(token, "si") //Spanish
|| !stricmp(token, "ita vero") //Latin
|| !stricmp(token, "HIja'") || !stricmp(token, "HISlaH")) //Klingon
{
*b = true;
return true;
}
else if(!stricmp(token, "no")
|| !stricmp(token, "false")
|| !stricmp(token, "nein") //German
|| !stricmp(token, "Non") //French
//I don't know spanish for "no"
//But according to altavista, spanish for "No" is "no"
//Go figure.
|| !stricmp(token, "minime") //Latin
|| !stricmp(token, "ghobe'")) //Klingon
{
*b = false;
return true;
}
}
// token not recognized
return false;
}
// Stuff an integer value (cast to a ubyte) pointed at by Mp.
// Advances past integer characters.
void stuff_ubyte(ubyte *i)
{
int temp;
stuff_int(&temp);
*i = (ubyte)temp;
}
template <typename T, typename F>
void stuff_token_list(SCP_vector<T> &list, F stuff_one_token, const char *type_as_string, bool skip_comma = true)
{
list.clear();
ignore_white_space();
if (*Mp != '(')
{
error_display(1, "Reading %s list. Found [%c]. Expected '('.\n", type_as_string, *Mp);
throw parse::ParseException("Syntax error");
}
Mp++;
while (!check_first_non_whitespace_char(Mp, ')', &Mp))
{
ignore_white_space();
T item;
if (stuff_one_token(&item))
list.push_back(std::move(item));
if (skip_comma)
check_first_non_grayspace_char(Mp, ',', &Mp);
}
}
template <typename T, typename F>
size_t stuff_token_list(T *listp, size_t list_max, F stuff_one_token, const char *type_as_string, bool skip_comma = true)
{
SCP_vector<T> list;
stuff_token_list(list, stuff_one_token, type_as_string, skip_comma);
if (list_max < list.size())
{
error_display(0, "Too many items in %s list. Found " SIZE_T_ARG "; max is " SIZE_T_ARG ". List has been truncated.", type_as_string, list.size(), list_max);
list.resize(list_max);
}
size_t i = 0;
for (const auto &item : list)
listp[i++] = item;
Assert(i == list.size());
return i;
}
// If this data is going to be parsed multiple times (like for mission load), then the dest variable
// needs to be set to zero in between parses, otherwise we keep bad data.
// For tbm files, it must not be reset.
void parse_string_flag_list(int *dest, flag_def_list defs[], size_t defs_size)
{
Assert(dest!=NULL); //wtf?
SCP_vector<SCP_string> slp;
stuff_string_list(slp);
for (auto &str : slp)
{
for (size_t j = 0; j < defs_size; j++)
{
if (!stricmp(str.c_str(), defs[j].name)) {
(*dest) |= defs[j].def;
}
}
}
}
size_t stuff_bool_list(bool *blp, size_t max_bools)
{
return stuff_token_list(blp, max_bools, [](bool *b)->bool {
stuff_boolean(b, false);
return true;
}, "bool");
}
void stuff_string_list(SCP_vector<SCP_string> &slp)
{
stuff_token_list(slp, [](SCP_string *buf)->bool {
if (*Mp != '\"') {
error_display(0, "Missing quotation marks in string list.");
// Since this is a bad token, skip characters until we find a comma, parenthesis, or EOLN
advance_to_eoln(",)");
return false;
}
*buf = "";
get_string(*buf);
return true;
}, "string");
}
size_t stuff_string_list(char slp[][NAME_LENGTH], size_t max_strings)
{
SCP_vector<SCP_string> list;
stuff_string_list(list);
if (max_strings < list.size())
{
error_display(0, "Too many items in %s list. Found " SIZE_T_ARG "; max is " SIZE_T_ARG ". List has been truncated.", "string", list.size(), max_strings);
list.resize(max_strings);
}
for (size_t i = 0; i < list.size(); ++i)
{
if (list[i].size() >= NAME_LENGTH)
{
Warning(LOCATION, "'%s' is too long and will be truncated. Max length is %d.", list[i].c_str(), NAME_LENGTH - 1);
list[i].resize(NAME_LENGTH - 1);
}
strcpy_s(slp[i], list[i].c_str());
}
return list.size();
}
const char* get_lookup_type_name(int lookup_type)
{
switch (lookup_type) {
case SHIP_TYPE:
return "Ships";
case SHIP_INFO_TYPE:
return "Ship Classes";
case WEAPON_POOL_TYPE:
return "Weapon Pool";
case WEAPON_LIST_TYPE:
return "Weapon Types";
case RAW_INTEGER_TYPE:
return "Untyped integer list";
case MISSION_LOADOUT_SHIP_LIST:
return "Mission Loadout Ships";
case MISSION_LOADOUT_WEAPON_LIST:
return "Mission Loadout Weapons";
case CAMPAIGN_LOADOUT_SHIP_LIST:
return "Campaign Loadout Ships";
case CAMPAIGN_LOADOUT_WEAPON_LIST:
return "Campaign Loadout Weapons";
}
return "Unknown lookup type, tell a coder!";
}
// Stuffs an integer list.
// This is of the form ( i* )
// where i is an integer.
// For example, (1) () (1 2 3) ( 1 ) are legal integer lists.
size_t stuff_int_list(int *ilp, size_t max_ints, int lookup_type)
{
return stuff_token_list(ilp, max_ints, [&](int *buf)->bool {
if (*Mp == '"') {
int num = 0;
bool valid_negative = false;
SCP_string str;
get_string(str);
switch (lookup_type) {
case SHIP_TYPE:
num = ship_name_lookup(str.c_str()); // returns index of Ship[] entry with name
if (num < 0)
error_display(0, "Unable to find ship %s in stuff_int_list!", str.c_str());
break;
case SHIP_INFO_TYPE:
num = ship_info_lookup(str.c_str()); // returns index of Ship_info[] entry with name
if (num < 0)
error_display(0, "Unable to find ship class %s in stuff_int_list!", str.c_str());
break;
case WEAPON_POOL_TYPE:
num = weapon_info_lookup(str.c_str());
if (num < 0)
error_display(0, "Unable to find weapon class %s in stuff_int_list!", str.c_str());
break;
case WEAPON_LIST_TYPE:
num = weapon_info_lookup(str.c_str());
if (str.empty())
valid_negative = true;
else if (num < 0)
error_display(0, "Unable to find weapon class %s in stuff_int_list!", str.c_str());
break;
case RAW_INTEGER_TYPE:
num = atoi(str.c_str());
valid_negative = true;
break;
default:
error_display(1, "Unknown lookup_type %d in stuff_int_list", lookup_type);
break;
}
if (num < 0 && !valid_negative)
return false;
*buf = num;
} else {
stuff_int(buf);
}
return true;
}, get_lookup_type_name(lookup_type));
}
// Karajorma/Goober5000 - Stuffs a loadout list by parsing a list of ship or weapon choices.
// Unlike stuff_int_list it can deal with variables
void stuff_loadout_list(SCP_vector<loadout_row> &list, int lookup_type)
{
stuff_token_list(list, [&](loadout_row *buf)->bool {
SCP_string str;
int variable_found = get_string_or_variable(str);
// if we've got a variable get the variable index and copy its value into str so that regardless of whether we found
// a variable or not it now holds the name of the ship or weapon we're interested in.
if (variable_found) {
Assert(lookup_type != CAMPAIGN_LOADOUT_SHIP_LIST);
buf->index_sexp_var = get_index_sexp_variable_name(str);
if (buf->index_sexp_var < 0) {
error_display(1, "Invalid SEXP variable name \"%s\" found in stuff_loadout_list.", str.c_str());
}
str = Sexp_variables[buf->index_sexp_var].text;
}
switch (lookup_type) {
case MISSION_LOADOUT_SHIP_LIST:
case CAMPAIGN_LOADOUT_SHIP_LIST:
buf->index = ship_info_lookup(str.c_str());
break;
case MISSION_LOADOUT_WEAPON_LIST:
case CAMPAIGN_LOADOUT_WEAPON_LIST:
buf->index = weapon_info_lookup(str.c_str());
break;
default:
Assertion(false, "Unsupported lookup type %d", lookup_type);
return false;
}
bool skip_this_entry = false;
// Complain if this isn't a valid ship or weapon and we are loading a mission. Campaign files can be loaded containing
// no ships from the current tables (when swapping mods) so don't report that as an error.
if (buf->index < 0 && (lookup_type == MISSION_LOADOUT_SHIP_LIST || lookup_type == MISSION_LOADOUT_WEAPON_LIST)) {
error_display(0, "Invalid type \"%s\" found in loadout of mission file...skipping", str.c_str());
skip_this_entry = true;
// increment counter for release FRED builds.
Num_unknown_loadout_classes++;
}
else if ((Game_mode & GM_MULTIPLAYER) && (lookup_type == MISSION_LOADOUT_WEAPON_LIST) && (Weapon_info[buf->index].maximum_children_spawned > 300)){
Warning(LOCATION, "Weapon '%s' has more than 300 possible spawned weapons over its lifetime! This can cause issues for Multiplayer.", Weapon_info[buf->index].name);
}
if (!skip_this_entry) {
// similarly, complain if this is a valid ship or weapon class that the player can't use
if ((lookup_type == MISSION_LOADOUT_SHIP_LIST) && (!(Ship_info[buf->index].flags[Ship::Info_Flags::Player_ship])) ) {
error_display(0, "Ship type \"%s\" found in loadout of mission file. This class is not marked as a player ship...skipping", str.c_str());
skip_this_entry = true;
}
else if ((lookup_type == MISSION_LOADOUT_WEAPON_LIST) && (!(Weapon_info[buf->index].wi_flags[Weapon::Info_Flags::Player_allowed])) ) {
nprintf(("Warning", "Warning: Weapon type %s found in loadout of mission file. This class is not marked as a player allowed weapon...skipping\n", str.c_str()));
if ( !Is_standalone )
error_display(0, "Weapon type \"%s\" found in loadout of mission file. This class is not marked as a player allowed weapon...skipping", str.c_str());
skip_this_entry = true;
}
}
// Loadout counts are only needed for missions
if (lookup_type == MISSION_LOADOUT_SHIP_LIST || lookup_type == MISSION_LOADOUT_WEAPON_LIST)
{
ignore_white_space();
// Now read in the number of this type available. The number must be positive
stuff_int_or_variable(&buf->count, &buf->count_sexp_var, true);
}
return !skip_this_entry;
}, get_lookup_type_name(lookup_type));
}
//Stuffs an float list like stuff_int_list.
size_t stuff_float_list(float* flp, size_t max_floats)
{
return stuff_token_list(flp, max_floats, [](float *f)->bool {
stuff_float(f);
return true;
}, "float", false); // don't skip the comma in stuff_token_list because stuff_float also skips one
}
// ditto the above, but a vector of floats...
void stuff_float_list(SCP_vector<float>& flp)
{
stuff_token_list(flp, [](float* buf)->bool {
stuff_float(buf);
return true;
}, "float", false); // don't skip the comma in stuff_token_list because stuff_float also skips one
}
// Stuff a vec2d struct, which is 2 floats.
void stuff_vec2d(vec2d* vp)
{
stuff_float(&vp->x);
stuff_float(&vp->y);
}
// Stuff a vec3d struct, which is 3 floats.
void stuff_vec3d(vec3d *vp)
{
stuff_float(&vp->xyz.x);
stuff_float(&vp->xyz.y);
stuff_float(&vp->xyz.z);
}
void stuff_angles_deg_phb(angles* ap) {
stuff_float(&ap->p);
stuff_float(&ap->h);
stuff_float(&ap->b);
ap->p = fl_radians(ap->p);
ap->h = fl_radians(ap->h);
ap->b = fl_radians(ap->b);
}
void stuff_parenthesized_vec2d(vec2d* vp)
{
ignore_white_space();
if (*Mp != '(') {
error_display(1, "Reading parenthesized vec2d. Found [%c]. Expected '('.\n", *Mp);
throw parse::ParseException("Syntax error");
}
else {
Mp++;
stuff_vec2d(vp);
ignore_white_space();
if (*Mp != ')') {
error_display(1, "Reading parenthesized vec2d. Found [%c]. Expected ')'.\n", *Mp);
throw parse::ParseException("Syntax error");
}
Mp++;
}
}
void stuff_parenthesized_vec3d(vec3d *vp)
{
ignore_white_space();
if (*Mp != '(') {
error_display(1, "Reading parenthesized vec3d. Found [%c]. Expected '('.\n", *Mp);
throw parse::ParseException("Syntax error");
} else {
Mp++;
stuff_vec3d(vp);
ignore_white_space();
if (*Mp != ')') {
error_display(1, "Reading parenthesized vec3d. Found [%c]. Expected ')'.\n", *Mp);
throw parse::ParseException("Syntax error");
}
Mp++;
}
}
// Stuffs vec3d list. *vlp is an array of vec3ds.
// This is of the form ( (vec3d)* )
// (where * is a kleene star, not a pointer indirection)
// For example, ( (1 2 3) (2 3 4) (2 3 5) )
// is a list of three vec3ds.
size_t stuff_vec3d_list(vec3d *vlp, size_t max_vecs)
{
return stuff_token_list(vlp, max_vecs, [](vec3d *buf)->bool {
stuff_parenthesized_vec3d(buf);
return true;
}, "vec3d");
}
// ditto the above, but a vector of vec3ds...
void stuff_vec3d_list(SCP_vector<vec3d> &vec_list)
{
stuff_token_list(vec_list, [](vec3d *buf)->bool {
stuff_parenthesized_vec3d(buf);
return true;
}, "vec3d");
}
// Stuff a matrix, which is 3 vec3ds.
void stuff_matrix(matrix *mp)
{
stuff_vec3d(&mp->vec.rvec);
stuff_vec3d(&mp->vec.uvec);
stuff_vec3d(&mp->vec.fvec);
}
/**
* @brief Given a string, find it in a string array.
*
* @param str1 is the string to be found.
* @param strlist is the list of strings to search.
* @param max is the number of entries in *strlist to scan.
* @param description is only used for diagnostics in case it can't be found.
* @param say_errors @c true if errors should be reported
* @return
*/
int string_lookup(const char *str1, const char* const *strlist, size_t max, const char *description, bool say_errors) {
for (size_t i=0; i<max; i++) {
Assert(strlen(strlist[i]) != 0); //-V805
if (!stricmp(str1, strlist[i]))
return (int)i;
}
if (say_errors)
error_display(0, "Unable to find [%s] in %s list.\n", str1, description);
return -1;
}
// Find a required string (*id), then stuff the text of type f_type that
// follows it at *addr. *strlist[] contains the strings it should try to
// match.
void find_and_stuff(const char *id, int *addr, int f_type, const char *strlist[], size_t max, const char *description)
{
char token[128];
int checking_ship_classes = (stricmp(id, "$class:") == 0);
// Goober5000 - don't say errors when we're checking classes because 1) we have more checking to do; and 2) we will say a redundant error later
required_string(id);
stuff_string(token, f_type, sizeof(token));
*addr = string_lookup(token, strlist, max, description, !checking_ship_classes);
// Goober5000 - handle certain FSPort idiosyncracies with ship classes
if (*addr < 0 && checking_ship_classes)
{
int idx = ship_info_lookup(token);
if (idx >= 0)
*addr = string_lookup(Ship_info[idx].name, strlist, max, description, 0);
else
*addr = -1;
}
}
void find_and_stuff_optional(const char *id, int *addr, int f_type, const char * const *strlist, size_t max, const char *description)
{
char token[128];
if(optional_string(id))
{
stuff_string(token, f_type, sizeof(token));
*addr = string_lookup(token, strlist, max, description, 1);
}
}
// Mp points at a string.
// Find the string in the list of strings *strlist[].
// Returns the index of the match, -1 if none.
int match_and_stuff(int f_type, const char * const *strlist, int max, const char *description)
{
char token[128];
stuff_string(token, f_type, sizeof(token));
return string_lookup(token, strlist, max, description, 0);
}
void find_and_stuff_or_add(const char *id, int *addr, int f_type, char *strlist[], int *total,
int max, const char *description)
{
char token[128];
*addr = -1;
required_string(id);
stuff_string(token, f_type, sizeof(token));
if (*total)
*addr = string_lookup(token, strlist, *total, description, 0);
if (*addr == -1) // not in list, so lets try and add it.
{
Assert(*total < max);
strcpy(strlist[*total], token);
*addr = (*total)++;
}
}
// pause current parsing so that some else can be parsed without interfering
// with the currently parsing file
void pause_parse()
{
Bookmark Mark;
Mark.filename = Current_filename;
Mark.Mp = Mp;
Mark.Warning_count = Warning_count;
Mark.Error_count = Error_count;
Bookmarks.push_back(Mark);
}
// unpause parsing to continue with previously parsing file
void unpause_parse()
{
Assert( !Bookmarks.empty() );
if (Bookmarks.empty())
return;
Bookmark Mark = Bookmarks.back();
Mp = Mark.Mp;
Warning_count = Mark.Warning_count;
Error_count = Mark.Error_count;
strcpy_s(Current_filename, Mark.filename.c_str());
Bookmarks.pop_back();
}
void reset_parse(char *text)
{
if (text != NULL) {
Mp = text;
} else {
Mp = Parse_text;
}
Warning_count = 0;
Error_count = 0;
strcpy_s(Current_filename, Current_filename_sub);
}
// Display number of warnings and errors at the end of a parse.
void display_parse_diagnostics()
{
nprintf(("Parse", "\nParse complete.\n"));
nprintf(("Parse", "%i errors. %i warnings.\n", Error_count, Warning_count));
}
// Splits a string into 2 lines if the string is wider than max_pixel_w pixels. A null
// terminator is placed where required to make the first line <= max_pixel_w. The remaining
// text is returned (leading whitespace removed). If the line doesn't need to be split,
// NULL is returned.
char *split_str_once(char *src, int max_pixel_w)
{
char *brk = nullptr;
int i, w, len;
bool last_was_white = false;
Assert(src);
if (max_pixel_w <= 0)
return src; // if there's no width, skip everything else
gr_get_string_size(&w, nullptr, src);
if ( (w <= max_pixel_w) && !strstr(src, "\n") ) {
return nullptr; // string doesn't require a cut
}
len = (int)strlen(src);
for (i=0; i<len; i++) {
gr_get_string_size(&w, nullptr, src, i + 1);
if (w <= max_pixel_w) {
if (src[i] == '\n') { // reached natural end of line
src[i] = 0;
return src + i + 1;
}
}
if (is_white_space(src[i])) {
if (!last_was_white) {
// only update the line break if:
// a) we don't have a line break yet;
// b) we're still within the required real estate
// (basically we want the latest line break that doesn't go off the edge of the screen,
// but if the *first* line break is off the end of the screen, we want that)
if (brk == nullptr || w <= max_pixel_w) {
brk = src + i;
}
}
last_was_white = true;
} else {
last_was_white = false;
}
}
// if we are over max pixel width and weren't able to come up with a good non-word
// split then just return the original src text and the calling function should
// have to handle the result
if ( (w > max_pixel_w) && ((i == 0) || !brk) ) {
return src;
}
if (!brk) {
brk = src + i;
}
*brk = 0;
src = brk + 1;
while (is_white_space(*src))
src++;
if (!*src)
return nullptr; // end of the string anyway
if (*src == '\n')
src++;
return src;
}
#define SPLIT_STR_BUFFER_SIZE 512
// --------------------------------------------------------------------------------------
// split_str()
//
// A general function that will split a string into several lines. Lines are allowed up
// to max_pixel_w pixels. Breaks are found in white space.
//
// Supports \n's in the strings!
//
// parameters: src => source string to be broken up
// max_pixel_w => max width of line in pixels
// n_chars => output array that will hold number of characters in each line
// p_str => output array of pointers to start of lines within src
// max_lines => limit of number of lines to break src up into
// ignore_char => OPTIONAL parameter (default val -1). Ignore words starting with this character
// This is useful when you want to ignore embedded control information that starts
// with a specific character, like $ or #
//
// returns: number of lines src is broken into
// -1 is returned when an error occurs
//
int split_str(const char *src, int max_pixel_w, int *n_chars, const char **p_str, int max_lines, int max_line_length, unicode::codepoint_t ignore_char, bool strip_leading_whitespace)
{
char buffer[SPLIT_STR_BUFFER_SIZE];
const char *breakpoint = NULL;
int sw, new_line = 1, line_num = 0, last_was_white = 0;
int ignore_until_whitespace, buf_index;
// check our assumptions..
Assert(src != NULL);
Assert(n_chars != NULL);
Assert(p_str != NULL);
Assert(max_lines > 0);
Assert(max_pixel_w > 0);
Assertion(max_line_length > 0, "Max line length should be >0, not %d; get a coder!\n", max_line_length);
memset(buffer, 0, sizeof(buffer));
buf_index = 0;
ignore_until_whitespace = 0;
// get rid of any leading whitespace
while (strip_leading_whitespace && is_white_space(*src))
src++;
new_line = 1;
p_str[0] = NULL;
// iterate through chars in line, keeping track of most recent "white space" location that can be used
// as a line splitting point if necessary
unicode::codepoint_range range(src);
auto end_iter = std::end(range);
auto iter = std::begin(range);
for (; iter != end_iter; ++iter) {
auto cp = *iter;
if (line_num >= max_lines)
return line_num; // time to bail out
// starting a new line of text, init stuff for that
if (new_line) {
p_str[line_num] = NULL;
if (strip_leading_whitespace && is_gray_space(cp))
continue;
p_str[line_num] = iter.pos();
breakpoint = NULL;
new_line = 0;
}
// maybe skip leading whitespace
if (ignore_until_whitespace) {
if ( is_white_space(cp) )
ignore_until_whitespace = 0;
continue;
}
// if we have a newline, split the line here
if (cp == UNICODE_CHAR('\n')) {
n_chars[line_num] = (int)(iter.pos() - p_str[line_num]); // track length of line
line_num++;
if (line_num < max_lines) {
p_str[line_num] = NULL;
}
new_line = 1;
memset(buffer, 0, SPLIT_STR_BUFFER_SIZE);
buf_index = 0;
continue;
}
if (cp == ignore_char) {
ignore_until_whitespace = 1;
continue;
}
if (is_gray_space(cp)) {
if (!last_was_white) // track at first whitespace in a series of whitespace
breakpoint = iter.pos();
last_was_white = 1;
} else {
// indicate next time around that this wasn't a whitespace character
last_was_white = 0;
}
auto encoded_width = unicode::encoded_size(cp);
Assertion(buf_index + encoded_width < SPLIT_STR_BUFFER_SIZE,
"buffer overflow in split_str: screen width causes this text to be longer than %d characters!",
SPLIT_STR_BUFFER_SIZE - 1);
// throw it in our buffer
unicode::encode(cp, &buffer[buf_index]);
buf_index += (int)encoded_width;
buffer[buf_index] = 0; // null terminate it
gr_get_string_size(&sw, NULL, buffer);
if (sw >= max_pixel_w || buf_index >= max_line_length) {
const char *end;
if (breakpoint) {
end = breakpoint;
iter = unicode::text_iterator(breakpoint, src, src + strlen(src));
} else {
end = iter.pos(); // force a split here since to whitespace
--iter; // reuse this character in next line
}
n_chars[line_num] = (int)(end - p_str[line_num]); // track length of line
Assert(n_chars[line_num]);
line_num++;
if (line_num < max_lines) {
p_str[line_num] = NULL;
}
new_line = 1;
memset(buffer, 0, sizeof(buffer));
buf_index = 0;
continue;
}
} // end for
if (!new_line && p_str[line_num]) {
n_chars[line_num] = (int)(iter.pos() - p_str[line_num]); // track length of line
Assert(n_chars[line_num]);
line_num++;
}
return line_num;
}
int split_str(const char *src, int max_pixel_w, SCP_vector<int> &n_chars, SCP_vector<const char*> &p_str, int max_line_length, unicode::codepoint_t ignore_char, bool strip_leading_whitespace)
{
char buffer[SPLIT_STR_BUFFER_SIZE];
const char *breakpoint = NULL;
int sw, new_line = 1, line_num = 0, last_was_white = 0;
int ignore_until_whitespace = 0, buf_index = 0;
// check our assumptions..
Assert(src != NULL);
Assert(max_pixel_w > 0);
Assertion(max_line_length > 0, "Max line length should be >0, not %d; get a coder!\n", max_line_length);
memset(buffer, 0, sizeof(buffer));
// get rid of any leading whitespace
while (strip_leading_whitespace && is_white_space(*src))
src++;
p_str.clear();
// iterate through chars in line, keeping track of most recent "white space" location that can be used
// as a line splitting point if necessary
unicode::codepoint_range range(src);
auto end_iter = std::end(range);
auto iter = std::begin(range);
for (; iter != end_iter; ++iter) {
auto cp = *iter;
// starting a new line of text, init stuff for that
if (new_line) {
if (strip_leading_whitespace && is_gray_space(cp))
continue;
p_str.push_back(iter.pos());
breakpoint = NULL;
new_line = 0;
}
// maybe skip leading whitespace
if (ignore_until_whitespace) {
if ( is_white_space(cp) ) {
ignore_until_whitespace = 0;
// don't eat the newline
if (cp == EOLN)
--iter;
}
continue;
}
// if we have a newline, split the line here
if (cp == UNICODE_CHAR('\n')) {
n_chars.push_back((int)(iter.pos() - p_str[line_num])); // track length of line
line_num++;
new_line = 1;
memset(buffer, 0, SPLIT_STR_BUFFER_SIZE);
buf_index = 0;
continue;
}
if (cp == ignore_char) {
ignore_until_whitespace = 1;
continue;
}
if (is_gray_space(cp)) {
if (!last_was_white) // track at first whitespace in a series of whitespace
breakpoint = iter.pos();
last_was_white = 1;
} else {
// indicate next time around that this wasn't a whitespace character
last_was_white = 0;
}
auto encoded_width = unicode::encoded_size(cp);
Assertion(buf_index + encoded_width < SPLIT_STR_BUFFER_SIZE,
"buffer overflow in split_str: screen width causes this text to be longer than %d characters!",
SPLIT_STR_BUFFER_SIZE - 1);
// throw it in our buffer
unicode::encode(cp, &buffer[buf_index]);
buf_index += (int)encoded_width;
buffer[buf_index] = 0; // null terminate it
gr_get_string_size(&sw, NULL, buffer);
if (sw >= max_pixel_w || buf_index >= max_line_length) {
const char *end;
if (breakpoint) {
end = breakpoint;
iter = unicode::text_iterator(breakpoint, src, src + strlen(src));
} else {
end = iter.pos(); // force a split here since to whitespace
--iter; // reuse this character in next line
}
n_chars.push_back((int)(end - p_str[line_num])); // track length of line
Assert(n_chars[line_num]);
line_num++;
new_line = 1;
memset(buffer, 0, sizeof(buffer));
buf_index = 0;
continue;
}
} // end for
if (!new_line && p_str[line_num]) {
n_chars.push_back((int)(iter.pos() - p_str[line_num])); // track length of line
Assert(n_chars[line_num]);
line_num++;
}
return line_num;
}
// A narrower but much faster alternative to split_str(), takes a string and a max pixel length, returns a vector with
// one string per line. Does not currently support a max line count or ignoring of characters.
SCP_vector<SCP_string>
str_wrap_to_width(const SCP_string& source_string, int max_pixel_length, bool strip_leading_whitespace)
{
// To avoid any unexpected side effects, we're copying the orignal string.
SCP_string new_string = SCP_string(source_string);
SCP_vector<SCP_string> lines = SCP_vector<SCP_string>();
while (strip_leading_whitespace && !new_string.empty() && is_white_space(new_string[0])) {
new_string.erase(0, 1);
}
if (new_string.empty())
return lines;
// Handle existing line breaks in the string recursively, then append the results.
auto newline_at = new_string.find_first_of(UNICODE_CHAR('\n'));
while (!new_string.empty() && newline_at < std::string::npos) {
if (newline_at == 0) {
// No content to split so just pushing a new string on.
lines.emplace_back();
} else {
SCP_vector<SCP_string> sublines =
str_wrap_to_width(new_string.substr(0, newline_at), max_pixel_length, strip_leading_whitespace);
for (auto line : sublines) {
lines.emplace_back(line);
}
}
new_string.erase(0, newline_at + 1);
newline_at = new_string.find_first_of(UNICODE_CHAR('\n'));
}
// With newlines handled, now moving into actually wrapping the content.
while (!new_string.empty()) {
auto split_at = std::string::npos;
// no newlines found, check length.
size_t stringlen = new_string.length();
int linelen = 0;
gr_get_string_size(&linelen, nullptr, new_string.c_str());
if (stringlen <= 1) {
// in this case checking is pointless, single-character strings can't wrap.
// copy into the return vector and then bail.
lines.emplace_back(new_string.c_str());
break;
} else if (linelen < max_pixel_length) {
// The remaining string is shorter than our limit so we're done.
// copy into the return vector and then bail.
lines.emplace_back(new_string.c_str());
break;
} else {
size_t search_min = 0;
size_t search_max = stringlen;
size_t center = 0;
while ((search_max - search_min) > 0) {
center = search_min + ((search_max - search_min) / 2);
gr_get_string_size(&linelen, nullptr, new_string.substr(0, center).c_str());
if (linelen == max_pixel_length) {
search_max = center;
search_min = center;
split_at = center;
} else if (linelen > max_pixel_length) {
search_max = MIN(center, search_max - 1);
split_at = search_max;
} else {
search_min = MAX(center, search_min + 1);
split_at = search_min;
}
}
}
if (split_at >= stringlen) { // don't split out of bounds
split_at = stringlen - 1;
}
if (split_at <= 0) {
// we need to always remove something from the current line or we're stuck
split_at = 1;
} else if (!is_white_space(new_string.at(split_at))) {
// split_at is now the last point where we can split, but could be mid-word
// work backwards to find whitespace.
for (int n = ((int)split_at) - 1; n >= 0; n--) {
if (is_white_space(new_string.at(n))) {
split_at = (size_t)n;
n = -1;
}
}
}
lines.emplace_back(new_string.substr(0, split_at));
new_string.erase(0, split_at);
// To trim the front whitespace off the next line
while (!new_string.empty() && is_white_space(new_string[0])) {
new_string.erase(0, 1);
}
}
return lines;
}
SCP_vector<SCP_string> str_wrap_to_width(const char* source_string, int max_pixel_length, bool strip_leading_whitespace)
{
// SCP_string temp = SCP_string(source_string);
return str_wrap_to_width(SCP_string(source_string), max_pixel_length, strip_leading_whitespace);
}
// Goober5000
// accounts for the dumb communications != communication, etc.
int subsystem_stricmp(const char *str1, const char *str2)
{
Assert(str1 && str2);
// ensure len-1 will be valid
if (!*str1 || !*str2)
return stricmp(str1, str2);
// calc lengths
auto len1 = (int)strlen(str1);
auto len2 = (int)strlen(str2);
// get rid of trailing s on s1?
if (SCP_tolower(*(str1+len1-1)) == 's')
len1--;
// get rid of trailing s on s2?
if (SCP_tolower(*(str2+len2-1)) == 's')
len2--;
// once we remove the trailing s on both names, they should be the same length
if (len1 == len2)
return strnicmp(str1, str2, len1);
// if not, just do a regular comparison
return stricmp(str1, str2);
}
// Goober5000
// current algorithm adapted from http://www.codeproject.com/string/stringsearch.asp
const char *stristr(const char *str, const char *substr)
{
// check for null and insanity
Assert(str);
Assert(substr);
if (str == NULL || substr == NULL || *substr == '\0')
return NULL;
// save both a lowercase and an uppercase version of the first character of substr
char substr_ch_lower = SCP_tolower(*substr);
char substr_ch_upper = SCP_toupper(*substr);
// find the maximum distance to search
const char *upper_bound = str + strlen(str) - strlen(substr);
// loop through every character of str
for (const char *start = str; start <= upper_bound; start++)
{
// check first character of substr
if ((*start == substr_ch_upper) || (*start == substr_ch_lower))
{
// first character matched, so check the rest
for (const char *str_ch = start+1, *substr_ch = substr+1; *substr_ch != '\0'; str_ch++, substr_ch++)
{
// character match?
if (*str_ch == *substr_ch)
continue;
// converted character match?
if (SCP_tolower(*str_ch) == SCP_tolower(*substr_ch))
continue;
// mismatch
goto stristr_continue_outer_loop;
}
// finished inner loop with success!
return start;
}
stristr_continue_outer_loop:
/* NO-OP */ ;
}
// no match
return NULL;
}
// non-const version
char *stristr(char *str, const char *substr)
{
// check for null and insanity
Assert(str);
Assert(substr);
if (str == NULL || substr == NULL || *substr == '\0')
return NULL;
// save both a lowercase and an uppercase version of the first character of substr
char substr_ch_lower = SCP_tolower(*substr);
char substr_ch_upper = SCP_toupper(*substr);
// find the maximum distance to search
const char *upper_bound = str + strlen(str) - strlen(substr);
// loop through every character of str
for (char *start = str; start <= upper_bound; start++)
{
// check first character of substr
if ((*start == substr_ch_upper) || (*start == substr_ch_lower))
{
// first character matched, so check the rest
for (const char *str_ch = start+1, *substr_ch = substr+1; *substr_ch != '\0'; str_ch++, substr_ch++)
{
// character match?
if (*str_ch == *substr_ch)
continue;
// converted character match?
if (SCP_tolower(*str_ch) == SCP_tolower(*substr_ch))
continue;
// mismatch
goto stristr_continue_outer_loop;
}
// finished inner loop with success!
return start;
}
stristr_continue_outer_loop:
/* NO-OP */ ;
}
// no match
return NULL;
}
// Goober5000
bool can_construe_as_integer(const char *text)
{
// trivial case; evaluates to 0
if (*text == '\0')
return true;
// number sign or digit for first char
if ((*text != '+') && (*text != '-') && !isdigit(*text))
return false;
// check digits for rest
for (const char *p = text + 1; *p != '\0'; p++)
{
if (!isdigit(*p))
return false;
}
return true;
}
// Goober5000
// yoinked gratefully from dbugfile.cpp
void vsprintf(SCP_string &dest, const char *format, va_list ap)
{
va_list copy;
#if defined(_MSC_VER) && _MSC_VER < 1800
// Only Visual Studio >= 2013 supports va_copy
// This isn't portable but should work for Visual Studio
copy = ap;
#else
va_copy(copy, ap);
#endif
int needed_length = vsnprintf(nullptr, 0, format, copy);
va_end(copy);
if (needed_length < 0) {
// Error
return;
}
dest.resize(static_cast<size_t>(needed_length));
vsnprintf(&dest[0], dest.size() + 1, format, ap);
}
void sprintf(SCP_string &dest, const char *format, ...)
{
va_list args;
va_start(args, format);
vsprintf(dest, format, args);
va_end(args);
}
// Goober5000
bool end_string_at_first_hash_symbol(char *src, bool ignore_doubled_hash)
{
char *p;
Assert(src);
p = get_pointer_to_first_hash_symbol(src, ignore_doubled_hash);
if (p)
{
while ((p != src) && (*(p-1) == ' '))
p--;
*p = '\0';
return true;
}
return false;
}
// Goober5000
bool end_string_at_first_hash_symbol(SCP_string &src, bool ignore_doubled_hash)
{
int index = get_index_of_first_hash_symbol(src, ignore_doubled_hash);
if (index >= 0)
{
while (index > 0 && src[index-1] == ' ')
index--;
src.resize(index);
return true;
}
return false;
}
// Goober5000
char *get_pointer_to_first_hash_symbol(char *src, bool ignore_doubled_hash)
{
Assert(src);
if (ignore_doubled_hash)
{
for (auto ch = src; *ch; ++ch)
{
if (*ch == '#')
{
if (*(ch + 1) == '#')
++ch;
else
return ch;
}
}
return nullptr;
}
else
return strchr(src, '#');
}
// Goober5000
const char *get_pointer_to_first_hash_symbol(const char *src, bool ignore_doubled_hash)
{
Assert(src);
if (ignore_doubled_hash)
{
for (auto ch = src; *ch; ++ch)
{
if (*ch == '#')
{
if (*(ch + 1) == '#')
++ch;
else
return ch;
}
}
return nullptr;
}
else
return strchr(src, '#');
}
// Goober5000
int get_index_of_first_hash_symbol(SCP_string &src, bool ignore_doubled_hash)
{
if (ignore_doubled_hash)
{
for (auto ch = src.begin(); ch != src.end(); ++ch)
{
if (*ch == '#')
{
if ((ch + 1) != src.end() && *(ch + 1) == '#')
++ch;
else
return (int)std::distance(src.begin(), ch);
}
}
return -1;
}
else
{
size_t pos = src.find('#');
return (pos == SCP_string::npos) ? -1 : (int)pos;
}
}
// Goober5000
// Used for escape sequences: ## to #, !! to !, etc.
void consolidate_double_characters(char *src, char ch)
{
auto dest = src;
while (*src)
{
if (*src == ch && *(src + 1) == ch)
dest--;
++src;
++dest;
if (src != dest)
*dest = *src;
}
}
char *three_dot_truncate(char *buffer, const char *source, size_t buffer_size)
{
Assertion(buffer && source, "Arguments must not be null!");
// this would be silly
if (buffer_size < 6)
{
*buffer = '\0';
return buffer;
}
strncpy(buffer, source, buffer_size);
if (buffer[buffer_size - 1] != '\0')
strcpy(&buffer[buffer_size - 6], "[...]");
return buffer;
}
// Goober5000
// Returns position of replacement, or a negative value if replacement failed: -1 if search string was not found, -2 if replacement would exceed max length, or -3 if any string argument is null
// Note that the parameter here is max *length*, not max buffer size. Leave room for the null-terminator!
ptrdiff_t replace_one(char *str, const char *oldstr, const char *newstr, size_t max_len, ptrdiff_t range)
{
Assertion(str && oldstr && newstr, "Arguments must not be null!");
Assertion(max_len < SIZE_MAX, "Size must be less than SIZE_MAX because an extra char is added for the null terminator.");
if (!str || !oldstr || !newstr || max_len == SIZE_MAX)
return -3;
// search
char *ch = stristr(str, oldstr);
// found?
if (ch)
{
// not found within bounds?
if ((range > 0) && ((ch - str) > range))
{
return -1;
}
// determine if replacement will exceed max len
if (strlen(str) + strlen(newstr) - strlen(oldstr) > max_len)
{
return -2;
}
// allocate temp string to hold extra stuff
char *temp = (char *) vm_malloc(sizeof(char) * (max_len + 1));
// ensure allocation was successful
if (temp)
{
// save remainder of string
strcpy(temp, ch + strlen(oldstr));
// replace
strcpy(ch, newstr);
// append rest of string
strcpy(ch + strlen(newstr), temp);
}
// free temp string
vm_free(temp);
}
// not found
else
{
return -1;
}
// return pos of replacement
return (ch - str);
}
// Goober5000
// Returns number of replacements or a negative result from replace_one if a replacement failed for some reason other than not found
// Note that the parameter here is max *length*, not max buffer size. Leave room for the null-terminator!
int replace_all(char *str, const char *oldstr, const char *newstr, size_t max_len, ptrdiff_t range)
{
ptrdiff_t val;
int tally = 0;
while ((val = replace_one(str, oldstr, newstr, max_len, range)) >= 0)
{
tally++;
// adjust range (if we have one), because the text length might have changed
if (range) {
range += strlen(newstr) - strlen(oldstr);
}
}
// return the tally, even if it's 0, unless there was an exceptional situation like exceeding max len
return (val < -1) ? (int)val : tally;
}
// Goober5000
// Returns position of replacement, or -1 if search string was not found
ptrdiff_t replace_one(SCP_string& context, const SCP_string& from, const SCP_string& to)
{
size_t foundHere;
if ((foundHere = context.find(from, 0)) != SCP_string::npos)
{
context.replace(foundHere, from.length(), to);
return foundHere;
}
else
return -1;
}
// Goober5000
// Returns position of replacement, or -1 if search string was not found
ptrdiff_t replace_one(SCP_string& context, const char* from, const char* to)
{
size_t foundHere;
if ((foundHere = context.find(from, 0)) != SCP_string::npos)
{
context.replace(foundHere, strlen(from), to);
return foundHere;
}
else
return -1;
}
// Goober5000
// Returns number of replacements
// http://www.cppreference.com/wiki/string/replace
int replace_all(SCP_string& context, const SCP_string& from, const SCP_string& to)
{
size_t from_len = from.length();
size_t to_len = to.length();
size_t lookHere = 0;
size_t foundHere;
int tally = 0;
while ((foundHere = context.find(from, lookHere)) != SCP_string::npos)
{
tally++;
context.replace(foundHere, from_len, to);
lookHere = foundHere + to_len;
}
return tally;
}
// Goober5000
// Returns number of replacements
// http://www.cppreference.com/wiki/string/replace
int replace_all(SCP_string& context, const char* from, const char* to)
{
size_t from_len = strlen(from);
size_t to_len = strlen(to);
size_t lookHere = 0;
size_t foundHere;
int tally = 0;
while ((foundHere = context.find(from, lookHere)) != SCP_string::npos)
{
tally++;
context.replace(foundHere, from_len, to);
lookHere = foundHere + to_len;
}
return tally;
}
// WMC
// Compares two strings, ignoring (last) extension
// Returns 0 if equal, nonzero if not
int strextcmp(const char *s1, const char *s2)
{
// sanity check
Assert( (s1 != NULL) && (s2 != NULL) );
// find last '.' in both strings
char *s1_end = (char *)strrchr(s1, '.');
char *s2_end = (char *)strrchr(s2, '.');
// get length
size_t s1_len, s2_len;
if (s1_end != NULL)
s1_len = (s1_end - s1);
else
s1_len = strlen(s1);
if (s2_end != NULL)
s2_len = (s2_end - s2);
else
s2_len = strlen(s2);
// if the lengths aren't the same then it's deffinitely not the same name
if (s2_len != s1_len)
return 1;
return strnicmp(s1, s2, s1_len);
}
// Goober5000
bool drop_extension(char *str)
{
char *p = strrchr(str, '.');
if (p != NULL)
{
*p = 0;
return true;
}
return false;
}
// Goober5000
bool drop_extension(SCP_string &str)
{
size_t pos = str.rfind('.');
if (pos != SCP_string::npos)
{
str.resize(pos);
return true;
}
return false;
}
//WMC
void backspace(char* src)
{
Assert(src!= NULL); //this would be bad
char *dest = src;
src++;
while(*src != '\0') {
*dest++ = *src++;
}
*dest = '\0';
}
// Goober5000
void format_integer_with_commas(char *buf, int integer, bool use_comma_with_four_digits)
{
int old_pos, new_pos, triad_count;
char backward_buf[32];
// print an initial string of just the digits
sprintf(buf, "%d", integer);
// no commas needed?
if ((integer < 1000) || (integer < 10000 && !use_comma_with_four_digits))
return;
// scan the string backwards, writing commas after every third digit
new_pos = 0;
triad_count = 0;
for (old_pos = (int)strlen(buf) - 1; old_pos >= 0; old_pos--)
{
backward_buf[new_pos] = buf[old_pos];
new_pos++;
triad_count++;
if (triad_count == 3 && old_pos > 0)
{
backward_buf[new_pos] = ',';
new_pos++;
triad_count = 0;
}
}
backward_buf[new_pos] = '\0';
// now reverse the string
new_pos = 0;
for (old_pos = (int)strlen(backward_buf) - 1; old_pos >= 0; old_pos--)
{
buf[new_pos] = backward_buf[old_pos];
new_pos++;
}
buf[new_pos] = '\0';
}
// Goober5000
// there's probably a better way to do this, but this way works and is clear and short
int scan_fso_version_string(const char *text, int *major, int *minor, int *build, int *revis)
{
int val;
val = sscanf(text, ";;FSO %i.%i.%i.%i;;", major, minor, build, revis);
if (val == 4)
return val;
*revis = 0;
val = sscanf(text, ";;FSO %i.%i.%i;;", major, minor, build);
if (val == 3)
return val;
*build = *revis = 0;
val = sscanf(text, ";;FSO %i.%i;;", major, minor);
if (val == 2)
return val;
*minor = *build = *revis = 0;
val = sscanf(text, ";;FSO %i;;", major);
if (val == 1)
return val;
*major = *minor = *build = *revis = 0;
return 0;
}
// Goober5000 - used for long Warnings, Errors, and FRED error messages with SEXPs
void truncate_message_lines(SCP_string &text, int num_allowed_lines)
{
Assert(num_allowed_lines > 0);
size_t find_from = 0;
while (find_from < text.size())
{
if (num_allowed_lines <= 0)
{
text.resize(find_from);
text.append("[...]");
break;
}
size_t pos = text.find('\n', find_from);
if (pos == SCP_string::npos)
break;
num_allowed_lines--;
find_from = pos + 1;
}
}
// Goober5000 - ugh, I can't see why they didn't just use stuff_*_list for these;
// the only difference is the lack of parentheses
// from aicode.cpp
// Stuff a list of floats at *plist.
void parse_float_list(float *plist, size_t size)
{
for (size_t i=0; i<size; i++)
{
stuff_float(&plist[i]);
}
}
// from aicode.cpp
// Stuff a list of ints at *plist.
void parse_int_list(int *ilist, size_t size)
{
for (size_t i=0; i<size; i++)
{
stuff_int(&ilist[i]);
}
}
void parse_string_map(SCP_map<SCP_string, SCP_string>& outMap, const char* end_marker, const char* entry_prefix)
{
while(optional_string(entry_prefix))
{
SCP_string temp;
stuff_string(temp, F_RAW);
drop_white_space(temp);
if (temp.empty())
{
Warning(LOCATION, "Empty entry in string map.");
continue;
}
size_t sep = temp.find_first_of(' ');
SCP_string key = temp.substr(0, sep);
SCP_string value = temp.substr(sep+1);
//if the modder didn't add a value, make the value an empty string. (Without this, value would instead be an identical string to key)
if (sep == SCP_string::npos)
value = "";
drop_white_space(key);
drop_white_space(value);
outMap.emplace(key, value);
}
required_string(end_marker);
}
// parse a modular table of type "name_check" and parse it using the specified function callback
int parse_modular_table(const char *name_check, void (*parse_callback)(const char *filename), int path_type, int sort_type)
{
SCP_vector<SCP_string> tbl_file_names;
int i, num_files = 0;
if ( (name_check == NULL) || (parse_callback == NULL) || ((*name_check) != '*') ) {
UNREACHABLE("parse_modular_table() called with invalid arguments; get a coder!\n");
return 0;
}
num_files = cf_get_file_list(tbl_file_names, path_type, name_check, sort_type);
Parsing_modular_table = true;
const auto ext = strrchr(name_check, '.');
for (i = 0; i < num_files; i++){
if (ext != nullptr) {
tbl_file_names[i] += ext;
}
mprintf(("TBM => Starting parse of '%s' ...\n", tbl_file_names[i].c_str()));
(*parse_callback)(tbl_file_names[i].c_str());
}
Parsing_modular_table = false;
return num_files;
}
|