1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003
|
/* ################################################################### */
/* Copyright 2015, Pierre Gentile (p.gen.progs@gmail.com) */
/* */
/* This Source Code Form is subject to the terms of the Mozilla Public */
/* License, v. 2.0. If a copy of the MPL was not distributed with this */
/* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
/* ################################################################### */
#include <errno.h>
#include <stddef.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/types.h>
#include <regex.h>
#include <stdarg.h>
#include <string.h>
#include "ctxopt.h"
/* ************************ */
/* Static global variables. */
/* ************************ */
static void *contexts_bst;
static void *options_bst;
state_t *cur_state;
/* Prototypes */
/* ************************** */
/* Fatal messages prototypes. */
/* ************************** */
static void (**err_functions)(errors e, state_t *state);
static void
fatal_internal(const char *format, ...);
static void
fatal(errors e, char *errmsg);
static int user_rc; /* Used by various callback functions. */
static int user_value; /* Used by various callback functions. */
static char *user_string; /* Used by various callback functions. */
static char *user_string2; /* Used by various callback functions. */
static void *user_object; /* Used by various callback functions. */
/* ************************************ */
/* Memory management static prototypes. */
/* ************************************ */
static void *
xmalloc(size_t size);
static void *
xcalloc(size_t num, size_t size);
static void *
xrealloc(void *ptr, size_t size);
static char *
xstrdup(const char *p);
static char *
xstrndup(const char *str, size_t len);
/* ********************** */
/* BST static prototypes. */
/* ********************** */
typedef struct bst_s bst_t;
typedef enum
{
preorder,
postorder,
endorder,
leaf
} walk_order_e;
#if 0 /* Unused yet. */
static void *
bst_delete(const void * vkey, void ** vrootp,
int (*compar)(const void *, const void *));
#endif
static void
bst_destroy(void *vrootp, void (*clean)(void *));
static void *
bst_find(const void *vkey,
void * const *vrootp,
int (*compar)(const void *, const void *));
static void *
bst_search(void *vkey,
void **vrootp,
int (*compar)(const void *, const void *));
static void
bst_walk_recurse(const bst_t *root,
void (*action)(const void *, walk_order_e, int),
int level);
static void
bst_walk(const void *vroot, void (*action)(const void *, walk_order_e, int));
/* ****************************** */
/* Linked list static prototypes. */
/* ****************************** */
typedef struct ll_node_s ll_node_t;
typedef struct ll_s ll_t;
static void
ll_append(ll_t * const list, void * const data);
static void
ll_prepend(ll_t * const list, void * const data);
static void
ll_insert_after(ll_t * const list, ll_node_t *node, void * const data);
static void
ll_insert_before(ll_t * const list, ll_node_t *node, void * const data);
static int
ll_delete(ll_t * const list, ll_node_t *node);
static void
ll_init(ll_t *list);
static ll_node_t *
ll_new_node(void);
static ll_t *
ll_new(void);
static void
ll_free(ll_t * const list, void (*)(void *));
static void
ll_destroy(ll_t * const list, void (*)(void *));
static int
ll_strarray(ll_t *list, ll_node_t *start_node, int *count, char ***array);
/* ************************** */
/* Various static prototypes. */
/* ************************** */
static void
ltrim(char *str, const char *trim_str);
static void
rtrim(char *str, const char *trim_str, size_t min);
static int
strchrcount(char *str, char c);
static int
strpref(char *s1, char *s2);
static int
stricmp(const char *s1, const char *s2);
static char *
xstrtok_r(char *str, const char *delim, char **end);
static int
eval_yes(char *value, int *invalid);
static char *
get_word(char *str, char *buf, size_t len);
/* ************************* */
/* ctxopt static prototypes. */
/* ************************* */
typedef struct flags_s flags_t;
typedef struct opt_s opt_t;
typedef struct par_s par_t;
typedef struct ctx_s ctx_t;
typedef struct constraint_s constraint_t;
typedef struct ctx_inst_s ctx_inst_t;
typedef struct opt_inst_s opt_inst_t;
typedef struct seen_opt_s seen_opt_t;
typedef struct req_s req_t;
static char *
strtoken(char *s, char *token, size_t tok_len, char *pattern, int *pos);
static int
ctx_compare(const void *c1, const void *c2);
static void
ctx_free(void *o);
static void
ctx_inst_free(void *ci);
static void
opt_inst_free(void *oi);
static int
seen_opt_compare(const void *so1, const void *so2);
static void
incomp_bst_free(void *b);
static void
req_free(void *r);
static void
seen_opt_free(void *seen_opt);
static int
opt_compare(const void *o1, const void *o2);
static void
opt_free(void *o);
static int
par_compare(const void *a1, const void *a2);
static void
par_free(void *p);
static void
constraint_free(void *cstr);
static ctx_t *
locate_ctx(char *name);
static opt_t *
locate_opt(char *name);
static par_t *
locate_par(char *name, ctx_t *ctx);
static void
print_before_constraints(ll_t *list);
static void
print_options(ll_t *list,
int *has_optional,
int *has_ellipsis,
int *has_rule,
int *has_generic_arg,
int *has_ctx_change,
int *has_early_eval);
static void
print_explanations(int has_early_eval,
int has_ctx_change,
int has_generic_arg,
int has_optional,
int has_ellipsis,
int has_rule);
static void
bst_seen_opt_cb(const void *node, walk_order_e kind, int level);
static void
bst_seen_opt_seen_cb(const void *node, walk_order_e kind, int level);
static void
bst_print_ctx_cb(const void *node, walk_order_e kind, int level);
static void
bst_check_opt_cb(const void *node, walk_order_e kind, int level);
static void
bst_match_par_cb(const void *node, walk_order_e kind, int level);
static void
match_prefix_cb(const void *node, walk_order_e kind, int level);
static int
has_unseen_mandatory_opt(ctx_inst_t *ctx_inst, char **missing);
static int
opt_parse(char *s, opt_t **opt);
static int
init_opts(char *spec, ctx_t *ctx);
static int
ctxopt_build_cmdline_list(int nb_words, char **words);
static int
opt_set_parms(char *opt_name, char *par_str);
static ctx_inst_t *
new_ctx_inst(ctx_t *ctx, ctx_inst_t *prev_ctx_inst);
static void
evaluate_ctx_inst(ctx_inst_t *ctx_inst);
/* ****************************** */
/* Fatal messages implementation. */
/* ****************************** */
/* =================================================================== */
/* Fatal error function used when a fatal condition is encountered. */
/* This function is reserved for the ctxopt internal usage. */
/* */
/* format : printf like format. */
/* ... : remaining arguments interpreted using the format argument. */
/* =================================================================== */
static void
fatal_internal(const char *format, ...)
{
va_list args;
fprintf(stderr, "CTXOPT: ");
va_start(args, format);
vfprintf(stderr, format, args);
fprintf(stderr, "\n");
va_end(args);
exit(EXIT_FAILURE);
}
/* ====================================================================== */
/* Generic fatal error function. This one uses the global status ctxopt */
/* stored in the cur_state structure and can call custom error functions. */
/* registered by the users for a given error identifier if any. */
/* */
/* e : Error identifier responsible of the fatal error. */
/* errmsg : User's provided string specific to the error e. */
/* Note that errmsg is not used in all cases. */
/* */
/* CTXOPTMISPAR Missing parameter. */
/* CTXOPTREQPAR Option: all parameters in a required group are */
/* missing. */
/* CTXOPTMISARG Missing argument. */
/* CTXOPTUXPARG Unexpected argument. */
/* CTXOPTDUPOPT Duplicated option. */
/* CTXOPTUNKPAR Unknown parameter. */
/* CTXOPTINCOPT Incompatible option. */
/* CTXOPTCTEOPT Option: bad number of occurrences. */
/* CTXOPTCTLOPT Option: not enough occurrences. */
/* CTXOPTCTGOPT Option: too many occurrence of. */
/* CTXOPTCTEARG Arguments: bad number of occurrences. */
/* CTXOPTCTLARG Arguments: not enough occurrences. */
/* CTXOPTCTGARG Arguments: too many occurrences. */
/* ====================================================================== */
static void
fatal(errors e, char *errmsg)
{
if (err_functions[e] != NULL)
err_functions[e](e, cur_state);
else
{
switch (e)
{
case CTXOPTNOERR:
break;
case CTXOPTMISPAR:
if (cur_state->ctx_par_name != NULL)
fprintf(stderr,
"the mandatory parameter(s) %s are missing in the context "
"introduced by %s.\n",
errmsg,
cur_state->ctx_par_name);
else
fprintf(stderr,
"The mandatory parameter(s) %s are missing "
"in the main context.\n",
errmsg);
free(errmsg);
break;
case CTXOPTREQPAR:
fprintf(stderr,
errmsg,
cur_state->req_opt_par_needed,
cur_state->req_opt_par);
break;
case CTXOPTUNXARG:
if (cur_state->cur_opt_par_name != NULL)
fprintf(stderr,
"The parameter %s takes no arguments "
"or has too many arguments.\n",
cur_state->cur_opt_par_name);
break;
case CTXOPTMISARG:
if (cur_state->pre_opt_par_name != NULL)
fprintf(stderr,
"%s requires argument(s).\n",
cur_state->pre_opt_par_name);
else
fprintf(stderr,
"%s requires argument(s).\n",
cur_state->cur_opt_par_name);
break;
case CTXOPTDUPOPT:
if (cur_state->pre_opt_par_name != NULL)
fprintf(stderr,
"The parameter %s can only appear once in the context "
"introduced by %s.\n",
cur_state->cur_opt_params,
cur_state->ctx_par_name);
else
fprintf(stderr,
"The parameter %s can only appear once "
"in the main context.\n",
cur_state->cur_opt_params);
break;
case CTXOPTUNKPAR:
fprintf(stderr,
"Unknown parameter %s.\n%s",
cur_state->cur_opt_par_name,
errmsg);
break;
case CTXOPTINCOPT:
fprintf(stderr,
"The parameter %s is incompatible with %s.\n",
cur_state->cur_opt_par_name,
errmsg);
break;
case CTXOPTCTEOPT:
if (cur_state->ctx_par_name)
fprintf(stderr,
"The parameter %s must appear exactly %d times "
"in the context introduced by %s.\n",
cur_state->cur_opt_params,
cur_state->opts_count,
cur_state->ctx_par_name);
else
fprintf(stderr,
"The parameter %s must appear exactly %d times "
"in the main context.\n",
cur_state->cur_opt_params,
cur_state->opts_count);
break;
case CTXOPTCTLOPT:
if (cur_state->ctx_par_name)
fprintf(stderr,
"The parameter %s must appear less than %d times "
"in the context introduced by %s.\n",
cur_state->cur_opt_params,
cur_state->opts_count,
cur_state->ctx_par_name);
else
fprintf(stderr,
"The parameter %s must appear less than %d times "
"in the main context.\n",
cur_state->cur_opt_params,
cur_state->opts_count);
break;
case CTXOPTCTGOPT:
if (cur_state->ctx_par_name)
fprintf(stderr,
"The parameter %s must appear more than %d times "
"in the context introduced by %s.\n",
cur_state->cur_opt_params,
cur_state->opts_count,
cur_state->ctx_par_name);
else
fprintf(stderr,
"The parameter %s must appear more than %d times "
"in the main context.\n",
cur_state->cur_opt_params,
cur_state->opts_count);
break;
case CTXOPTCTEARG:
fprintf(stderr,
"The parameter %s must have exactly %d arguments.\n",
cur_state->cur_opt_par_name,
cur_state->opt_args_count);
break;
case CTXOPTCTLARG:
fprintf(stderr,
"The parameter %s must have less than %d arguments.\n",
cur_state->cur_opt_par_name,
cur_state->opt_args_count);
break;
case CTXOPTCTGARG:
fprintf(stderr,
"The parameter %s must have more than %d arguments.\n",
cur_state->cur_opt_par_name,
cur_state->opt_args_count);
break;
case CTXOPTERRSIZ:
break;
}
}
/* CTXOPTUNKPAR should display the full usage to help the user follow */
/* the chaining of contexts when several possible contexts have been */
/* identified. Otherwise, errmsg is the empty string and the display of */
/* the current usage is enough. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (e == CTXOPTUNKPAR && *errmsg != '\0')
ctxopt_disp_usage(continue_after);
else
ctxopt_ctx_disp_usage(NULL, continue_after);
exit(e); /* Exit with the error id e as return code. */
}
/* ********************************* */
/* Memory management implementation. */
/* ********************************* */
/* ================== */
/* Customized malloc. */
/* ================== */
static void *
xmalloc(size_t size)
{
void *allocated;
size_t real_size;
real_size = (size > 0) ? size : 1;
allocated = malloc(real_size);
if (allocated == NULL)
fatal_internal("Insufficient memory (attempt to malloc %lu bytes).\n",
(unsigned long int)size);
return allocated;
}
/* ================== */
/* Customized calloc. */
/* ================== */
static void *
xcalloc(size_t n, size_t size)
{
void *allocated;
n = (n > 0) ? n : 1;
size = (size > 0) ? size : 1;
allocated = calloc(n, size);
if (allocated == NULL)
fatal_internal("Insufficient memory (attempt to calloc %lu bytes).\n",
(unsigned long int)size);
return allocated;
}
/* =================== */
/* Customized realloc. */
/* =================== */
static void *
xrealloc(void *p, size_t size)
{
void *allocated;
allocated = realloc(p, size);
if (allocated == NULL && size > 0)
fatal_internal("Insufficient memory (attempt to xrealloc %lu bytes).\n",
(unsigned long int)size);
return allocated;
}
/* ==================================== */
/* strdup implementation using xmalloc. */
/* ==================================== */
static char *
xstrdup(const char *p)
{
char *allocated;
allocated = xmalloc(strlen(p) + 1);
strcpy(allocated, p);
return allocated;
}
/* =================================================== */
/* strndup implementation using xmalloc. */
/* This version guarantees that there is a final '\0'. */
/* =================================================== */
static char *
xstrndup(const char *str, size_t len)
{
char *p;
p = memchr(str, '\0', len);
if (p)
len = p - str;
p = xmalloc(len + 1);
memcpy(p, str, len);
p[len] = '\0';
return p;
}
/* *************************** */
/* Linked list implementation. */
/* *************************** */
/* Linked list node structure. */
/* """"""""""""""""""""""""""" */
struct ll_node_s
{
void *data;
struct ll_node_s *next;
struct ll_node_s *prev;
};
/* Linked List structure. */
/* """""""""""""""""""""" */
struct ll_s
{
ll_node_t *head;
ll_node_t *tail;
long len;
};
/* ========================= */
/* Create a new linked list. */
/* ========================= */
static ll_t *
ll_new(void)
{
ll_t *ret = xmalloc(sizeof(ll_t));
ll_init(ret);
return ret;
}
/* =============================================== */
/* Free all the elements of a list (make it empty) */
/* NULL or a custom function may be used to free */
/* the sub components of the elements. */
/* =============================================== */
static void
ll_free(ll_t * const list, void (*clean)(void *))
{
ll_node_t *node;
if (list)
{
node = list->head;
while (node)
{
/* Apply a custom cleaner if not NULL. */
/* """"""""""""""""""""""""""""""""""" */
if (clean)
clean(node->data);
ll_delete(list, node);
node = list->head;
}
}
}
/* ==================================== */
/* Destroy a list and all its elements. */
/* ==================================== */
static void
ll_destroy(ll_t *list, void (*clean)(void *))
{
if (list)
{
ll_free(list, clean);
free(list);
}
}
/* ========================= */
/* Initialize a linked list. */
/* ========================= */
static void
ll_init(ll_t *list)
{
list->head = NULL;
list->tail = NULL;
list->len = 0;
}
/* ===================================================== */
/* Allocate the space for a new node in the linked list. */
/* ===================================================== */
static ll_node_t *
ll_new_node(void)
{
ll_node_t *ret = xmalloc(sizeof(ll_node_t));
return ret;
}
/* ==================================================================== */
/* Append a new node filled with its data at the end of the linked list */
/* The user is responsible for the memory management of the data. */
/* ==================================================================== */
static void
ll_append(ll_t * const list, void * const data)
{
ll_node_t *node;
node = ll_new_node(); /* ll_new_node cannot return NULL because it *
| uses xmalloc which does not return if there *
| is an allocation error. */
node->data = data;
node->next = NULL; /* This node will be the last. */
node->prev = list->tail; /* NULL if it is a new list. */
if (list->tail)
list->tail->next = node;
else
list->head = node;
list->tail = node;
++list->len; /* One more node in the list. */
}
/* ================================================================== */
/* Put a new node filled with its data at the beginning of the linked */
/* list. */
/* The user is responsible for the memory management of the data. */
/* ================================================================== */
static void
ll_prepend(ll_t * const list, void * const data)
{
ll_node_t *node;
node = ll_new_node(); /* ll_new_node cannot return NULL because it *
| uses xmalloc which does not return if there *
| is an allocation error. */
node->data = data;
node->prev = NULL; /* This node will be the first. */
node->next = list->head; /* NULL if it is a new list. */
if (list->head)
list->head->prev = node;
else
list->tail = node;
list->head = node;
++list->len; /* One more node in the list. */
}
/* ======================================================== */
/* Insert a new node before the specified node in the list. */
/* ======================================================== */
static void
ll_insert_before(ll_t * const list, ll_node_t *node, void * const data)
{
ll_node_t *new_node;
if (node->prev == NULL)
ll_prepend(list, data);
else
{
new_node = ll_new_node(); /* ll_new_node cannot return NULL because it *
| uses xmalloc which does not return if there *
| is an allocation error. */
new_node->data = data;
new_node->next = node;
new_node->prev = node->prev;
node->prev->next = new_node;
node->prev = new_node;
++list->len; /* One more node in the list. */
}
}
/* ======================================================= */
/* Insert a new node after the specified node in the list. */
/* ======================================================= */
static void
ll_insert_after(ll_t * const list, ll_node_t *node, void * const data)
{
ll_node_t *new_node;
if (node->next == NULL)
ll_append(list, data);
else
{
new_node = ll_new_node(); /* ll_new_node cannot return NULL because it *
| uses xmalloc which does not return if there *
| is an allocation error. */
new_node->data = data;
new_node->prev = node;
new_node->next = node->next;
node->next->prev = new_node;
node->next = new_node;
++list->len; /* One more node in the list. */
}
}
/* ================================================================= */
/* Remove a node from a linked list. */
/* The memory taken by the deleted node must be freed by the caller. */
/* ================================================================= */
static int
ll_delete(ll_t * const list, ll_node_t *node)
{
if (list->head == list->tail)
{
/* We delete the last remaining element from the list. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""" */
if (list->head == NULL)
return 0;
list->head = list->tail = NULL;
}
else if (node->prev == NULL)
{
/* We delete the first element from the list. */
/* """""""""""""""""""""""""""""""""""""""""" */
list->head = node->next;
list->head->prev = NULL;
}
else if (node->next == NULL)
{
/* We delete the last element from the list. */
/* """"""""""""""""""""""""""""""""""""""""" */
list->tail = node->prev;
list->tail->next = NULL;
}
else
{
/* We delete an element from the list. */
/* """"""""""""""""""""""""""""""""""" */
node->next->prev = node->prev;
node->prev->next = node->next;
}
free(node);
--list->len; /* One less node in the list. */
return 1;
}
/* ==================================================================== */
/* Allocate and fill an array of strings from a list. */
/* WARNINGS: */
/* 1) The list node must contain strings (char *). */
/* 2) The strings in the resulting array MUST NOT be freed as the are */
/* NOT copied from the strings of the list. */
/* */
/* IN list : The list from which the array is generated. */
/* IN start_node : The node of the list which will be the first node to */
/* consider to create the array. */
/* OUT: count : The number of elements of the resulting array. */
/* OUT: array : The resulting array or NULL if the list is empty. */
/* RC : : The number of elements of the resulting array. */
/* ==================================================================== */
static int
ll_strarray(ll_t *list, ll_node_t *start_node, int *count, char ***array)
{
int n = 0;
ll_node_t *node;
*count = 0;
node = start_node;
if (list == NULL || node == NULL)
{
*array = NULL;
return 0;
}
*array = xmalloc((list->len + 1) * sizeof(char *));
while (node != NULL)
{
(*array)[n++] = (char *)(node->data);
(*count)++;
node = node->next;
}
(*array)[*count] = NULL;
return *count;
}
/* ******************************************************************* */
/* BST (search.h compatible) implementation. */
/* */
/* Tree search generalized from Knuth (6.2.2) Algorithm T just like */
/* the AT&T man page says. */
/* */
/* Written by reading the System V Interface Definition, not the code. */
/* */
/* Totally public domain. */
/* ******************************************************************* */
struct bst_s
{
void *key;
struct bst_s *llink;
struct bst_s *rlink;
};
#if 0 /* Unused yet. */
/* =========================== */
/* Delete node with given key. */
/* =========================== */
static void *
bst_delete(const void * vkey, void ** vrootp,
int (*compar)(const void *, const void *))
{
bst_t ** rootp = (bst_t **)vrootp;
bst_t * p, *q, *r;
int cmp;
if (rootp == NULL || (p = *rootp) == NULL)
return NULL;
while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0)
{
p = *rootp;
rootp = (cmp < 0) ? &(*rootp)->llink /* follow llink branch */
: &(*rootp)->rlink; /* follow rlink branch */
if (*rootp == NULL)
return NULL; /* key not found */
}
r = (*rootp)->rlink; /* D1: */
if ((q = (*rootp)->llink) == NULL) /* Left NULL? */
q = r;
else if (r != NULL)
{ /* Right link is NULL? */
if (r->llink == NULL)
{ /* D2: Find successor */
r->llink = q;
q = r;
}
else
{ /* D3: Find NULL link */
for (q = r->llink; q->llink != NULL; q = r->llink)
r = q;
r->llink = q->rlink;
q->llink = (*rootp)->llink;
q->rlink = (*rootp)->rlink;
}
}
if (p != *rootp)
free(*rootp); /* D4: Free node */
*rootp = q; /* link parent to new node */
return p;
}
#endif
/* ===================================================================== */
/* Destroy a tree. */
/* The clean function pointer can be NULL, in this case the node content */
/* is not freed. */
/* ===================================================================== */
static void
bst_destroy(void *vrootp, void (*clean)(void *))
{
bst_t *root = (bst_t *)vrootp;
if (root == NULL)
return;
bst_destroy(root->llink, clean);
bst_destroy(root->rlink, clean);
if (clean)
clean((void *)root->key);
free(root);
}
/* ========================= */
/* Find a node, or return 0. */
/* ========================= */
static void *
bst_find(const void *vkey,
void * const *vrootp,
int (*compar)(const void *, const void *))
{
bst_t * const *rootp = (bst_t * const *)vrootp;
if (rootp == NULL)
return NULL;
while (*rootp != NULL)
{ /* T1: */
int r;
if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
return *rootp; /* key found */
rootp = (r < 0) ? &(*rootp)->llink /* T3: follow left branch */
: &(*rootp)->rlink; /* T4: follow right branch */
}
return NULL;
}
/* ======================================= */
/* Find or inserts datum into search tree. */
/* ======================================= */
static void *
bst_search(void *vkey, void **vrootp, int (*compar)(const void *, const void *))
{
bst_t *q;
bst_t **rootp = (bst_t **)vrootp;
if (rootp == NULL)
return NULL;
while (*rootp != NULL)
{ /* Knuth's T1: */
int r;
if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
return *rootp; /* we found it! */
rootp = (r < 0) ? &(*rootp)->llink /* T3: follow left branch */
: &(*rootp)->rlink; /* T4: follow right branch */
}
q = xmalloc(sizeof(bst_t)); /* T5: key not found */
if (q != 0)
{ /* make new node */
*rootp = q; /* link new node to old */
q->key = vkey; /* initialize new node */
q->llink = q->rlink = NULL;
}
return q;
}
/* ========================= */
/* Walk the nodes of a tree. */
/* ========================= */
static void
bst_walk_recurse(const bst_t *root,
void (*action)(const void *, walk_order_e, int),
int level)
{
if (root->llink == NULL && root->rlink == NULL)
(*action)(root, leaf, level);
else
{
(*action)(root, preorder, level);
if (root->llink != NULL)
bst_walk_recurse(root->llink, action, level + 1);
(*action)(root, postorder, level);
if (root->rlink != NULL)
bst_walk_recurse(root->rlink, action, level + 1);
(*action)(root, endorder, level);
}
}
static void
bst_walk(const void *vroot, void (*action)(const void *, walk_order_e, int))
{
if (vroot != NULL && action != NULL)
bst_walk_recurse(vroot, action, 0);
}
/* ************************ */
/* Various implementations. */
/* ************************ */
/* ======================== */
/* Trim leading characters. */
/* ======================== */
static void
ltrim(char *str, const char *trim_str)
{
size_t len = strlen(str);
size_t begin = strspn(str, trim_str);
size_t i;
if (begin > 0)
for (i = begin; i <= len; ++i)
str[i - begin] = str[i];
}
/* ================================================= */
/* Trim trailing characters. */
/* The resulting string will have at least min bytes */
/* even if trailing spaces remain. */
/* ================================================= */
static void
rtrim(char *str, const char *trim_str, size_t min)
{
size_t len = strlen(str);
while (len > min && strchr(trim_str, str[len - 1]))
str[--len] = '\0';
}
/* ================================================== */
/* Count the number of occurrences of the character c */
/* in the string str. */
/* The str pointer is assumed to be not NULL. */
/* ================================================== */
static int
strchrcount(char *str, char c)
{
int count = 0;
while (*str)
if (*str++ == c)
count++;
return count;
}
/* =============================================== */
/* Is the string str2 a prefix of the string str1? */
/* =============================================== */
static int
strpref(char *str1, char *str2)
{
while (*str1 != '\0' && *str1 == *str2)
{
str1++;
str2++;
}
return *str2 == '\0';
}
/* ========================== */
/* Like strcmp ignoring case. */
/* ========================== */
static int
stricmp(const char *s1, const char *s2)
{
while (tolower((unsigned char)*s1) == tolower((unsigned char)*s2))
{
if (*s1 == '\0')
return 0;
s1++;
s2++;
}
return (int)tolower((unsigned char)*s1) - (int)tolower((unsigned char)*s2);
}
/* ====================================================================== */
/* Strings concatenation with dynamic memory allocation. */
/* IN : a variable number of char * arguments with NULL terminating */
/* the sequence. */
/* The first one must have been dynamically allocated and is */
/* mandatory. */
/* */
/* Returns a new allocated string containing the concatenation of all */
/* the arguments. It is the caller's responsibility to free the resulting */
/* string. */
/* ====================================================================== */
static char *
strappend(char *str, ...)
{
size_t l;
va_list args;
char *s;
l = 1 + strlen(str);
va_start(args, str);
s = va_arg(args, char *);
while (s)
{
l += strlen(s);
s = va_arg(args, char *);
}
va_end(args);
if (l > 0)
str = xrealloc(str, l);
va_start(args, str);
s = va_arg(args, char *);
while (s)
{
strcat(str, s);
s = va_arg(args, char *);
}
va_end(args);
return str;
}
/* ====================================================================== */
/* Public domain strtok_r() by Charlie Gordon. */
/* from comp.lang.c 9/14/2007 */
/* http://groups.google.com/group/comp.lang.c/msg/2ab1ecbb86646684 */
/* */
/* (Declaration that it's public domain): */
/* http://groups.google.com/group/comp.lang.c/msg/7c7b39328fefab9c */
/* */
/* Also, fixed by Fletcher T. Penney --- added the "return NULL" when */
/* *end == NULL. */
/* ====================================================================== */
static char *
xstrtok_r(char *str, const char *delim, char **end)
{
char *ret;
if (str == NULL)
str = *end;
if (str == NULL)
return NULL;
str += strspn(str, delim);
if (*str == '\0')
return NULL;
ret = str;
str += strcspn(str, delim);
if (*str)
*str++ = '\0';
*end = str;
return ret;
}
/* ===================================================================== */
/* Put the first word of str, truncated to len characters, in buf. */
/* Return a pointer in str pointing just after the word. */
/* buf must have been pre-allocated to accept at least len+1 characters. */
/* Note that buf can contains a sting full of spaces is str was not */
/* trimmed before the call. */
/* ===================================================================== */
char *
get_word(char *str, char *buf, size_t len)
{
char *s = str;
/* Skip spaces. */
/* """""""""""" */
while (*s && isspace(*s))
s++;
/* Set the new string start. */
/* """"""""""""""""""""""""" */
str = s;
/* Get the word. */
/*"""""""""""""" */
while (*s && !isspace(*s) && s - str < (ptrdiff_t)len)
s++;
strncpy(buf, str, s - str);
buf[s - str] = 0;
return s;
}
/* ==================================================================== */
/* Return 1 is value is "1" or "yes" (ignoring case). */
/* Return 0 is value is "0" or "no" (ignoring case). */
/* If value has another value, then set invalid to 1 and also return 0 */
/* invalid is set to 0 in all the other cases. */
/* ==================================================================== */
static int
eval_yes(char *value, int *invalid)
{
*invalid = 0;
if (strcmp(value, "1") == 0 || stricmp(value, "yes") == 0)
return 1;
else if (strcmp(value, "0") != 0 && stricmp(value, "no") != 0)
*invalid = 1;
return 0;
}
/* =========================================================== */
/* Fill an array of strings from the words composing a string. */
/* */
/* str: initial string which will be altered. */
/* args: array of pointers to the start of the words in str. */
/* max: maximum number of words used before giving up. */
/* return: the number of words (<=max). */
/* =========================================================== */
static int
str2argv(char *str, char **args, int max)
{
int nb_args = 0;
while (*str)
{
if (nb_args >= max)
return nb_args;
while (*str == ' ' || *str == '\t')
*(str++) = '\0';
if (!*str)
return nb_args;
args[nb_args] = str;
nb_args++;
while (*str && (*str != ' ') && (*str != '\t'))
str++;
}
return nb_args;
}
/* ********************** */
/* ctxopt implementation. */
/* ********************** */
static int ctxopt_initialized = 0; /* cap_init has not yet been called. */
/* Flags structure initialized by ctxopt_init. */
/* """"""""""""""""""""""""""""""""""""""""""" */
struct flags_s
{
int stop_if_non_option;
int allow_abbreviations;
int display_usage_on_error;
};
static flags_t flags = { 0, 1, 1 };
/* Context structure. */
/* """""""""""""""""" */
struct ctx_s
{
char *name;
ll_t *opt_list; /* list of options allowed in this context. */
ll_t *incomp_list; /* list of strings containing incompatible names *
| of options separated by spaces or tabs. */
ll_t *req_list; /* list of strings containing an option name and *
| all the option names where at least one of *
| them is required to be also present. */
int (*action)(char *name,
int type,
char *new_ctx,
int ctx_nb_data,
void **ctx_data);
void *par_bst;
int nb_data;
void **data;
};
/* https://textik.com/#488ce3649b6c60f5 */
/* */
/* +--------------+ */
/* |first_ctx_inst| */
/* +---+----------+ */
/* | */
/* +--v-----+ +--------+ +--------+ +-----+ */
/* +---+-->ctx_inst+------>opt_inst+----->opt_inst+------> ... | */
/* | | +-+------+ +----+---+ +----+---+ +-----+ */
/* | | | | | */
/* | | +-v------+ | | */
/* | +--+ctx_inst<-----------+ | */
/* | +-+------+ | */
/* | | | */
/* | +-v------+ | */
/* +------+ctx_inst<--------------------------+ */
/* +-+------+ */
/* | */
/* +-v---+ */
/* | ... | */
/* +-----+ */
/* Option structure. */
/* """"""""""""""""" */
struct opt_s
{
char *name; /* option name. */
char *next_ctx; /* new context this option may lead to */
ll_t *ctx_list; /* list of contexts allowing this option. */
char *params; /* string containing all the parameters of *
| the option. */
void (*action)( /* The option associated action. */
char *ctx_name, /* context name. */
char *opt_name, /* option name. */
char *par, /* option parameter. */
int nb_args, /* number of arguments. */
char **args, /* option arguments. */
int nb_opt_data, /* number of option data pointers. */
void **opt_data, /* option data pointers. */
int nb_ctx_data, /* nb of current context data ptrs. */
void **ctx_data /* current context data pointers. */
);
int visible_in_help; /* visibility in help. */
int nb_data; /* number of the data pointers passed as argument to action. */
void **data; /* array of data pointers passed as argument to action. */
int args; /* 1 if this option takes arguments else 0. */
int optional; /* 1 if the option is optional, else 0. */
int multiple; /* 1 if the option can appear more than one time in a *
| context, else 0. */
int opt_count_matter; /* 1 if we must restrict the count, else 0. */
int occurrences; /* Number of option occurrences in a context. */
char opt_count_oper; /* <, = or > */
int opt_count_mark; /* Value to be compared to with opt_count_oper. */
char *arg; /* symbolic text after # describing the option argument. */
int optional_args; /* 1 of option is optional else 0. */
int multiple_args; /* 1 is option can appear more than once in a context *
| instance. */
int opt_args_count_matter; /* 1 if count is restricted, else 0. */
char opt_args_count_oper; /* <, = or > */
int opt_args_count_mark; /* Value to be compared to with *
| opt_count_oper. */
int eval_first; /* 1 if this option must be evaluated before the options *
| without this mark. */
ll_t *eval_before_list; /* List of pointers on options which must be *
| evaluated before this option. */
ll_t *constraints_list; /* List of constraint check functions pointers. */
};
/* Context instance structure. */
/* """"""""""""""""""""""""""" */
struct ctx_inst_s
{
ctx_t *ctx; /* the context whose this is an instance of */
ctx_inst_t *prev_ctx_inst; /* ctx_inst of the opt_inst which led to the *
| creation of this ctx_inst structure. */
opt_inst_t *gen_opt_inst; /* opt_inst which led to the creation of a *
| instance of this structure. */
ll_t *incomp_bst_list; /* list of seen_opt_t BST. */
void *seen_opt_bst; /* tree of seen_opt_t. */
ll_t *opt_req_list; /* list of req_t. */
ll_t *opt_inst_list; /* The list of option instances in this *
| context instance. */
char *par_name; /* parameter which created this instance. */
};
/* Option instance structure. */
/* """""""""""""""""""""""""" */
struct opt_inst_s
{
opt_t *opt; /* The option this is an instance of. */
char *opt_name; /* The option which led to this creation. */
char *par; /* The parameter which led to this creation. */
ll_t *values_list; /* The list of arguments of this option. */
ctx_inst_t *next_ctx_inst; /* The new context instance this option. *
| instance may create. */
};
/* Structure used to check if an option has bee seen or not */
/* in a context instance. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
struct seen_opt_s
{
opt_t *opt; /* The concerned option. */
char *par; /* Parameter which led to the making of this structure. */
int seen; /* 1 if seen in the context instances, else 0. */
};
/* Structure used to check if at least one instance of the options whose */
/* pointers are in or_opt_list has been seen in the ctx_inst where an */
/* instance or opt is also present. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
struct req_s
{
opt_t *opt; /* Option that asks for other options. */
ll_t *or_opt_list; /* Required options, at least one of them *
| must be present. */
};
/* Parameter structure which links a parameter to the option it belongs to. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
struct par_s
{
char *name; /* Parameter name (with the leading -). */
opt_t *opt; /* Attached option. */
};
/* Constraint structure. */
/* """"""""""""""""""""" */
struct constraint_s
{
int (*constraint)(int nb_args, char **args, char *value, char *parameter);
int nb_args;
char **args;
char *to_free; /* pointer to the original string in which the array in *
| args points to. This pointer is kept there to allow *
| it to be freed. */
};
state_t *cur_state = NULL; /* Current analysis state. */
static ll_t *cmdline_list = NULL; /* List of interpreted CLI words *
| serves as the basis for the *
| analysis of the parameters. */
static ctx_t *main_ctx = NULL; /* initial context. */
static ctx_inst_t *first_ctx_inst = NULL; /* Pointer to the fist context *
| instance which holds the *
| options instances. */
static ll_t *ctx_inst_list = NULL; /* List of the context instances. */
/* ======================================================= */
/* Parse a string for the next matching token. */
/* */
/* s: string to parse. */
/* token: pre_allocated array of max tok_len characters. */
/* pattern: scanf type pattern token must match. */
/* pos: number of characters successfully parsed in s. */
/* */
/* Returns: a pointer to the first unread character or */
/* to he terminating \0. */
/* ======================================================= */
static char *
strtoken(char *s, char *token, size_t tok_len, char *pattern, int *pos)
{
char *full_pattern;
char len[3];
int n;
*pos = 0;
n = snprintf(len, 3, "%zu", tok_len);
if (n < 0)
return NULL;
full_pattern = xmalloc(strlen(pattern) + n + 4);
strcpy(full_pattern, "%");
strcat(full_pattern, len);
strcat(full_pattern, pattern);
strcat(full_pattern, "%n");
n = sscanf(s, full_pattern, token, pos);
free(full_pattern);
if (n != 1)
return NULL;
return s + *pos;
}
/* ****************************************** */
/* Various comparison and deletion functions. */
/* ****************************************** */
static int
ctx_compare(const void *c1, const void *c2)
{
return strcmp(((ctx_t *)c1)->name, ((ctx_t *)c2)->name);
}
/* =========================== */
/* Free a context_bst element. */
/* =========================== */
static void
ctx_free(void *c)
{
ctx_t *ctx = c;
free(ctx->name);
free(ctx->data);
ll_destroy(ctx->opt_list, NULL);
ll_destroy(ctx->incomp_list, free);
ll_destroy(ctx->req_list, free);
bst_destroy(ctx->par_bst, par_free);
free(c);
}
/* ============================= */
/* Free a ctx_inst_list element. */
/* ============================= */
static void
ctx_inst_free(void *ci)
{
ctx_inst_t *ctx_inst = ci;
free(ctx_inst->par_name);
ll_destroy(ctx_inst->incomp_bst_list, incomp_bst_free);
bst_destroy(ctx_inst->seen_opt_bst, seen_opt_free);
ll_destroy(ctx_inst->opt_inst_list, opt_inst_free);
ll_destroy(ctx_inst->opt_req_list, req_free);
free(ci);
}
/* ============================== */
/* Free an opt_inst_list element. */
/* ============================== */
static void
opt_inst_free(void *oi)
{
opt_inst_t *opt_inst = oi;
ll_destroy(opt_inst->values_list, NULL);
free(oi);
}
/* ================================== */
/* Compare two seen_opt_bst elements. */
/* ================================== */
static int
seen_opt_compare(const void *so1, const void *so2)
{
opt_t *o1, *o2;
o1 = ((seen_opt_t *)so1)->opt;
o2 = ((seen_opt_t *)so2)->opt;
return strcmp(o1->name, o2->name);
}
/* ============================ */
/* Free a seen_opt_bst element. */
/* ============================ */
void
seen_opt_free(void *so)
{
seen_opt_t *seen_opt = so;
free(seen_opt->par);
free(so);
}
/* =========================== */
/* Free an incomp_bst element. */
/* =========================== */
static void
incomp_bst_free(void *b)
{
bst_t *bst = b;
bst_destroy(bst, NULL);
}
/* ============================= */
/* Free an opt_req_list element. */
/* ============================= */
static void
req_free(void *r)
{
req_t *req = r;
ll_destroy(req->or_opt_list, NULL);
free(req);
}
/* ================================= */
/* Compare two options_bst elements. */
/* ================================= */
static int
opt_compare(const void *o1, const void *o2)
{
return strcmp(((opt_t *)o1)->name, ((opt_t *)o2)->name);
}
/* ============================= */
/* Free an options_bst elements. */
/* ============================= */
void
opt_free(void *o)
{
opt_t *opt = o;
free(opt->name);
free(opt->next_ctx);
free(opt->params);
free(opt->arg);
free(opt->data);
ll_destroy(opt->ctx_list, NULL);
ll_destroy(opt->constraints_list, constraint_free);
ll_destroy(opt->eval_before_list, NULL);
free(o);
}
/* ============================= */
/* Compare two par_bst elements. */
/* ============================= */
static int
par_compare(const void *a1, const void *a2)
{
return strcmp(((par_t *)a1)->name, ((par_t *)a2)->name);
}
/* ======================= */
/* Free a par_bst element. */
/* ======================= */
static void
par_free(void *p)
{
par_t *par = p;
free(par->name);
free(p);
}
/* ================================ */
/* Free a constraints_list element. */
/* ================================ */
static void
constraint_free(void *c)
{
constraint_t *cstr = c;
free(cstr->args);
free(cstr->to_free);
free(c);
}
/* ******************************************************************** */
/* Helper functions to locate contexts, options and parameters in a BST */
/* by their names. */
/* ******************************************************************** */
static ctx_t *
locate_ctx(char *name)
{
bst_t *node;
ctx_t ctx = { 0 };
ctx.name = name;
if ((node = bst_find(&ctx, &contexts_bst, ctx_compare)) == NULL)
return NULL;
else
return node->key;
}
static opt_t *
locate_opt(char *name)
{
bst_t *node;
opt_t opt = { 0 };
opt.name = name;
if ((node = bst_find(&opt, &options_bst, opt_compare)) == NULL)
return NULL;
else
return node->key;
}
static par_t *
locate_par(char *name, ctx_t *ctx)
{
bst_t *node;
par_t par = { 0 };
void *bst = ctx->par_bst;
par.name = name;
if ((node = bst_find(&par, &bst, par_compare)) == NULL)
return NULL;
else
return node->key;
}
/* ====================================================================== */
/* Helper function to display the dependency constraints between options. */
/* These constraints are set with the ctxopt_add_opt_settings function */
/* using the 'before' and 'after' arguments. */
/* IN list : a list of options. */
/* ====================================================================== */
static void
print_before_constraints(ll_t *list)
{
ll_node_t *node = list->head;
ll_node_t *before_node;
opt_t *opt, *before_opt;
int msg = 0;
while (node != NULL)
{
opt = node->data;
if (opt->eval_before_list->len > 0)
{
if (!msg)
{
printf("\n If present in the command line,");
msg = 1; /* Display this message only once. */
}
before_node = opt->eval_before_list->head;
printf("\n ");
while (before_node != NULL)
{
before_opt = before_node->data;
printf("%s", before_opt->params);
before_node = before_node->next;
if (before_node != NULL)
printf(" and\n ");
}
printf(" will be evaluated after %s\n", opt->params);
}
node = node->next;
}
}
/* =================================================================== */
/* Utility function to format and print the options present in a list. */
/* */
/* IN list : a list of options. */
/* OUT has_* : a set of flags which will determine the content of the */
/* explanation given after the formatted printing of the */
/* options. */
/* =================================================================== */
static void
print_options(ll_t *list,
int *has_optional,
int *has_ellipsis,
int *has_rule,
int *has_generic_arg,
int *has_ctx_change,
int *has_early_eval)
{
ll_node_t *node = list->head;
opt_t *opt;
char *line;
char *option;
line = xstrdup(" ");
while (node != NULL)
{
option = xstrdup("");
opt = node->data;
/* Skip option set as not visible in help. */
/* """"""""""""""""""""""""""""""""""""""" */
if (!opt->visible_in_help)
{
node = node->next;
continue;
}
if (opt->optional)
{
option = strappend(option, "[", (char *)0);
*has_optional = 1;
}
if (opt->eval_first)
{
option = strappend(option, "*", (char *)0);
*has_early_eval = 1;
}
option = strappend(option, opt->params, (char *)0);
if (opt->next_ctx != NULL)
{
option = strappend(option, ">", opt->next_ctx, (char *)0);
*has_ctx_change = 1;
}
if (opt->multiple)
{
if (opt->opt_count_oper != '\0')
{
char m[4];
char o[2];
o[0] = opt->opt_count_oper;
o[1] = '\0';
snprintf(m, 3, "%u", opt->opt_count_mark);
option = strappend(option, "...", o, m, (char *)0);
*has_rule = 1;
}
else
option = strappend(option, "...", (char *)0);
*has_ellipsis = 1;
}
if (opt->args)
{
if (*(opt->arg) == '#')
*has_generic_arg = 1;
option = strappend(option, " ", (char *)0);
if (opt->optional_args)
{
option = strappend(option, "[", opt->arg, (char *)0);
*has_optional = 1;
}
else
option = strappend(option, opt->arg, (char *)0);
if (opt->multiple_args)
{
if (opt->opt_args_count_oper != '\0')
{
char m[4];
char o[2];
o[0] = opt->opt_args_count_oper;
o[1] = '\0';
snprintf(m, 3, "%u", opt->opt_args_count_mark);
option = strappend(option, "...", o, m, (char *)0);
*has_rule = 1;
}
else
option = strappend(option, "...", (char *)0);
*has_ellipsis = 1;
}
if (opt->optional_args)
option = strappend(option, "]", (char *)0);
}
if (opt->optional)
option = strappend(option, "]", (char *)0);
if (strlen(line) + 1 + strlen(option) < 80)
line = strappend(line, option, " ", (char *)0);
else
{
printf("%s\n", line);
line[2] = '\0';
line = strappend(line, option, " ", (char *)0);
}
free(option);
node = node->next;
}
printf("%s\n", line);
free(line);
}
/* ==================================================== */
/* Explain the special syntactic symbols present in the */
/* generated usage messages. */
/* ==================================================== */
static void
print_explanations(int has_early_eval,
int has_ctx_change,
int has_generic_arg,
int has_optional,
int has_ellipsis,
int has_rule)
{
if (has_early_eval || has_ctx_change || has_generic_arg || has_optional
|| has_ellipsis || has_rule)
{
printf("\nExplanation of the syntax used above:\n");
printf("Only the parameters (prefixed by -) and the arguments, if any, "
"must be entered.\n");
printf("The following is just there to explain the other symbols "
"displayed.\n\n");
if (has_early_eval)
printf("* : the parameters defined for this option will "
"be evaluated first.\n");
if (has_ctx_change)
printf("> : the context after this symbol will be the new "
"default context.\n");
if (has_generic_arg)
printf("#tag : argument with a hint about its meaning.\n");
if (has_optional)
printf("[...] : the object between square brackets is "
"optional.\n");
if (has_ellipsis)
printf("... : several occurrences of the previous object "
"are possible.\n");
if (has_rule)
printf("[<|=|>]number: rules constraining the number of "
"parameters/arguments.\n");
}
}
/* ************************************************************ */
/* Various utilities and callback functions called when walking */
/* through a BST. */
/* ************************************************************ */
static void
bst_seen_opt_cb(const void *node, walk_order_e kind, int level)
{
seen_opt_t *seen_opt = ((bst_t *)node)->key;
if (kind == postorder || kind == leaf)
{
if ((!seen_opt->opt->optional) && seen_opt->seen == 0)
{
user_rc = 1;
user_string = strappend(user_string,
seen_opt->opt->params,
" ",
(char *)0);
}
}
}
static void
bst_seen_opt_seen_cb(const void *node, walk_order_e kind, int level)
{
seen_opt_t *seen_opt = ((bst_t *)node)->key;
if (kind == postorder || kind == leaf)
if (seen_opt->seen == 1)
{
user_rc = 1;
user_object = seen_opt->par;
}
}
static void
bst_print_ctx_cb(const void *node, walk_order_e kind, int level)
{
ctx_t *ctx = main_ctx;
ctx_t *cur_ctx = ((bst_t *)node)->key;
ll_t *list;
int has_optional = 0;
int has_ellipsis = 0;
int has_rule = 0;
int has_generic_arg = 0;
int has_ctx_change = 0;
int has_early_eval = 0;
if (kind == postorder || kind == leaf)
if (strcmp(ctx->name, cur_ctx->name) != 0)
{
list = cur_ctx->opt_list;
printf("\nAllowed options in the context %s:\n", cur_ctx->name);
print_options(list,
&has_optional,
&has_ellipsis,
&has_rule,
&has_generic_arg,
&has_ctx_change,
&has_early_eval);
print_before_constraints(list);
}
}
static void
bst_check_opt_cb(const void *node, walk_order_e kind, int level)
{
opt_t *opt = ((bst_t *)node)->key;
if (kind == postorder || kind == leaf)
{
if (opt->params == NULL) /* opt must have associated parameters. */
fatal_internal("Option %s has no registered parameter.\n", opt->name);
if (opt->action == NULL) /* opt must have an action. */
fatal_internal("Option %s has no registered action.\n", opt->name);
}
}
static void
bst_match_par_cb(const void *node, walk_order_e kind, int level)
{
ctx_t *ctx = ((bst_t *)node)->key;
if (kind == postorder || kind == leaf)
{
char *str = xstrdup(user_string);
while (*str != '\0')
{
if (locate_par(str, ctx) != NULL)
{
if (*user_string2 == '\0')
user_string2 = strappend(user_string2, "- ", ctx->name, (char *)0);
else
user_string2 = strappend(user_string2, "\n- ", ctx->name, (char *)0);
break;
}
str[strlen(str) - 1] = '\0';
}
free(str);
}
}
static void
match_prefix_cb(const void *node, walk_order_e kind, int level)
{
par_t *par = ((bst_t *)node)->key;
if (kind == postorder || kind == leaf)
if (strpref(par->name, (char *)user_object))
{
user_rc++;
user_string = strappend(user_string, par->name, " ", (char *)0);
}
}
/* ====================================================================== */
/* A parameter may not be separated from its first option by spaces, in */
/* this case this function looks for a valid flag as a prefix and splits */
/* the command line queue (eg: "-pa1" -> "-pa" "1" if "-pa" is a valid */
/* option). */
/* */
/* IN word : the word to be checked. */
/* IN ctx : the context in which the flag indexed by the word is to be */
/* checked. */
/* OUT pos : the offset in word pointing just after the matching prefix. */
/* OUT opt : a pointer to the option associated with the new parameter */
/* or NULL if none is found. */
/* */
/* The returned pointer must be freed by the caller. */
/* ====================================================================== */
static char *
look_for_valid_prefix_in_word(char *word, ctx_t *ctx, int *pos, opt_t **opt)
{
char *new = NULL;
int len;
par_t *par;
par_t tmp_par = { 0 };
len = strlen(word);
if (len > 2)
{
new = xstrdup(word);
do
{
new[--len] = '\0';
tmp_par.name = new;
} while ((par = locate_par(tmp_par.name, ctx)) == NULL && len > 2);
if (par != NULL)
{
*pos = len;
*opt = par->opt;
}
else
{
free(new);
new = NULL;
}
}
else
*pos = 0;
return new;
}
/* ============================================================= */
/* If par_name is an unique abbreviation of an exiting parameter */
/* in the context ctx, then return this parameter. */
/* ============================================================= */
static char *
abbrev_expand(char *par_name, ctx_t *ctx)
{
user_object = par_name;
user_rc = 0;
*user_string = '\0';
bst_walk(ctx->par_bst, match_prefix_cb);
rtrim(user_string, " ", 0);
/* The previous bst_walk has built a string of blank separated parameters */
/* all having par_name as prefix. This string is put in the user_string */
/* exchange zone. The number of these words in put in user_rc. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (user_rc == 1) /* The number of matching abbreviations. */
return xstrdup(user_string);
else /* There is at least two defined parameters starting with par_name. */
{
char *s, *first_s;
par_t *par;
opt_t *opt;
int opt_count = 0;
void *tmp_opt_bst = NULL;
/* Find all the options corresponding to these words and store them */
/* without duplication in a temporary BST. Only their resulting count */
/* matters. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
s = first_s = strtok(user_string, " "); /* first_s holds a copy of *
| the first word. */
while (s != NULL)
{
par = locate_par(s, ctx); /* par cannot be NULL here. */
opt = par->opt;
if (bst_find(opt, &tmp_opt_bst, opt_compare) == NULL)
{
/* This option as not already been seen */
/* store it and increase the seen counter. */
/* """"""""""""""""""""""""""""""""""""""" */
bst_search(opt, &tmp_opt_bst, opt_compare);
opt_count++;
}
s = strtok(NULL, " ");
}
/* Clean the temporary BST without removing the pointer */
/* to the real options. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""" */
if (tmp_opt_bst != NULL)
bst_destroy(tmp_opt_bst, NULL);
if (opt_count == 1)
/* All the abbreviation are leading to only one option */
/* We can just continue as in the previous case. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""" */
return xstrdup(first_s);
else
return NULL;
}
}
/* ================================================================ */
/* Terminate the program if mandatory options required by a context */
/* are not present. */
/* ================================================================ */
static void
check_for_missing_mandatory_opt(ctx_inst_t *ctx_inst, char *opt_par)
{
char *missing;
if (has_unseen_mandatory_opt(ctx_inst, &missing))
fatal(CTXOPTMISPAR, missing);
}
/* ====================================================== */
/* Return 1 if at least one mandatory option was not seen */
/* when quitting a context, else 0. */
/* ====================================================== */
static int
has_unseen_mandatory_opt(ctx_inst_t *ctx_inst, char **missing)
{
user_rc = 0;
*user_string = '\0';
bst_walk(ctx_inst->seen_opt_bst, bst_seen_opt_cb);
rtrim(user_string, " ", 0);
*missing = user_string;
return user_rc ? 1 : 0;
}
/* ========================================================================= */
/* This function terminates the program if an option or its arguments do not */
/* conform to its occurrences constraint. */
/* There constraints can appear by trailing >, < or = in their definition */
/* given in ctxopt_new_ctx. */
/* ========================================================================= */
static void
check_for_occurrence_issues(ctx_inst_t *ctx_inst)
{
ctx_t *ctx = ctx_inst->ctx;
opt_t *opt;
ll_node_t *node;
opt_inst_t *opt_inst;
char *cur_opt_params = cur_state->cur_opt_params;
char *cur_opt_par_name = cur_state->cur_opt_par_name;
/* Checks options. */
/* """"""""""""""" */
node = ctx->opt_list->head;
while (node != NULL)
{
opt = node->data;
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->cur_opt_params = opt->params;
cur_state->opts_count = opt->opt_count_mark;
cur_state->opt_args_count = opt->opt_args_count_mark;
if (opt->opt_count_matter)
switch (opt->opt_count_oper)
{
case '=':
if (opt->occurrences > 0 && opt->opt_count_mark != opt->occurrences)
fatal(CTXOPTCTEOPT, "");
break;
case '<':
if (opt->occurrences > 0 && opt->opt_count_mark <= opt->occurrences)
fatal(CTXOPTCTLOPT, "");
break;
case '>':
if (opt->occurrences > 0 && opt->opt_count_mark >= opt->occurrences)
fatal(CTXOPTCTGOPT, "");
break;
}
node = node->next;
}
/* Checks arguments. */
/* """"""""""""""""" */
node = ctx_inst->opt_inst_list->head;
while (node != NULL)
{
opt_inst = node->data;
opt = opt_inst->opt;
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->cur_opt_par_name = opt_inst->par;
cur_state->opts_count = opt->opt_count_mark;
cur_state->opt_args_count = opt->opt_args_count_mark;
int nb_values = opt_inst->values_list->len; /* Number of arguments of opt */
if (opt->opt_args_count_matter)
switch (opt->opt_args_count_oper)
{
case '=':
if (nb_values > 0 && opt->opt_args_count_mark != nb_values)
fatal(CTXOPTCTEARG, "");
break;
case '<':
if (nb_values > 0 && opt->opt_args_count_mark <= nb_values)
fatal(CTXOPTCTLARG, "");
break;
case '>':
if (nb_values > 0 && opt->opt_args_count_mark >= nb_values)
fatal(CTXOPTCTGARG, "");
break;
}
node = node->next;
}
cur_state->cur_opt_params = cur_opt_params;
cur_state->cur_opt_par_name = cur_opt_par_name;
}
/* ====================================================================== */
/* This function terminates the program if all the options which are part */
/* of a group of required options by some other option are missing. */
/* ====================================================================== */
static void
check_for_requirement_issues(ctx_inst_t *ctx_inst)
{
ll_node_t *node;
ll_node_t *req_node;
req_t *req;
opt_t *opt;
opt_t *req_opt;
bst_t *bst_node;
seen_opt_t tmp_seen_opt;
int found;
char *needed_params = NULL;
node = ctx_inst->opt_req_list->head;
while (node != NULL)
{
req = node->data;
opt = req->opt;
tmp_seen_opt.opt = opt;
bst_node = bst_find(&tmp_seen_opt,
&(ctx_inst->seen_opt_bst),
seen_opt_compare);
/* TODO: make sure bst_node cannot be NULL here. */
if (bst_node && ((seen_opt_t *)(bst_node->key))->seen != 0)
{
found = 0;
req_node = req->or_opt_list->head;
/* needed_params accumulates the params of the options in the group. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
free(needed_params); /* free can applied to the NULL pointer. */
needed_params = xstrdup("");
/* Go through the list of the required group of options and */
/* succeed when one of them has been seen in the context. */
/* otherwise a fatal error is triggered and the program is */
/* terminated. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
while (req_node != NULL)
{
req_opt = req_node->data;
tmp_seen_opt.opt = req_opt;
needed_params = strappend(needed_params,
req_opt->params,
"\n ",
(char *)0);
bst_node = bst_find(&tmp_seen_opt,
&(ctx_inst->seen_opt_bst),
seen_opt_compare);
if (((seen_opt_t *)(bst_node->key))->seen != 0)
{
found = 1; /* A required option has been seen, */
break; /* accept the group. */
}
req_node = req_node->next;
}
rtrim(needed_params, "\n ", 0);
/* This is a fatal error if none of the options in the required */
/* options group has been seen in the context. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (!found)
{
char *errmsg;
if (req->or_opt_list->len > 1)
errmsg = xstrdup("At least one of the parameters among:\n %s\n"
"requested by %s must be present.\n");
else
errmsg = xstrdup("The parameter %s "
"requested by %s must be present.\n");
cur_state->req_opt_par_needed = needed_params;
cur_state->req_opt_par = opt->params;
fatal(CTXOPTREQPAR, errmsg);
}
}
node = node->next;
}
}
/* ======================================================================== */
/* Parse a strings describing options and some of their characteristics */
/* The input string must have follow some rules like in the examples below: */
/* */
/* "opt_name1 opt_name2" */
/* "[opt_name1] opt_name2" */
/* "[opt_name1] opt_name2..." */
/* "[opt_name1 #...] opt_name2... [#]" */
/* "[opt_name1 [#...]] opt_name2... [#...]" */
/* */
/* Where [ ] encloses an optional part, # means: has parameters and ... */
/* means that there can be more than one occurrence of the previous thing. */
/* */
/* opt_name can be followed by a 'new context' change prefixed with the */
/* symbol >, as in opt1>c2 by eg. */
/* */
/* This function returns as soon as one (or no) option has been parsed and */
/* return the offset to the next option to parse. */
/* */
/* In case of successful parsing, an new option is allocated and its */
/* pointer returned. */
/* ======================================================================== */
static int
opt_parse(char *s, opt_t **opt)
{
int opt_optional = 0;
int opt_multiple = 0;
int opt_count_matter = 0;
char opt_count_oper = '\0';
unsigned opt_count_mark = 0;
int opt_args = 0;
char opt_arg[33] = { 0 };
int opt_multiple_args = 0;
int opt_args_count_matter = 0;
char opt_args_count_oper = '\0';
unsigned opt_args_count_mark = 0;
int opt_optional_args = 0;
int opt_eval_first = 0;
int n;
int pos;
int count = 0;
char *s_orig = s;
char *p;
char *opt_name = NULL;
char *next_ctx;
char token[65];
*opt = NULL;
memset(opt_arg, '\0', 33);
/* Strip the leading blanks. */
/* """"""""""""""""""""""""" */
while (isblank(*s))
s++;
if (*s == '[') /* Start of an optional option. */
{
opt_optional = 1;
s++;
}
s = strtoken(s, token, sizeof(token) - 1, "[^] \n\t.]", &pos);
if (s == NULL)
return -1; /* Empty string. */
/* Early EOS, only return success if the option is mandatory. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (!*s)
if (opt_optional == 1)
return -(s - s_orig - 1);
/* Validate the option name */
/* ALPHA+(ALPHANUM|_)* */
/* """""""""""""""""""""""" */
p = token;
if (!isalpha(*p) && *p != '*')
return -(s - s_orig - 1); /* opt_name must start with a letter. */
if (*p == '*')
opt_eval_first = 1;
p++;
while (*p)
{
if (!isalnum(*p) && *p != '_' && *p != '>')
return -(s - s_orig - 1); /* opt_name must contain a letter, *
* a number or a _ */
p++;
}
if (opt_eval_first)
opt_name = xstrdup(token + 1); /* Ignore the first '*' in token. */
else
opt_name = xstrdup(token);
if (*s == ']')
{
s++;
while (isblank(*s))
s++;
goto success;
}
/* Check if it can appear multiple times by looking for the dots. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
p = strtoken(s, token, 3, "[.]", &pos);
if (p)
{
if (strcmp(token, "...") == 0)
{
opt_multiple = 1;
s = p;
if (*s == '<' || *s == '=' || *s == '>')
{
unsigned value;
int offset;
n = sscanf(s + 1, "%u%n", &value, &offset);
if (n == 1)
{
opt_count_matter = 1;
opt_count_oper = *s;
opt_count_mark = value;
}
s += offset + 1;
}
}
else
{
free(opt_name);
return -(s - s_orig - 1);
}
}
if (*s == ']')
{
/* Abort on extraneous ] if the option is mandatory. */
/* """"""""""""""""""""""""""""""""""""""""""""""""" */
if (!opt_optional)
{
free(opt_name);
return -(s - s_orig - 1);
}
s++; /* skip the ] */
if (!*s || isblank(*s))
goto success;
else
{
free(opt_name);
return -(s - s_orig - 1);
}
}
/* A blank separates the option name and the argument tag. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (isblank(*s))
{
char dots[4];
while (isblank(*s))
s++;
if (!*s)
goto success;
pos = 0;
n = sscanf(s, "[%32[^] .\t]%n%3[.]", opt_arg, &pos, dots);
if (pos > 1 && *opt_arg == '#') /* [# has been read. */
{
opt_args = 1;
opt_optional_args = 1;
if (n == 2)
opt_multiple_args = 1; /* There were dots. */
s += pos + !!(n == 2) * 3; /* Skips the dots. */
if (*s == '<' || *s == '=' || *s == '>')
{
unsigned value;
int offset;
n = sscanf(s + 1, "%u%n", &value, &offset);
if (n == 1)
{
opt_args_count_matter = 1;
opt_args_count_oper = *s;
opt_args_count_mark = value;
}
s += offset + 1;
}
/* Optional arg tag must end with a ] */
/* """""""""""""""""""""""""""""""""" */
if (*s != ']')
{
free(opt_name);
return -(s - s_orig - 1);
}
s++; /* Skip the ] */
}
else
{
n = sscanf(s, "%32[^] .\t]%n%3[.]", opt_arg, &pos, dots);
if (pos > 0 && *opt_arg == '#') /* # has been read. */
{
opt_args = 1;
if (n == 2) /* There were dots. */
opt_multiple_args = 1;
s += pos + !!(n == 2) * 3; /* Skip the dots. */
if (*s == '<' || *s == '=' || *s == '>')
{
unsigned value;
int offset;
n = sscanf(s + 1, "%u%n", &value, &offset);
if (n == 1)
{
opt_args_count_matter = 1;
opt_args_count_oper = *s;
opt_args_count_mark = value;
}
s += offset + 1;
}
}
}
if (*s == ']')
{
/* Abort on extraneous ] if the option is mandatory. */
/* """"""""""""""""""""""""""""""""""""""""""""""""" */
if (!opt_optional)
{
free(opt_name);
return -(s - s_orig - 1);
}
s++; /* skip the ] */
/* Strip the following blanks. */
/* """"""""""""""""""""""""""" */
while (isblank(*s))
s++;
goto success;
}
else if (opt_optional == 0 && (!*s || isblank(*s)))
{
/* Strip the following blanks. */
/* """"""""""""""""""""""""""" */
while (isblank(*s))
s++;
goto success;
}
else if (opt_args == 0) /* # was not read it is possibly the start *
| of another option. */
goto success;
else
{
free(opt_name);
return -(s - s_orig - 1);
}
}
success:
/* Strip the following blanks. */
/* """"""""""""""""""""""""""" */
while (isblank(*s))
s++;
next_ctx = NULL;
if (*opt_name == '>')
fatal_internal("The option name is missing in %s.", opt_name);
count = strchrcount(opt_name, '>');
if (count == 1)
{
char *tmp = strchr(opt_name, '>');
next_ctx = xstrdup(tmp + 1);
*tmp = '\0';
}
else if (count > 1)
fatal_internal("Only one occurrence of '>' is allowed in %s.", opt_name);
*opt = xmalloc(sizeof(opt_t));
(*opt)->name = opt_name;
(*opt)->optional = opt_optional;
(*opt)->multiple = opt_multiple;
(*opt)->opt_count_matter = opt_count_matter;
(*opt)->opt_count_oper = opt_count_oper;
(*opt)->opt_count_mark = opt_count_mark;
(*opt)->args = opt_args;
(*opt)->arg = xstrdup(opt_arg);
(*opt)->optional_args = opt_optional_args;
(*opt)->multiple_args = opt_multiple_args;
(*opt)->opt_args_count_matter = opt_args_count_matter;
(*opt)->opt_args_count_oper = opt_args_count_oper;
(*opt)->opt_args_count_mark = opt_args_count_mark;
(*opt)->eval_first = opt_eval_first;
(*opt)->next_ctx = next_ctx;
(*opt)->ctx_list = ll_new();
(*opt)->constraints_list = ll_new();
(*opt)->eval_before_list = ll_new();
(*opt)->action = NULL;
(*opt)->params = NULL;
(*opt)->data = NULL;
(*opt)->visible_in_help = 1;
return s - s_orig;
}
/* ==================================================================== */
/* Try to initialize all the option in a given string. */
/* Each parsed option are put in a BST tree with its name as index. */
/* */
/* On collision, the arguments only the signature are required to be */
/* the same else this is considered as an error. Options can be used in */
/* more than one context and can be optional in one and mandatory in */
/* another. */
/* ==================================================================== */
static int
init_opts(char *spec, ctx_t *ctx)
{
opt_t *opt, *bst_opt;
bst_t *node;
int offset;
while (*spec)
{
if ((offset = opt_parse(spec, &opt)) > 0)
{
spec += offset;
if ((node = bst_find(opt, &options_bst, opt_compare)) != NULL)
{
int same_next_ctx = 0;
bst_opt = node->key; /* Node extracted from the BST. */
if (bst_opt->next_ctx == NULL && opt->next_ctx == NULL)
same_next_ctx = 1;
else if (bst_opt->next_ctx == NULL && opt->next_ctx != NULL)
same_next_ctx = 0;
else if (bst_opt->next_ctx != NULL && opt->next_ctx == NULL)
same_next_ctx = 0;
else
same_next_ctx = strcmp(bst_opt->next_ctx, opt->next_ctx) == 0;
if (bst_opt->optional_args != opt->optional_args
|| bst_opt->multiple_args != opt->multiple_args
|| bst_opt->args != opt->args || !same_next_ctx)
{
fatal_internal("The option %s already exists with "
"a different arguments signature.\n",
opt->name);
}
/* The newly created opt is already present in options_bst. */
/* We can remove it. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
opt_free(opt);
/* The new occurrence of the option option is legal */
/* append the current context ptr in the list. */
/* """""""""""""""""""""""""""""""""""""""""""""""" */
ll_append(bst_opt->ctx_list, ctx);
/* Append the new option to the context's options list. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""" */
ll_append(ctx->opt_list, bst_opt);
}
else
{
/* Initialize the option's context list with the current context. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
ll_append(opt->ctx_list, ctx);
/* Append the new option to the context's options list. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""" */
ll_append(ctx->opt_list, opt);
/* Insert the new option in the BST. */
/* """"""""""""""""""""""""""""""""" */
bst_search(opt, &options_bst, opt_compare);
}
}
else
{
char *s = xstrndup(spec, -offset);
printf("%s <---\nSyntax error at or before offset %d\n", s, -offset);
free(s);
exit(EXIT_FAILURE);
}
}
return 1;
}
/* ===================================================== */
/* ctxopt initialization function, must be called first. */
/* ===================================================== */
void
ctxopt_init(char *prog_name, char *init_flags)
{
int n;
contexts_bst = NULL;
options_bst = NULL;
char *ptr;
user_rc = 0;
user_value = 0;
user_string = xmalloc(8);
user_string2 = xmalloc(8);
user_object = NULL;
char flag[33], fname[31], vname[31];
int invalid;
ctxopt_initialized = 1;
/* Initialize current_state.*/
/* """""""""""""""""""""""" */
cur_state = xcalloc(sizeof(state_t), 0);
/* Initialize custom error function pointers to NULL. */
/* """""""""""""""""""""""""""""""""""""""""""""""""" */
err_functions = xmalloc(CTXOPTERRSIZ * sizeof(void *));
for (n = 0; n < CTXOPTERRSIZ; n++)
err_functions[n] = NULL;
/* Parse init_flags if any. */
/* """""""""""""""""""""""" */
while (*init_flags && (init_flags = get_word(init_flags, flag, 32)))
{
if (*flag)
{
if (sscanf(flag, "%30[^=]=%30[^=]", fname, vname) != 2)
fatal_internal("Invalid flag assignment: %s.", flag);
if (strcmp(fname, "stop_if_non_option") == 0)
{
if (eval_yes(vname, &invalid))
flags.stop_if_non_option = 1;
else if (!invalid)
flags.stop_if_non_option = 0;
else
fatal_internal("Invalid flag value for %s: %s.", fname, vname);
}
else if (strcmp(fname, "allow_abbreviations") == 0)
{
if (eval_yes(vname, &invalid))
flags.allow_abbreviations = 1;
else if (!invalid)
flags.allow_abbreviations = 0;
else
fatal_internal("Invalid flag value for %s: %s.", fname, vname);
}
else if (strcmp(fname, "display_usage_on_error") == 0)
{
if (eval_yes(vname, &invalid))
flags.display_usage_on_error = 1;
else if (!invalid)
flags.display_usage_on_error = 0;
else
fatal_internal("Invalid flag value for %s: %s.", fname, vname);
}
else
fatal_internal("Invalid flag name: %s.", fname);
}
}
/* Update current_state. */
/* """"""""""""""""""""" */
if (prog_name)
{
if (*prog_name == '\0')
cur_state->prog_name = xstrdup("program_name");
else if ((ptr = strrchr(prog_name, '/')))
cur_state->prog_name = xstrdup(ptr + 1);
else
cur_state->prog_name = xstrdup(prog_name);
}
else
cur_state->prog_name = xstrdup("program_name");
}
/* ========================================================================= */
/* Utility function which create and register a par_t object in a BST */
/* embedded in a context. */
/* This object will have a name and a pointer to the option it refers to. */
/* These object will be used to quickly find an option from a command */
/* line parameter during the analysis phase. */
/* */
/* IN : an option name. */
/* IN : a string of command line parameters to associate to the option. */
/* Returns : 1 is all was fine else 0. */
/* ========================================================================= */
static int
opt_set_parms(char *opt_name, char *par_str)
{
char *par_name, *ctx_name;
char *tmp_par_str, *end_tmp_par_str;
ctx_t *ctx;
opt_t *opt;
bst_t *node;
par_t *par, tmp_par;
int rc = 1; /* Return code. */
ll_t *list;
ll_node_t *lnode;
/* Look if the given option is defined. */
/* """""""""""""""""""""""""""""""""""" */
opt = locate_opt(opt_name);
if (opt == NULL)
fatal_internal("Unknown option %s.", opt_name);
/* For each context using this option. */
/* """"""""""""""""""""""""""""""""""" */
list = opt->ctx_list;
lnode = list->head;
while (lnode != NULL)
{
/* Locate the context in the contexts tree. */
/* """""""""""""""""""""""""""""""""""""""" */
ctx_name = ((ctx_t *)(lnode->data))->name;
ctx = locate_ctx(ctx_name);
if (ctx == NULL)
fatal_internal("Unknown context %s.", ctx_name);
else
{
void *par_bst = ctx->par_bst;
tmp_par_str = xstrdup(par_str);
ltrim(tmp_par_str, " \t");
rtrim(tmp_par_str, " \t", 0);
par_name = xstrtok_r(tmp_par_str, " \t,", &end_tmp_par_str);
if (par_name == NULL)
fatal_internal("Parameters are missing for option %s.", opt_name);
/* For each parameter given in par_str, creates a par_t object and */
/* insert it the in the parameters BST of the context. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
while (par_name != NULL)
{
tmp_par.name = par_name;
node = bst_find(&tmp_par, &par_bst, par_compare);
if (node != NULL)
{
fatal_internal("The parameter %s is already defined in context %s.",
par_name,
ctx->name);
rc = 0;
}
else
{
par = xmalloc(sizeof(par_t));
par->name = xstrdup(par_name);
par->opt = opt; /* Link the option to this parameter. */
bst_search(par, &par_bst, par_compare);
}
par_name = xstrtok_r(NULL, " \t,", &end_tmp_par_str);
}
/* Update the value of the root of ctx->par_bst as it may have */
/* been modified. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
ctx->par_bst = par_bst;
free(tmp_par_str);
}
lnode = lnode->next;
}
return rc;
}
/* ==================================================================== */
/* Create a new context instance. */
/* IN ctx : a context pointer to allow this instance to */
/* access the context fields */
/* IN prev_ctx_inst : the context instance whose option leading to the */
/* creation of this new context instance is part of */
/* Returns : the new context. */
/* ==================================================================== */
static ctx_inst_t *
new_ctx_inst(ctx_t *ctx, ctx_inst_t *prev_ctx_inst)
{
opt_t *opt;
opt_inst_t *gen_opt_inst;
ctx_inst_t *ctx_inst;
seen_opt_t *seen_opt;
char *str, *opt_name;
void *bst;
bst_t *bst_node;
/* Keep a trace of the opt_inst which was at the origin of the creation */
/* of this context instance. */
/* This will serve during the evaluation of the option callbacks. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (prev_ctx_inst != NULL)
{
gen_opt_inst = (opt_inst_t *)(prev_ctx_inst->opt_inst_list->tail->data);
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->opt_name = gen_opt_inst->opt->name;
}
else
gen_opt_inst = NULL;
/* Create and initialize the new context instance. */
/* """"""""""""""""""""""""""""""""""""""""""""""" */
ctx_inst = xmalloc(sizeof(ctx_inst_t));
ctx_inst->ctx = ctx;
ctx_inst->prev_ctx_inst = prev_ctx_inst;
ctx_inst->gen_opt_inst = gen_opt_inst;
ctx_inst->incomp_bst_list = ll_new();
ctx_inst->opt_inst_list = ll_new();
ctx_inst->opt_req_list = ll_new();
ctx_inst->seen_opt_bst = NULL;
ll_node_t *node;
if (prev_ctx_inst == NULL)
first_ctx_inst = ctx_inst;
/* Initialize the occurrence counters of each opt allowed in the context. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
node = ctx->opt_list->head;
while (node != NULL)
{
opt = node->data;
opt->occurrences = 0;
node = node->next;
}
/* Initialize the BST containing the seen indicator for all the options */
/* allowed in this context instance. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
node = ctx->opt_list->head;
while (node != NULL)
{
opt = node->data;
seen_opt = xmalloc(sizeof(seen_opt_t));
seen_opt->opt = opt;
seen_opt->par = NULL;
seen_opt->seen = 0;
bst_search(seen_opt, &(ctx_inst->seen_opt_bst), seen_opt_compare);
node = node->next;
}
/* Initialize the BST containing the incompatibles options. */
/* Incompatibles option names are read from strings found in the list */
/* incomp_list present in each instance of ctx_t. */
/* These names are then used to search for the object of type seen_opt_t */
/* which is already present in the seen_opt_bst of the context instance. */
/* in the BST. */
/* Once found the seen_opt_t object in inserted in the new BST. */
/* At the end the new BST in added to the list incomp_bst_list. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
node = ctx->incomp_list->head;
while (node != NULL)
{
bst = NULL;
seen_opt_t tmp_seen_opt;
str = xstrdup(node->data);
ltrim(str, " \t");
rtrim(str, " \t", 0);
opt_name = strtok(str, " \t"); /* Extract the first option name. */
while (opt_name != NULL) /* For each option name. */
{
if ((opt = locate_opt(opt_name)) != NULL)
{
/* The option found is searched in the tree of potential */
/* seen options. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
tmp_seen_opt.opt = opt;
bst_node = bst_find(&tmp_seen_opt,
&(ctx_inst->seen_opt_bst),
seen_opt_compare);
if (bst_node != NULL)
{
/* If found then it is added into the new BST tree. */
/* """""""""""""""""""""""""""""""""""""""""""""""" */
seen_opt = bst_node->key;
bst_search(seen_opt, &bst, seen_opt_compare);
}
else
/* Not found! That means that the option is unknown in this */
/* context as all options has have a seen_opt structure in */
/* seen_opt_bst. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
fatal_internal("%s is not known in the context %s.",
opt->name,
ctx->name);
}
else
fatal_internal("Unknown option %s.", opt_name);
opt_name = strtok(NULL, " \t");
}
free(str);
ll_append(ctx_inst->incomp_bst_list, bst);
node = node->next;
}
/* Initialize the list of res_t structures according to the */
/* list set in the context by ctxopt_add_ctx_settings/required. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
node = ctx->req_list->head;
while (node != NULL)
{
req_t *req = xmalloc(sizeof(req_t));
str = xstrdup(node->data);
ltrim(str, " \t");
rtrim(str, " \t", 0);
opt_name = strtok(str, " \t"); /* Extract the first option name. */
if ((opt = locate_opt(opt_name)) != NULL)
{
req->opt = opt;
req->or_opt_list = ll_new();
while ((opt_name = strtok(NULL, " \t")) != NULL)
{
if ((opt = locate_opt(opt_name)) != NULL)
ll_append(req->or_opt_list, opt);
else
fatal_internal("Unknown option %s.", opt_name);
}
ll_append(ctx_inst->opt_req_list, req);
}
else
fatal_internal("Unknown option %s.", opt_name);
free(str);
node = node->next;
}
return ctx_inst;
}
/* ====================================================================== */
/* Create a list formed by all the significant command line words */
/* Words beginning or ending with { or } are split. Each of these */
/* symbols will get their own place in the list. */
/* */
/* the {...} part delimits a context, the { will not appear in the list */
/* and the } will be replaced by a | in the resulting list (cmdline_list) */
/* to facilitate the parsing phase. | must not be used by the end user. */
/* */
/* IN nb_word : number of word to parse, this is typically argc-1 as the */
/* program name is not considered. */
/* IN words : is the array of strings constituting the command line to */
/* parse. */
/* Returns : 1 on success, 0 if a { or } is missing. */
/* ====================================================================== */
static int
ctxopt_build_cmdline_list(int nb_words, char **words)
{
int i;
char *prev_word = NULL;
char *word;
char *ptr;
int level = 0;
ll_node_t *node, *start_node;
/* The analysis is divided into three passes, this is not optimal but */
/* must be done only one time. Doing that we privilege readability. */
/* */
/* In the following, SG is the ASCII character 1d (dec 29) */
/* */
/* The first pass creates the list, extract the leading an trailing */
/* SG '{' and '}' of each word and give them their own place in the */
/* list */
/* */
/* The second pass transform the '{...}' blocks by a trailing SG */
/* ({...} -> ...|) */
/* */
/* The last pass remove the duplicated SG, check for SG, '{' or '}' in */
/* the middle in the remaining list elements and recreate the pseudo */
/* argument: {} */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
/* If the option list is not empty, clear it before going further. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (cmdline_list != NULL)
ll_destroy(cmdline_list, free);
cmdline_list = ll_new();
start_node = cmdline_list->head; /* In the following loop start_node will *
| contain a pointer to the current *
| word stripped from its leading *
| sequence of {, }. */
for (i = 0; i < nb_words; i++)
{
size_t len = strlen(words[i]);
size_t start, end;
char *str;
str = words[i];
/* Replace each occurrence of the legal word {} by the characters */
/* 0x02 and 0x03 to hide them from the following process. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
while ((ptr = strstr(str, "{}")) != NULL)
{
*ptr = 0x02; /* Arbitrary values unlikely */
*(ptr + 1) = 0x03; /* present in a word. */
}
if (len > 1) /* The word contains at least 2 characters. */
{
start = 0;
/* Interpret its beginning and look for the start of the real word. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
while (start <= len - 1 && (str[start] == '{' || str[start] == '}'))
{
ll_append(cmdline_list, xstrndup(str + start, 1));
start++;
start_node = cmdline_list->tail;
}
end = len - 1;
if (str[end] == '{' || str[end] == '}')
{
if (end > 0 && str[end - 1] != '\\')
{
ll_append(cmdline_list, xstrndup(str + end, 1));
end--;
node = cmdline_list->tail;
while (str[end] == '{' || str[end] == '}')
{
if (end > start && str[end - 1] == '\\')
break;
ll_insert_before(cmdline_list, node, xstrndup(str + end, 1));
end--;
node = node->prev;
}
}
}
if (start <= end)
{
if (start_node != NULL)
ll_insert_after(cmdline_list,
start_node,
xstrndup(str + start, end - start + 1));
else
ll_append(cmdline_list, xstrndup(str + start, end - start + 1));
start_node = cmdline_list->tail;
}
}
else if (len == 1)
{
ll_append(cmdline_list, xstrdup(str));
start_node = cmdline_list->tail;
}
}
/* 2nd pass. */
/* """"""""" */
node = cmdline_list->head;
level = 0;
while (node != NULL)
{
word = node->data;
if (strcmp(word, "{") == 0)
{
ll_node_t *old_node = node;
level++;
node = node->next;
free(word);
ll_delete(cmdline_list, old_node);
}
else if (strcmp(word, "}") == 0)
{
level--;
if (level < 0)
return 0;
else
*word = 0x1d;
}
else
node = node->next;
}
if (level != 0)
return 0;
/* 3rd pass. */
/* """"""""" */
node = cmdline_list->head;
while (node != NULL)
{
word = node->data;
/* Restore the original { and } characters forming the legal word {}. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
while ((ptr = strchr(word, 0x02)) != NULL)
*ptr = '{';
while ((ptr = strchr(word, 0x03)) != NULL)
*ptr = '}';
/* Remove a SG if the previous element is SG. */
/* """""""""""""""""""""""""""""""""""""""""" */
if (strcmp(word, "\x1d") == 0)
{
if (prev_word != NULL && (strcmp(prev_word, "\x1d") == 0))
{
ll_node_t *old_node = node;
node = node->prev;
free(old_node->data);
ll_delete(cmdline_list, old_node);
}
}
else if (strcmp(word, "-") == 0) /* A single - is a legal argument, not *
| a parameter. Protect it. */
{
free(node->data);
node->data = xstrdup("\\-");
}
prev_word = node->data;
node = node->next;
}
/* Clean useless and SG at the beginning and end of list. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""" */
node = cmdline_list->head;
if (node == NULL)
return 1;
word = node->data;
if (strcmp(word, "\x1d") == 0)
{
free(word);
ll_delete(cmdline_list, node);
}
node = cmdline_list->tail;
if (node == NULL)
return 1;
word = node->data;
if (strcmp(word, "\x1d") == 0)
{
free(word);
ll_delete(cmdline_list, node);
}
return 1;
}
/* ===================================================================== */
/* Build and analyze the command line list and create the linked data */
/* structures whose data will be evaluated later by ctxopt_evaluate. */
/* This function identifies the following errors and creates an array of */
/* The remaining not yet analyzed arguments. */
/* - detect missing arguments */
/* - detect too many arguments */
/* - detect unknown parameters in a context */
/* - detect too many occurrences of a parameters in a context */
/* - detect missing required arguments in a context */
/* */
/* IN nb_word : number of word to parse, this is typically argc-1 as the */
/* program name is not considered */
/* IN words : is the array of strings constituting the command line to */
/* parse. */
/* OUT nb_rem_args : nb of remaining command line arguments if a -- */
/* is present in the list. */
/* OUT rem_args : array of remaining command line arguments if a -- */
/* is present in the list. This array must be free by */
/* The caller as it is allocated here. */
/* ===================================================================== */
void
ctxopt_analyze(int nb_words, char **words, int *nb_rem_args, char ***rem_args)
{
char *ctxopt_debug_env; /* Environment variable CTXOPT_DEBUG content. */
int ctxopt_debug; /* 1 if ctxopt_debug_env is set and not empty. *
| 0 if ctxopt_debug_env is unset or empty. */
ctx_t *ctx;
opt_t *opt = NULL;
par_t *par;
ctx_inst_t *ctx_inst;
opt_inst_t *opt_inst;
int expect_par = 0;
int expect_arg = 0;
int expect_par_or_arg = 0;
ll_node_t *cli_node;
bst_t *bst_node;
seen_opt_t *bst_seen_opt;
char *par_name;
void *bst;
ll_node_t *node;
if (!ctxopt_build_cmdline_list(nb_words, words))
fatal_internal("The command line could not be parsed: "
"missing '{' or '}' detected.");
if (main_ctx == NULL)
fatal_internal("At least one context must have been created.");
/* Check that all options has an action and at least one parameter. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
bst_walk(options_bst, bst_check_opt_cb);
/* CTXOPT debug setting. */
/* """"""""""""""""""""" */
ctxopt_debug_env = getenv("CTXOPT_DEBUG");
if (ctxopt_debug_env != NULL && *ctxopt_debug_env != '\0')
ctxopt_debug = 1;
else
ctxopt_debug = 0;
/* Create the first ctx_inst record. */
/* """"""""""""""""""""""""""""""""" */
ctx = main_ctx;
ctx_inst_list = ll_new();
ctx_inst = new_ctx_inst(ctx, NULL);
ctx_inst->par_name = NULL;
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->ctx_name = ctx->name;
ll_append(ctx_inst_list, ctx_inst);
/* For each node in the command line. */
/* """""""""""""""""""""""""""""""""" */
cli_node = cmdline_list->head;
expect_par = 1;
par_name = NULL;
while (cli_node != NULL)
{
if (strcmp(cli_node->data, "--") == 0)
break; /* No new parameter will be analyzed after this point. */
par_name = cli_node->data;
/* Replace a leading -- by a single - */
/* """""""""""""""""""""""""""""""""" */
if (strncmp(par_name, "--", 2) == 0)
par_name += 1; /* Ignore the first dash. */
if (strcmp(par_name, "\x1d") == 0)
{
check_for_missing_mandatory_opt(ctx_inst, (char *)(cli_node->prev->data));
check_for_occurrence_issues(ctx_inst);
check_for_requirement_issues(ctx_inst);
/* Forced backtracking to the previous context instance. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
if (ctx_inst->prev_ctx_inst != NULL)
{
ctx_inst = ctx_inst->prev_ctx_inst;
ctx = ctx_inst->ctx;
/* Update current_states. */
/* """"""""""""""""""""" */
cur_state->ctx_name = ctx->name;
cur_state->ctx_par_name = ctx_inst->par_name;
if (ctxopt_debug)
fprintf(stderr,
"CTXOPT_DEBUG: Context forced backtrack, "
"new current context: %s.\n",
ctx->name);
}
else
{
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->ctx_par_name = NULL;
}
}
else if (expect_par && *par_name == '-')
{
int pos = 0;
char *prefix;
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->cur_opt_par_name = par_name;
cur_state->ctx_name = ctx->name;
cur_state->ctx_par_name = ctx_inst->par_name;
if (ctxopt_debug)
fprintf(stderr,
"CTXOPT_DEBUG: Parameter: %s. Current context: %s.\n",
par_name,
cur_state->ctx_name);
/* An expected parameter has been seen. */
/* """""""""""""""""""""""""""""""""""" */
if ((par = locate_par(par_name, ctx)) == NULL)
{
opt_t *popt;
char *word;
/* Look if this parameter is an unique abbreviation of a longer */
/* parameter. If this is the case then just replace it with its */
/* full length version and try again. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (flags.allow_abbreviations)
if ((word = abbrev_expand(par_name, ctx)) != NULL)
{
cli_node->data = word;
continue;
}
/* Try to find a prefix which is a valid parameter in this context */
/* If found, split the cli_node in two to build a new parameter */
/* node and followed by a node containing the remaining string */
/* If the new parameter corresponds to an option not taking */
/* argument then prefix the remaining string whit a dash as it may */
/* contain a new parameter. */
/* The new parameter will be re-evaluated in the next iteration of */
/* the loop. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""*/
prefix = look_for_valid_prefix_in_word(par_name, ctx, &pos, &popt);
if (prefix != NULL && pos != 0)
{
if (ctxopt_debug)
fprintf(stderr,
"CTXOPT_DEBUG: Found a valid parameter "
"as a prefix of %s: %s.\n",
par_name,
prefix);
cli_node->data = prefix; /* prefix contains le name of a valid *
| parameter in this context. */
if (popt->args)
{
/* The parameter may be followed by arguments. */
/* ''''''''''''''''''''''''''''''''''''''''''' */
if (*(par_name + pos) == '-')
{
word = xstrdup("\\"); /* Protect the '-' */
word = strappend(word, par_name + pos, (char *)0);
}
else
word = xstrdup(par_name + pos);
}
else
{
/* The parameter does not take arguments, the */
/* following word must be a parameter or nothing */
/* hence prefix it with a dash. */
/* ''''''''''''''''''''''''''''''''''''''''''''' */
word = xstrdup("-");
word = strappend(word, par_name + pos, (char *)0);
}
/* Insert it after the current node in the list. */
/* """"""""""""""""""""""""""""""""""""""""""""" */
ll_insert_after(cmdline_list, cli_node, word);
continue; /* loop. */
}
else
{
check_for_missing_mandatory_opt(ctx_inst, par_name);
check_for_occurrence_issues(ctx_inst);
check_for_requirement_issues(ctx_inst);
if (ctx_inst->prev_ctx_inst == NULL)
{
char *errmsg = xstrdup("");
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->ctx_par_name = NULL;
*user_string = '\0';
*user_string2 = '\0';
user_string = strappend(user_string, par_name, (char *)0);
bst_walk(contexts_bst, bst_match_par_cb);
if (*user_string2 != '\0')
{
char *help_msg;
int count = 0;
count = strchrcount(user_string2, '\n');
if (flags.display_usage_on_error)
help_msg = ", see below";
else
help_msg = "";
if (count == 0) /* Only one context involved. */
errmsg = strappend(
errmsg,
"\nThis parameter is only valid in the following "
"context:\n",
user_string2,
"\n\nFirst switch to this context using the appropriate "
"parameter",
help_msg,
".\n",
(char *)0);
else
errmsg = strappend(
errmsg,
"\nThis parameter is only valid in one of the following "
"contexts:\n",
user_string2,
"\n\nFirst switch to one of them using the appropriate "
"parameter",
help_msg,
".\n",
(char *)0);
}
fatal(CTXOPTUNKPAR, errmsg);
}
else
{
/* Tries to backtrack and analyse the same parameter in the */
/* previous context. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
ctx_inst = ctx_inst->prev_ctx_inst;
ctx = ctx_inst->ctx;
if (ctxopt_debug)
fprintf(stderr,
"CTXOPT_DEBUG: Context backtrack, "
"new current context: %s.\n",
ctx->name);
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->ctx_name = ctx->name;
cur_state->ctx_par_name = ctx_inst->par_name;
cli_node = cli_node->prev;
}
}
}
else
{
seen_opt_t seen_opt;
/* The parameter is valid in the context, create a opt_inst and */
/* append it to the ctx_inst list options list. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
opt = par->opt;
opt->occurrences++;
opt_inst = xmalloc(sizeof(opt_inst_t));
opt_inst->opt = opt;
opt_inst->par = par_name;
opt_inst->values_list = ll_new();
opt_inst->next_ctx_inst = NULL;
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->cur_opt_params = opt->params;
/* Priority option are inserted at the start of the opt_inst list */
/* but their order of appearance in the context definition must */
/* be preserver so each new priority option will be placed after */
/* the previous ones at the start of the opt_inst list. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (!opt->eval_first)
{
/* Look if we have a registered dependency in the order of the */
/* evaluation of two options. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (opt->eval_before_list->len > 0)
{
ll_t *list = ctx_inst->opt_inst_list;
ll_node_t *opt_inst_node;
ll_t *before_list = opt->eval_before_list;
ll_node_t *before_node = before_list->head;
ll_node_t *target_node = NULL; /* If not NULL, the new node *
| will be inserted before it. */
/* For each entry in eval_before_list, try to find if it */
/* refers to an option already entered in the context. If this */
/* is the case, insert it just before it instead of putting it */
/* at the end. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
while (before_node != NULL)
{
opt_inst_node = list->head;
while (opt_inst_node != target_node)
{
opt_t *tmp_opt = (((opt_inst_t *)opt_inst_node->data))->opt;
/* We have found an option mentioned if the before_list */
/* of the option we want to add. We can stop searching. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
if (strcmp(tmp_opt->name, ((opt_t *)before_node->data)->name))
opt_inst_node = opt_inst_node->next;
else
target_node = opt_inst_node; /* Set the target node. */
}
before_node = before_node->next;
}
/* Insert or append ? */
/* """""""""""""""""" */
if (target_node != NULL)
ll_insert_before(ctx_inst->opt_inst_list, target_node, opt_inst);
else
ll_append(ctx_inst->opt_inst_list, opt_inst);
}
else
ll_append(ctx_inst->opt_inst_list, opt_inst);
}
else
{
ll_node_t *opt_inst_node = ctx_inst->opt_inst_list->head;
opt_inst_t *tmp_opt_inst;
while (opt_inst_node != NULL)
{
tmp_opt_inst = opt_inst_node->data;
if (!tmp_opt_inst->opt->eval_first)
{
ll_insert_before(ctx_inst->opt_inst_list,
opt_inst_node,
opt_inst);
break;
}
else
opt_inst_node = opt_inst_node->next;
}
if (opt_inst_node == NULL)
ll_append(ctx_inst->opt_inst_list, opt_inst);
}
/* Check if an option was already seen in the */
/* current context instance. */
/* """""""""""""""""""""""""""""""""""""""""" */
seen_opt.opt = opt;
bst_node = bst_find(&seen_opt,
&(ctx_inst->seen_opt_bst),
seen_opt_compare);
/* bst_node cannot be NULL here. */
bst_seen_opt = (seen_opt_t *)(bst_node->key);
if (!opt->multiple && bst_seen_opt->seen == 1)
fatal(CTXOPTDUPOPT, "");
/* Check if this option is compatible with the options already */
/* seen in this context instance. */
/* Look if the option is present in one on the BST present in */
/* the incomp_bst_list of the context instance. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
node = ctx_inst->incomp_bst_list->head;
while (node != NULL)
{
bst = node->data;
user_object = NULL;
/* There can only have one seen_opt object in the BST tree was */
/* already seen, try to locate it, the result will be put in */
/* user_object by the bst_seen_opt_seen_cb function. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
bst_walk(bst, bst_seen_opt_seen_cb);
/* If it is the case, look if the current option is also */
/* in this BST. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""" */
if (user_object != NULL)
{
bst_node = bst_find(bst_seen_opt, &bst, seen_opt_compare);
if (bst_node != NULL)
{
bst_seen_opt = (seen_opt_t *)(bst_node->key);
if (bst_seen_opt->seen == 0)
fatal(CTXOPTINCOPT, (char *)user_object);
}
}
node = node->next;
}
/* Mark this option as seen in the current context instance. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""" */
bst_seen_opt->seen = 1;
free(bst_seen_opt->par);
bst_seen_opt->par = xstrdup(par_name);
/* If this option leads to a next context, create a new ctx_inst */
/* and switch to it for the analyse of the future parameter. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (opt->next_ctx != NULL)
{
ctx = locate_ctx(opt->next_ctx);
if (ctx == NULL)
fatal_internal("Unknown context %s.", opt->next_ctx);
opt_inst->next_ctx_inst = ctx_inst = new_ctx_inst(ctx, ctx_inst);
ctx_inst->par_name = xstrdup(par_name);
ll_append(ctx_inst_list, ctx_inst);
if (ctxopt_debug)
fprintf(stderr,
"CTXOPT_DEBUG: Context change, "
"new current context: %s.\n",
ctx->name);
}
/* Look is we must expect some arguments. */
/* """""""""""""""""""""""""""""""""""""" */
expect_par_or_arg = 0;
expect_par = 0;
expect_arg = 0;
if (!opt->args)
expect_par = 1; /* Parameter doesn't accept any argument. */
else
{
if (!opt->optional_args)
expect_arg = 1; /* Parameter has mandatory arguments. */
else
expect_par_or_arg = 1; /* Parameter has optional arguments. */
}
}
}
else if (expect_par && *par_name != '-')
{
ll_node_t *n = cli_node->next;
if (!flags.stop_if_non_option)
/* Look if potential arguments must still be analyzed until the */
/* end of the context/command line part to analyze/command line. */
/* If this is the case we have met an extra argument. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
while (n != NULL)
{
if (strcmp(n->data, "--") == 0 || strcmp(n->data, "\x1d") == 0)
fatal(CTXOPTUNXARG, "");
if (*(char *)(n->data) == '-')
fatal(CTXOPTUNXARG, "");
n = n->next;
}
break; /* An unexpected non parameter was seen, if no Potential *
| arguments remain in the command line or *
| flags.stop_if_non_option is set, assume that it is is *
| the first of the non arguments and stop the command *
| line analysis. */
}
else if (expect_arg && *par_name != '-')
{
ll_node_t *cstr_node;
constraint_t *cstr;
if (ctxopt_debug)
fprintf(stderr, "CTXOPT_DEBUG: Argument: %s.\n", par_name);
/* Check if the arguments of the option respects */
/* the attached constraints if any. */
/* """"""""""""""""""""""""""""""""""""""""""""" */
cstr_node = opt->constraints_list->head;
while (cstr_node != NULL)
{
cstr = cstr_node->data;
if (!cstr->constraint(cstr->nb_args,
cstr->args,
par_name,
cur_state->cur_opt_par_name))
{
fputs("\n", stderr);
ctxopt_ctx_disp_usage(cur_state->ctx_name, exit_after);
}
cstr_node = cstr_node->next;
}
/* If the argument is valid, store it. */
/* """"""""""""""""""""""""""""""""""" */
if (*par_name == '\\' && *(par_name + 1) == '-')
ll_append(opt_inst->values_list, par_name + 1);
else
ll_append(opt_inst->values_list, par_name);
expect_arg = 0;
expect_par = 0;
expect_par_or_arg = 0;
if (opt->multiple_args)
expect_par_or_arg = 1;
else
expect_par = 1; /* Parameter takes only one argument. */
}
else if (expect_arg && *par_name == '-')
fatal(CTXOPTMISARG, "");
else if (expect_par_or_arg)
{
expect_arg = 0;
expect_par = 0;
expect_par_or_arg = 0;
if (*par_name != '-')
expect_arg = 1; /* Consider this word as an argument and retry. */
else
expect_par = 1; /* Consider this word as a parameter and retry. */
cli_node = cli_node->prev;
}
cli_node = cli_node->next;
}
if (cmdline_list->len > 0 && par_name && *par_name == '-')
{
if (expect_arg && opt && !opt->optional_args)
fatal(CTXOPTMISARG, "");
}
/* Look if a context_instance has unseen mandatory options. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
node = ctx_inst_list->head;
while (node != NULL)
{
ctx_inst = node->data;
/* Update current_state. */
/* """"""""""""""""""""" */
cur_state->ctx_name = ctx_inst->ctx->name;
cur_state->ctx_par_name = ctx_inst->par_name;
check_for_missing_mandatory_opt(ctx_inst, par_name);
check_for_occurrence_issues(ctx_inst);
check_for_requirement_issues(ctx_inst);
node = node->next;
}
/* Allocate the array containing the remaining not analyzed */
/* command line arguments. */
/* NOTE: The strings in the array are just pointer to the */
/* data of the generating list and must not be freed. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (cli_node != NULL)
{
if (strcmp((char *)cli_node->data, "--") == 0)
/* The special parameter -- was encountered, the -- argument is not */
/* put in the remaining arguments. */
/* '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' */
ll_strarray(cmdline_list, cli_node->next, nb_rem_args, rem_args);
else
/* A non parameter was encountered when a parameter was expected. We */
/* assume that the evaluation of the remaining command line argument */
/* are not the responsibility of the users code. */
/* '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' */
ll_strarray(cmdline_list, cli_node, nb_rem_args, rem_args);
}
else
{
*nb_rem_args = 0;
*rem_args = xmalloc(sizeof(char *));
(*rem_args)[0] = NULL;
}
}
/* ==================================================== */
/* Free ctxopt memory used for its internal structures. */
/* ==================================================== */
void
ctxopt_free_memory(void)
{
ll_destroy(cmdline_list, free);
ll_destroy(ctx_inst_list, ctx_inst_free);
bst_destroy(options_bst, opt_free);
bst_destroy(contexts_bst, ctx_free);
}
/* ==================================================================== */
/* Parse the options data structures and launches the callback function */
/* attached to each options instances. */
/* This calls a recursive function which proceeds context per context. */
/* ==================================================================== */
void
ctxopt_evaluate(void)
{
evaluate_ctx_inst(first_ctx_inst);
}
/* =================================================================== */
/* Recursive function called by ctxopt_evaluate to process the list of */
/* the opt_inst present in a ctx_inst and attempt to evaluate the */
/* action attached to the context and its option instances. */
/* =================================================================== */
static void
evaluate_ctx_inst(ctx_inst_t *ctx_inst)
{
opt_inst_t *opt_inst;
ctx_t *ctx;
opt_t *opt;
ll_node_t *opt_inst_node;
char **args;
int nb_args;
if (ctx_inst == NULL)
return;
ctx = ctx_inst->ctx;
/* Do not evaluate the action attached to this context is there is no */
/* option to evaluate. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
opt_inst_node = ctx_inst->opt_inst_list->head;
if (opt_inst_node == NULL)
return;
/* Call the entering action attached to this context if any. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (ctx->action != NULL)
{
if (ctx_inst->prev_ctx_inst != NULL)
ctx->action(ctx->name,
entering,
ctx_inst->prev_ctx_inst->ctx->name,
ctx->nb_data,
ctx->data);
else
ctx->action(ctx->name, entering, NULL, ctx->nb_data, ctx->data);
}
/* For each instance of options. */
/* """"""""""""""""""""""""""""" */
while (opt_inst_node != NULL)
{
opt_inst = (opt_inst_t *)(opt_inst_node->data);
ll_strarray(opt_inst->values_list,
opt_inst->values_list->head,
&nb_args,
&args);
opt = opt_inst->opt;
/* Launch the attached action if any. */
/* """""""""""""""""""""""""""""""""" */
if (opt->action != NULL)
opt->action(ctx->name,
opt->name,
opt_inst->par,
nb_args,
args,
opt->nb_data,
opt->data,
ctx->nb_data,
ctx->data);
if (opt_inst->next_ctx_inst != NULL)
evaluate_ctx_inst(opt_inst->next_ctx_inst);
if (args != NULL)
free(args);
opt_inst_node = opt_inst_node->next;
}
/* Call the exiting action attached to this context if any. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
if (ctx->action != NULL)
{
if (ctx_inst->prev_ctx_inst != NULL)
ctx->action(ctx->name,
exiting,
ctx_inst->prev_ctx_inst->ctx->name,
ctx->nb_data,
ctx->data);
else
ctx->action(ctx->name, exiting, NULL, ctx->nb_data, ctx->data);
}
}
/* ============================================================ */
/* Create and initializes a new context. */
/* - allocate space. */
/* - name it. */
/* - initialize its option with a few of their characteristics. */
/* ============================================================ */
void
ctxopt_new_ctx(char *name, char *opts_specs)
{
ctx_t *ctx;
char *p;
if (!ctxopt_initialized)
fatal_internal("Please call ctxopt_init first.");
ctx = xmalloc(sizeof(ctx_t));
/* Validates the context name: */
/* ALPHA+(ALPHANUM|_)* */
/* """"""""""""""""""""""""""" */
p = name;
if (*p == '\0' || !isalpha(*p))
fatal_internal("A context name must start with a letter: %s.", name);
p++;
while (*p)
{
if (!isalnum(*p) && *p != '_')
fatal_internal("A context name must only contain letters, "
"numbers or '_': %s.",
name);
p++;
}
ctx->name = xstrdup(name);
ctx->opt_list = ll_new(); /* List of options legit in this context. */
ctx->incomp_list = ll_new(); /* List of incompatible options strings. */
ctx->req_list = ll_new(); /* List of opts/required opts tuples (str). */
ctx->par_bst = NULL;
ctx->data = NULL;
ctx->action = NULL;
/* The first created context is the main one. */
/* """""""""""""""""""""""""""""""""""""""""" */
if (contexts_bst == NULL)
{
main_ctx = ctx;
cur_state->ctx_name = ctx->name;
}
if (init_opts(opts_specs, ctx) == 0)
exit(EXIT_FAILURE);
if (bst_find(ctx, &contexts_bst, ctx_compare) != NULL)
fatal_internal("The context %s already exists.", name);
else
bst_search(ctx, &contexts_bst, ctx_compare);
}
/* ==================================================== */
/* Display a usage screen limited to a specific context */
/* IN: the context name. */
/* IN: what to do after (continue or exit the program) */
/* possible values: continue_after, exit_after. */
/* ==================================================== */
void
ctxopt_ctx_disp_usage(char *ctx_name, usage_behaviour action)
{
ctx_t *ctx;
ll_t *list;
int has_optional = 0;
int has_ellipsis = 0;
int has_rule = 0;
int has_generic_arg = 0;
int has_ctx_change = 0;
int has_early_eval = 0;
if (!flags.display_usage_on_error)
return;
ctx = NULL;
if (ctx_name != NULL)
ctx = locate_ctx(ctx_name);
else
ctx = locate_ctx(cur_state->ctx_name);
if (ctx == NULL)
fatal_internal("Unknown context %s.", ctx_name);
if (cur_state->ctx_par_name == NULL)
printf("\nSynopsis:\n%s \\\n", cur_state->prog_name);
else
printf("\nSynopsis for the context introduced by %s:\n",
cur_state->ctx_par_name);
list = ctx->opt_list;
print_options(list,
&has_optional,
&has_ellipsis,
&has_rule,
&has_generic_arg,
&has_ctx_change,
&has_early_eval);
print_before_constraints(list);
print_explanations(has_early_eval,
has_ctx_change,
has_generic_arg,
has_optional,
has_ellipsis,
has_rule);
if (action == exit_after)
exit(EXIT_FAILURE);
}
/* =================================================== */
/* Display a full usage screen about all contexts. */
/* IN: what to do after (continue or exit the program) */
/* possible values: continue_after, exit_after. */
/* =================================================== */
void
ctxopt_disp_usage(usage_behaviour action)
{
ll_t *list;
int has_optional = 0;
int has_ellipsis = 0;
int has_rule = 0;
int has_generic_arg = 0;
int has_ctx_change = 0;
int has_early_eval = 0;
if (!flags.display_usage_on_error)
return;
if (main_ctx == NULL)
fatal_internal("At least one context must have been created.");
/* Usage for the first context. */
/* """""""""""""""""""""""""""" */
printf("\nAllowed options in the base context:\n");
list = main_ctx->opt_list;
print_options(list,
&has_optional,
&has_ellipsis,
&has_rule,
&has_generic_arg,
&has_ctx_change,
&has_early_eval);
/* Dependency constraints between options. */
/* """"""""""""""""""""""""""""""""""""""" */
print_before_constraints(list);
/* Usage for the other contexts. */
/* """"""""""""""""""""""""""""" */
bst_walk(contexts_bst, bst_print_ctx_cb);
/* Contextual syntactic explanations. */
/* """""""""""""""""""""""""""""""""" */
print_explanations(has_early_eval,
has_ctx_change,
has_generic_arg,
has_optional,
has_ellipsis,
has_rule);
if (action == exit_after)
exit(EXIT_FAILURE);
}
/* ************************************ */
/* Built-in constraint check functions. */
/* ************************************ */
/* ============================================================= */
/* This constraint checks if each arguments respects a format as */
/* defined for the scanf function. */
/* return 1 if yes and 0 if no. */
/* ============================================================= */
int
ctxopt_format_constraint(int nb_args, char **args, char *value, char *par)
{
int rc = 0;
char x[256];
char y;
char *format;
if (nb_args != 1)
fatal_internal("Format constraint, invalid number of parameters.");
if (strlen(value) > 255)
value[255] = '\0';
format = xstrdup(args[0]);
format = strappend(format, "%c", (char *)0);
rc = sscanf(value, format, x, &y);
if (rc != 1)
fprintf(stderr,
"The argument %s of %s does not respect the imposed format %s.",
value,
par,
args[0]);
free(format);
return rc == 1;
}
/* ================================================================== */
/* This constraint checks if each arguments of the option instance is */
/* between a minimum and a maximum (inclusive). */
/* return 1 if yes and 0 if no. */
/* ================================================================== */
int
ctxopt_re_constraint(int nb_args, char **args, char *value, char *par)
{
regex_t re;
if (nb_args != 1)
fatal_internal(
"Regular expression constraint, invalid number of parameters.");
if (regcomp(&re, args[0], REG_EXTENDED) != 0)
fatal_internal("Invalid regular expression %s.", args[0]);
if (regexec(&re, value, (size_t)0, NULL, 0) != 0)
{
fprintf(stderr,
"The argument %s of %s doesn't match the constraining "
"regular expression %s.",
value,
par,
args[0]);
return 0;
}
regfree(&re);
return 1;
}
/* ================================================================== */
/* This constraint checks if each arguments of the option instance is */
/* between a minimum and a maximum (inclusive). */
/* return 1 if yes and 0 if no. */
/* ================================================================== */
int
ctxopt_range_constraint(int nb_args, char **args, char *value, char *par)
{
long min = LONG_MIN, max = LONG_MAX;
char c;
char *ptr;
int n;
long v;
int min_only = 0;
int max_only = 0;
if (nb_args != 2)
fatal_internal("Range constraint, invalid number of parameters.");
n = 0;
if (strcmp(args[0], ".") == 0)
max_only = 1;
else
n = sscanf(args[0], "%ld%c", &min, &c);
if (!max_only && n != 1)
fatal_internal("Range constraint, min: invalid parameters.");
n = 0;
if (strcmp(args[1], ".") == 0)
min_only = 1;
else
n = sscanf(args[1], "%ld%c", &max, &c);
if (!min_only && n != 1)
fatal_internal("Range constraint, max: invalid parameters.");
if (min_only && max_only)
fatal_internal("Range constraint, invalid parameters.");
errno = 0;
v = strtol(value, &ptr, 10);
if (errno || ptr == value)
return 0;
if (min_only)
{
if (v < min)
{
fprintf(stderr,
"The argument %ld of %s is not greater than or equal to %ld.",
v,
par,
min);
return 0;
}
else
return 1;
}
else if (max_only)
{
if (v > max)
{
fprintf(stderr,
"The argument %ld of %s is not less than or equal to %ld.",
v,
par,
max);
return 0;
}
else
return 1;
}
else if (v < min || v > max)
{
fprintf(stderr,
"The argument %ld of %s is not between %ld and %ld.",
v,
par,
min,
max);
return 0;
}
return 1; /* Check passed. */
}
/* =============================================================== */
/* This function provides a way to set the behaviour of a context. */
/* =============================================================== */
void
ctxopt_add_global_settings(settings s, ...)
{
va_list(args);
va_start(args, s);
switch (s)
{
case error_functions:
{
typedef void fn(errors e, state_t * state);
void (*function)(errors e, state_t *state);
errors e;
e = va_arg(args, errors);
function = va_arg(args, fn *);
err_functions[e] = function;
break;
}
default:
break;
}
va_end(args);
}
/* ================================================================ */
/* This function provides a way to set the behaviour of an option. */
/* It can take a variable number of arguments according to its */
/* first argument: */
/* - parameter: */
/* o a string containing an option name and all its possible */
/* parameters separates by spaces, tabs or commas (char *) */
/* (e.g: "help -h -help"). */
/* - actions: */
/* o a string containing an option name. */
/* o a pointer to a function which will be called at evaluation */
/* time. */
/* - constraints: */
/* o a string containing an option name. */
/* o a pointer to a function to check if an argument is valid. */
/* o a strings containing the arguments to this function. */
/* - visible_in_help: */
/* o a string containing an option name. */
/* o the string "yes" or "no" (case insensitive) which will */
/* determine if the option must be seen in help/usage. */
/* ================================================================ */
void
ctxopt_add_opt_settings(settings s, ...)
{
opt_t *opt = NULL;
void *ptr = NULL;
va_list(args);
va_start(args, s);
switch (s)
{
/* This part associates some command line parameters to an option. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
case parameters:
{
char *opt_name = NULL;
char *params;
/* The second argument must be a string containing: */
/* - The name of an existing option. */
/* - a list of parameters with a leading dash (-). */
/* """""""""""""""""""""""""""""""""""""""""""""""" */
ptr = va_arg(args, char *);
opt_name = ptr;
if (opt_name != NULL)
{
if ((opt = locate_opt(opt_name)) != NULL)
{
ptr = va_arg(args, char *);
params = ptr;
if (!opt_set_parms(opt_name, params))
fatal_internal(
"Duplicated parameters or bad settings for the option %s.",
params);
}
else
fatal_internal("Unknown option %s.", opt_name);
}
else
fatal_internal(
"ctxopt_opt_add_settings: parameters: not enough arguments.");
/* Here opt is a known option. */
/* """"""""""""""""""""""""""" */
if (opt->params != NULL)
fatal_internal("Parameters are already set for %s.", opt_name);
else
{
size_t n;
size_t l = strlen(params);
opt->params = xstrdup(params);
while ((n = strcspn(opt->params, " \t")) < l)
opt->params[n] = '|';
}
break;
}
/* This part associates a callback function to an option. */
/* This function will be called when an instance of an option */
/* is evaluated. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
case actions:
{
void *data;
void (*function)(char *,
char *,
char *,
int,
char **,
int,
void **,
int,
void **);
int nb_data = 0;
/* The second argument must be the name of an existing option. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
ptr = va_arg(args, char *);
if ((opt = locate_opt(ptr)) != NULL)
{
typedef void
fn(char *, char *, char *, int, char **, int, void **, int, void **);
/* The third argument must be the callback function. */
/* """"""""""""""""""""""""""""""""""""""""""""""""" */
function = va_arg(args, fn *);
opt->action = function;
/* The fourth argument must be a pointer to an user's defined */
/* variable or structure that the previous function can manage. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
while ((data = va_arg(args, void *)) != NULL)
{
nb_data++;
opt->data = xrealloc(opt->data, nb_data * sizeof(void *));
opt->data[nb_data - 1] = data;
}
opt->nb_data = nb_data;
}
else
fatal_internal("Unknown option %s.", ptr);
break;
}
/* This part associates a list of functions to control some */
/* characteristics of the arguments of an option. */
/* Each function will be called in order and must return 1 */
/* to validate the arguments. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
case constraints:
{
char *value;
constraint_t *cstr;
int (*function)(int, char **, char *, char *);
/* The second argument must be a string. */
/* """"""""""""""""""""""""""""""""""""" */
ptr = va_arg(args, char *);
if ((opt = locate_opt(ptr)) != NULL)
{
typedef int fn(int, char **, char *, char *);
/* The third argument must be a function. */
/* """""""""""""""""""""""""""""""""""""" */
function = va_arg(args, fn *);
cstr = xmalloc(sizeof(constraint_t));
cstr->constraint = function;
/* The fourth argument must be a string containing the argument of */
/* The previous function separated by spaces or tabs. */
/* Theses arguments will be passed to the previous function */
/* max: 32 argument! */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
value = xstrdup(va_arg(args, char *));
cstr->to_free = value;
cstr->args = xcalloc(sizeof(char *), 32);
cstr->nb_args = str2argv(value, cstr->args, 32);
ll_append(opt->constraints_list, cstr);
}
else
fatal_internal("Unknown option %s.", ptr);
break;
}
/* This part allows to indicate that an option must be evaluated */
/* after a list of other options. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
case after:
{
char *str;
/* The second argument must be a string. */
/* """"""""""""""""""""""""""""""""""""" */
ptr = va_arg(args, char *);
if ((opt = locate_opt(ptr)) != NULL)
{
char *end_str;
char *opt_name;
opt_t *opt_before;
ptr = va_arg(args, char *);
str = xstrdup(ptr);
ltrim(str, " \t");
rtrim(str, " \t", 0);
/* Feed the list of options to be evaluated after the given option. */
/* This list will contain pointers to options. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
opt_name = xstrtok_r(str, " \t,", &end_str);
if (opt_name != NULL)
{
if ((opt_before = locate_opt(opt_name)) != NULL)
{
ll_append(opt->eval_before_list, opt_before);
while ((opt_name = xstrtok_r(NULL, " \t,", &end_str)) != NULL)
{
if ((opt_before = locate_opt(opt_name)) != NULL)
ll_append(opt->eval_before_list, opt_before);
else
fatal_internal("Unknown option %s.", opt_name);
}
}
else
fatal_internal("Unknown option %s.", opt_name);
}
else
fatal_internal("Not enough options to be evaluated after %s.",
opt->name);
free(str);
}
else
fatal_internal("Unknown option %s.", ptr);
break;
}
/* This part allows to indicate that an option must be evaluated */
/* before a list of other options. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
case before:
{
char *str;
/* The second argument must be a string. */
/* """"""""""""""""""""""""""""""""""""" */
ptr = va_arg(args, char *);
if ((opt = locate_opt(ptr)) != NULL)
{
char *end_str;
char *opt_name;
opt_t *opt_before;
ptr = va_arg(args, char *);
str = xstrdup(ptr);
ltrim(str, " \t");
rtrim(str, " \t", 0);
/* Feed the list of options to be evaluated before the given option. */
/* This list will contain pointers to options. */
/* """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" */
opt_name = xstrtok_r(str, " \t,", &end_str);
if (opt_name != NULL)
{
if ((opt_before = locate_opt(opt_name)) != NULL)
{
ll_append(opt_before->eval_before_list, opt);
while ((opt_name = xstrtok_r(NULL, " \t,", &end_str)) != NULL)
{
if ((opt_before = locate_opt(opt_name)) != NULL)
ll_append(opt_before->eval_before_list, opt);
else
fatal_internal("Unknown option %s.", opt_name);
}
}
else
fatal_internal("Unknown option %s.", opt_name);
}
else
fatal_internal("Not enough options to be evaluated before %s.",
opt->name);
free(str);
}
else
fatal_internal("Unknown option %s.", ptr);
break;
}
case visible_in_help:
{
char *opt_name;
char *toggle;
/* The second argument must be a string containing */
/* The name of an existing option. */
/* """"""""""""""""""""""""""""""""""""""""""""""" */
ptr = va_arg(args, char *);
opt_name = ptr;
if (opt_name != NULL)
{
if ((opt = locate_opt(opt_name)) != NULL)
{
ptr = va_arg(args, char *);
toggle = ptr;
if (stricmp(toggle, "yes") == 0)
opt->visible_in_help = 1;
else if (stricmp(toggle, "no") == 0)
opt->visible_in_help = 0;
else
fatal_internal("The value for the visible_in_help setting must be "
"\"yes\" or \"no\" (case insensitive).",
toggle);
}
else
fatal_internal("Unknown option %s.", opt_name);
}
else
fatal_internal(
"ctxopt_opt_add_settings: visible_in_help: not enough arguments.");
break;
}
default:
break;
}
va_end(args);
}
/* =============================================================== */
/* This function provides a way to set the behaviour of a context. */
/* =============================================================== */
void
ctxopt_add_ctx_settings(settings s, ...)
{
ctx_t *ctx;
va_list(args);
va_start(args, s);
switch (s)
{
/* Add a set of mutually incompatible options in a context. */
/* """""""""""""""""""""""""""""""""""""""""""""""""""""""" */
case incompatibilities:
{
void *ptr;
ll_t *list;
size_t n;
char *str;
ptr = va_arg(args, char *);
if ((ctx = locate_ctx(ptr)) != NULL)
{
ptr = va_arg(args, char *);
list = ctx->incomp_list;
str = xstrdup(ptr);
ltrim(str, " \t");
rtrim(str, " \t", 0);
n = strcspn(str, " \t");
if (n > 0 && n < strlen(str))
ll_append(list, str);
else
fatal_internal(
"Not enough incompatible options in the string: \"%s\".",
str);
}
else
fatal_internal("Unknown context %s.", ptr);
break;
}
case requirements:
{
void *ptr;
ll_t *list;
size_t n;
char *str;
ptr = va_arg(args, char *);
if ((ctx = locate_ctx(ptr)) != NULL)
{
ptr = va_arg(args, char *);
list = ctx->req_list;
str = xstrdup(ptr);
ltrim(str, " \t");
rtrim(str, " \t", 0);
n = strcspn(str, " \t");
if (n > 0 && n < strlen(str))
ll_append(list, str);
else
fatal_internal("Not enough required options in the string: \"%s\".",
str);
}
else
fatal_internal("Unknown context %s.", ptr);
break;
}
/* Add functions which will be called when */
/* entering and exiting a context. */
/* """"""""""""""""""""""""""""""""""""""" */
case actions:
{
void *ptr;
void *data;
int (*function)(char *, int, char *, int, void **);
int nb_data = 0;
ptr = va_arg(args, char *);
if ((ctx = locate_ctx(ptr)) != NULL)
{
typedef int fn(char *, int, char *, int, void **);
function = va_arg(args, fn *);
ctx->action = function;
while ((data = va_arg(args, void *)) != NULL)
{
nb_data++;
ctx->data = xrealloc(ctx->data, nb_data * sizeof(void *));
ctx->data[nb_data - 1] = data;
}
ctx->nb_data = nb_data;
}
else
fatal_internal("Unknown context %s.", ptr);
break;
}
default:
break;
}
va_end(args);
}
|