1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413
|
/*****************************************************************************
* ___ _ _ ___ ___
* | _|| | | | | _ \ _ \ CLIPP - command line interfaces for modern C++
* | |_ | |_ | | | _/ _/ version 1.1.0
* |___||___||_| |_| |_| https://github.com/muellan/clipp
*
* Licensed under the MIT License <http://opensource.org/licenses/MIT>.
* Copyright (c) 2017 André Müller <foss@andremueller-online.de>
*
* ---------------------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef AM_CLIPP_H__
#define AM_CLIPP_H__
#include <cstring>
#include <string>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <memory>
#include <vector>
#include <limits>
#include <stack>
#include <algorithm>
#include <sstream>
#include <utility>
#include <iterator>
#include <functional>
/*************************************************************************//**
*
* @brief primary namespace
*
*****************************************************************************/
namespace clipp {
/*****************************************************************************
*
* basic constants and datatype definitions
*
*****************************************************************************/
using arg_index = int;
using arg_string = std::string;
using doc_string = std::string;
using arg_list = std::vector<arg_string>;
/*************************************************************************//**
*
* @brief tristate
*
*****************************************************************************/
enum class tri : char { no, yes, either };
inline constexpr bool operator == (tri t, bool b) noexcept {
return b ? t != tri::no : t != tri::yes;
}
inline constexpr bool operator == (bool b, tri t) noexcept { return (t == b); }
inline constexpr bool operator != (tri t, bool b) noexcept { return !(t == b); }
inline constexpr bool operator != (bool b, tri t) noexcept { return !(t == b); }
/*************************************************************************//**
*
* @brief (start,size) index range
*
*****************************************************************************/
class subrange {
public:
using size_type = arg_string::size_type;
/** @brief default: no match */
explicit constexpr
subrange() noexcept :
at_{arg_string::npos}, length_{0}
{}
/** @brief match length & position within subject string */
explicit constexpr
subrange(size_type pos, size_type len) noexcept :
at_{pos}, length_{len}
{}
/** @brief position of the match within the subject string */
constexpr size_type at() const noexcept { return at_; }
/** @brief length of the matching subsequence */
constexpr size_type length() const noexcept { return length_; }
/** @brief returns true, if query string is a prefix of the subject string */
constexpr bool prefix() const noexcept {
return at_ == 0 && length_ > 0;
}
/** @brief returns true, if query is a substring of the query string */
constexpr explicit operator bool () const noexcept {
return at_ != arg_string::npos && length_ > 0;
}
private:
size_type at_;
size_type length_;
};
/*************************************************************************//**
*
* @brief match predicates
*
*****************************************************************************/
using match_predicate = std::function<bool(const arg_string&)>;
using match_function = std::function<subrange(const arg_string&)>;
/*************************************************************************//**
*
* @brief type traits (NOT FOR DIRECT USE IN CLIENT CODE!)
* no interface guarantees; might be changed or removed in the future
*
*****************************************************************************/
namespace traits {
/*************************************************************************//**
*
* @brief function (class) signature type trait
*
*****************************************************************************/
template<class Fn, class Ret, class... Args>
constexpr auto
check_is_callable(int) -> decltype(
std::declval<Fn>()(std::declval<Args>()...),
std::integral_constant<bool,
std::is_same<Ret,typename std::result_of<Fn(Args...)>::type>::value>{} );
template<class,class,class...>
constexpr auto
check_is_callable(long) -> std::false_type;
template<class Fn, class Ret>
constexpr auto
check_is_callable_without_arg(int) -> decltype(
std::declval<Fn>()(),
std::integral_constant<bool,
std::is_same<Ret,typename std::result_of<Fn()>::type>::value>{} );
template<class,class>
constexpr auto
check_is_callable_without_arg(long) -> std::false_type;
template<class Fn, class... Args>
constexpr auto
check_is_void_callable(int) -> decltype(
std::declval<Fn>()(std::declval<Args>()...), std::true_type{});
template<class,class,class...>
constexpr auto
check_is_void_callable(long) -> std::false_type;
template<class Fn>
constexpr auto
check_is_void_callable_without_arg(int) -> decltype(
std::declval<Fn>()(), std::true_type{});
template<class>
constexpr auto
check_is_void_callable_without_arg(long) -> std::false_type;
template<class Fn, class Ret>
struct is_callable;
template<class Fn, class Ret, class... Args>
struct is_callable<Fn, Ret(Args...)> :
decltype(check_is_callable<Fn,Ret,Args...>(0))
{};
template<class Fn, class Ret>
struct is_callable<Fn,Ret()> :
decltype(check_is_callable_without_arg<Fn,Ret>(0))
{};
template<class Fn, class... Args>
struct is_callable<Fn, void(Args...)> :
decltype(check_is_void_callable<Fn,Args...>(0))
{};
template<class Fn>
struct is_callable<Fn,void()> :
decltype(check_is_void_callable_without_arg<Fn>(0))
{};
/*************************************************************************//**
*
* @brief input range type trait
*
*****************************************************************************/
template<class T>
constexpr auto
check_is_input_range(int) -> decltype(
begin(std::declval<T>()), end(std::declval<T>()),
std::true_type{});
template<class T>
constexpr auto
check_is_input_range(char) -> decltype(
std::begin(std::declval<T>()), std::end(std::declval<T>()),
std::true_type{});
template<class>
constexpr auto
check_is_input_range(long) -> std::false_type;
template<class T>
struct is_input_range :
decltype(check_is_input_range<T>(0))
{};
/*************************************************************************//**
*
* @brief size() member type trait
*
*****************************************************************************/
template<class T>
constexpr auto
check_has_size_getter(int) ->
decltype(std::declval<T>().size(), std::true_type{});
template<class>
constexpr auto
check_has_size_getter(long) -> std::false_type;
template<class T>
struct has_size_getter :
decltype(check_has_size_getter<T>(0))
{};
} // namespace traits
/*************************************************************************//**
*
* @brief helpers (NOT FOR DIRECT USE IN CLIENT CODE!)
* no interface guarantees; might be changed or removed in the future
*
*****************************************************************************/
namespace detail {
/*************************************************************************//**
* @brief forwards string to first non-whitespace char;
* std string -> unsigned conv yields max value, but we want 0;
* also checks for nullptr
*****************************************************************************/
inline bool
fwd_to_unsigned_int(const char*& s)
{
if(!s) return false;
for(; std::isspace(*s); ++s);
if(!s[0] || s[0] == '-') return false;
if(s[0] == '-') return false;
return true;
}
/*************************************************************************//**
*
* @brief value limits clamping
*
*****************************************************************************/
template<class T, class V, bool = (sizeof(V) > sizeof(T))>
struct limits_clamped {
static T from(const V& v) {
if(v > V(std::numeric_limits<T>::max())) {
return std::numeric_limits<T>::max();
}
if(v < V(std::numeric_limits<T>::lowest())) {
return std::numeric_limits<T>::lowest();
}
return T(v);
}
};
template<class T, class V>
struct limits_clamped<T,V,false> {
static T from(const V& v) { return T(v); }
};
/*************************************************************************//**
*
* @brief returns value of v as a T, clamped at T's maximum
*
*****************************************************************************/
template<class T, class V>
inline T clamped_on_limits(const V& v) {
return limits_clamped<T,V>::from(v);
}
/*************************************************************************//**
*
* @brief type conversion helpers
*
*****************************************************************************/
template<class T>
struct make {
static inline T from(const char* s) {
if(!s) return false;
//a conversion from const char* to / must exist
return static_cast<T>(s);
}
};
template<>
struct make<bool> {
static inline bool from(const char* s) {
if(!s) return false;
return static_cast<bool>(s);
}
};
template<>
struct make<unsigned char> {
static inline unsigned char from(const char* s) {
if(!fwd_to_unsigned_int(s)) return (0);
return clamped_on_limits<unsigned char>(std::strtoull(s,nullptr,10));
}
};
template<>
struct make<unsigned short int> {
static inline unsigned short int from(const char* s) {
if(!fwd_to_unsigned_int(s)) return (0);
return clamped_on_limits<unsigned short int>(std::strtoull(s,nullptr,10));
}
};
template<>
struct make<unsigned int> {
static inline unsigned int from(const char* s) {
if(!fwd_to_unsigned_int(s)) return (0);
return clamped_on_limits<unsigned int>(std::strtoull(s,nullptr,10));
}
};
template<>
struct make<unsigned long int> {
static inline unsigned long int from(const char* s) {
if(!fwd_to_unsigned_int(s)) return (0);
return clamped_on_limits<unsigned long int>(std::strtoull(s,nullptr,10));
}
};
template<>
struct make<unsigned long long int> {
static inline unsigned long long int from(const char* s) {
if(!fwd_to_unsigned_int(s)) return (0);
return clamped_on_limits<unsigned long long int>(std::strtoull(s,nullptr,10));
}
};
template<>
struct make<char> {
static inline char from(const char* s) {
//parse as single character?
const auto n = std::strlen(s);
if(n == 1) return s[0];
//parse as integer
return clamped_on_limits<char>(std::strtoll(s,nullptr,10));
}
};
template<>
struct make<short int> {
static inline short int from(const char* s) {
return clamped_on_limits<short int>(std::strtoll(s,nullptr,10));
}
};
template<>
struct make<int> {
static inline int from(const char* s) {
return clamped_on_limits<int>(std::strtoll(s,nullptr,10));
}
};
template<>
struct make<long int> {
static inline long int from(const char* s) {
return clamped_on_limits<long int>(std::strtoll(s,nullptr,10));
}
};
template<>
struct make<long long int> {
static inline long long int from(const char* s) {
return (std::strtoll(s,nullptr,10));
}
};
template<>
struct make<float> {
static inline float from(const char* s) {
return (std::strtof(s,nullptr));
}
};
template<>
struct make<double> {
static inline double from(const char* s) {
return (std::strtod(s,nullptr));
}
};
template<>
struct make<long double> {
static inline long double from(const char* s) {
return (std::strtold(s,nullptr));
}
};
template<>
struct make<std::string> {
static inline std::string from(const char* s) {
return std::string(s);
}
};
/*************************************************************************//**
*
* @brief assigns boolean constant to one or multiple target objects
*
*****************************************************************************/
template<class T, class V = T>
class assign_value
{
public:
template<class X>
explicit constexpr
assign_value(T& target, X&& value) noexcept :
t_{std::addressof(target)}, v_{std::forward<X>(value)}
{}
void operator () () const {
if(t_) *t_ = v_;
}
private:
T* t_;
V v_;
};
/*************************************************************************//**
*
* @brief flips bools
*
*****************************************************************************/
class flip_bool
{
public:
explicit constexpr
flip_bool(bool& target) noexcept :
b_{&target}
{}
void operator () () const {
if(b_) *b_ = !*b_;
}
private:
bool* b_;
};
/*************************************************************************//**
*
* @brief increments using operator ++
*
*****************************************************************************/
template<class T>
class increment
{
public:
explicit constexpr
increment(T& target) noexcept : t_{std::addressof(target)} {}
void operator () () const {
if(t_) ++(*t_);
}
private:
T* t_;
};
/*************************************************************************//**
*
* @brief decrements using operator --
*
*****************************************************************************/
template<class T>
class decrement
{
public:
explicit constexpr
decrement(T& target) noexcept : t_{std::addressof(target)} {}
void operator () () const {
if(t_) --(*t_);
}
private:
T* t_;
};
/*************************************************************************//**
*
* @brief increments by a fixed amount using operator +=
*
*****************************************************************************/
template<class T>
class increment_by
{
public:
explicit constexpr
increment_by(T& target, T by) noexcept :
t_{std::addressof(target)}, by_{std::move(by)}
{}
void operator () () const {
if(t_) (*t_) += by_;
}
private:
T* t_;
T by_;
};
/*************************************************************************//**
*
* @brief makes a value from a string and assigns it to an object
*
*****************************************************************************/
template<class T>
class map_arg_to
{
public:
explicit constexpr
map_arg_to(T& target) noexcept : t_{std::addressof(target)} {}
void operator () (const char* s) const {
if(t_ && s && (std::strlen(s) > 0))
*t_ = detail::make<T>::from(s);
}
private:
T* t_;
};
//-------------------------------------------------------------------
/**
* @brief specialization for vectors: append element
*/
template<class T>
class map_arg_to<std::vector<T>>
{
public:
map_arg_to(std::vector<T>& target): t_{std::addressof(target)} {}
void operator () (const char* s) const {
if(t_ && s) t_->push_back(detail::make<T>::from(s));
}
private:
std::vector<T>* t_;
};
//-------------------------------------------------------------------
/**
* @brief specialization for bools:
* set to true regardless of string content
*/
template<>
class map_arg_to<bool>
{
public:
map_arg_to(bool& target): t_{&target} {}
void operator () (const char* s) const {
if(t_ && s) *t_ = true;
}
private:
bool* t_;
};
} // namespace detail
/*************************************************************************//**
*
* @brief string matching and processing tools
*
*****************************************************************************/
namespace str {
/*************************************************************************//**
*
* @brief converts string to value of target type 'T'
*
*****************************************************************************/
template<class T>
T make(const arg_string& s)
{
return detail::make<T>::from(s);
}
/*************************************************************************//**
*
* @brief removes trailing whitespace from string
*
*****************************************************************************/
template<class C, class T, class A>
inline void
trimr(std::basic_string<C,T,A>& s)
{
if(s.empty()) return;
s.erase(
std::find_if_not(s.rbegin(), s.rend(),
[](char c) { return std::isspace(c);} ).base(),
s.end() );
}
/*************************************************************************//**
*
* @brief removes leading whitespace from string
*
*****************************************************************************/
template<class C, class T, class A>
inline void
triml(std::basic_string<C,T,A>& s)
{
if(s.empty()) return;
s.erase(
s.begin(),
std::find_if_not(s.begin(), s.end(),
[](char c) { return std::isspace(c);})
);
}
/*************************************************************************//**
*
* @brief removes leading and trailing whitespace from string
*
*****************************************************************************/
template<class C, class T, class A>
inline void
trim(std::basic_string<C,T,A>& s)
{
triml(s);
trimr(s);
}
/*************************************************************************//**
*
* @brief removes all whitespaces from string
*
*****************************************************************************/
template<class C, class T, class A>
inline void
remove_ws(std::basic_string<C,T,A>& s)
{
if(s.empty()) return;
s.erase(std::remove_if(s.begin(), s.end(),
[](char c) { return std::isspace(c); }),
s.end() );
}
/*************************************************************************//**
*
* @brief returns true, if the 'prefix' argument
* is a prefix of the 'subject' argument
*
*****************************************************************************/
template<class C, class T, class A>
inline bool
has_prefix(const std::basic_string<C,T,A>& subject,
const std::basic_string<C,T,A>& prefix)
{
if(prefix.size() > subject.size()) return false;
return subject.find(prefix) == 0;
}
/*************************************************************************//**
*
* @brief returns true, if the 'postfix' argument
* is a postfix of the 'subject' argument
*
*****************************************************************************/
template<class C, class T, class A>
inline bool
has_postfix(const std::basic_string<C,T,A>& subject,
const std::basic_string<C,T,A>& postfix)
{
if(postfix.size() > subject.size()) return false;
return (subject.size() - postfix.size()) == subject.find(postfix);
}
/*************************************************************************//**
*
* @brief returns longest common prefix of several
* sequential random access containers
*
* @details InputRange require begin and end (member functions or overloads)
* the elements of InputRange require a size() member
*
*****************************************************************************/
template<class InputRange>
auto
longest_common_prefix(const InputRange& strs)
-> typename std::decay<decltype(*begin(strs))>::type
{
static_assert(traits::is_input_range<InputRange>(),
"parameter must satisfy the InputRange concept");
static_assert(traits::has_size_getter<
typename std::decay<decltype(*begin(strs))>::type>(),
"elements of input range must have a ::size() member function");
using std::begin;
using std::end;
using item_t = typename std::decay<decltype(*begin(strs))>::type;
using str_size_t = typename std::decay<decltype(begin(strs)->size())>::type;
const auto n = size_t(distance(begin(strs), end(strs)));
if(n < 1) return item_t("");
if(n == 1) return *begin(strs);
//length of shortest string
auto m = std::min_element(begin(strs), end(strs),
[](const item_t& a, const item_t& b) {
return a.size() < b.size(); })->size();
//check each character until we find a mismatch
for(str_size_t i = 0; i < m; ++i) {
for(str_size_t j = 1; j < n; ++j) {
if(strs[j][i] != strs[j-1][i])
return strs[0].substr(0, i);
}
}
return strs[0].substr(0, m);
}
/*************************************************************************//**
*
* @brief returns longest substring range that could be found in 'arg'
*
* @param arg string to be searched in
* @param substrings range of candidate substrings
*
*****************************************************************************/
template<class C, class T, class A, class InputRange>
subrange
longest_substring_match(const std::basic_string<C,T,A>& arg,
const InputRange& substrings)
{
using string_t = std::basic_string<C,T,A>;
static_assert(traits::is_input_range<InputRange>(),
"parameter must satisfy the InputRange concept");
static_assert(std::is_same<string_t,
typename std::decay<decltype(*begin(substrings))>::type>(),
"substrings must have same type as 'arg'");
auto i = string_t::npos;
auto n = string_t::size_type(0);
for(const auto& s : substrings) {
auto j = arg.find(s);
if(j != string_t::npos && s.size() > n) {
i = j;
n = s.size();
}
}
return subrange{i,n};
}
/*************************************************************************//**
*
* @brief returns longest prefix range that could be found in 'arg'
*
* @param arg string to be searched in
* @param prefixes range of candidate prefix strings
*
*****************************************************************************/
template<class C, class T, class A, class InputRange>
subrange
longest_prefix_match(const std::basic_string<C,T,A>& arg,
const InputRange& prefixes)
{
using string_t = std::basic_string<C,T,A>;
using s_size_t = typename string_t::size_type;
static_assert(traits::is_input_range<InputRange>(),
"parameter must satisfy the InputRange concept");
static_assert(std::is_same<string_t,
typename std::decay<decltype(*begin(prefixes))>::type>(),
"prefixes must have same type as 'arg'");
auto i = string_t::npos;
auto n = s_size_t(0);
for(const auto& s : prefixes) {
auto j = arg.find(s);
if(j == 0 && s.size() > n) {
i = 0;
n = s.size();
}
}
return subrange{i,n};
}
/*************************************************************************//**
*
* @brief returns the first occurrence of 'query' within 'subject'
*
*****************************************************************************/
template<class C, class T, class A>
inline subrange
substring_match(const std::basic_string<C,T,A>& subject,
const std::basic_string<C,T,A>& query)
{
if(subject.empty() || query.empty()) return subrange{};
auto i = subject.find(query);
if(i == std::basic_string<C,T,A>::npos) return subrange{};
return subrange{i,query.size()};
}
/*************************************************************************//**
*
* @brief returns first substring match (pos,len) within the input string
* that represents a number
* (with at maximum one decimal point and digit separators)
*
*****************************************************************************/
template<class C, class T, class A>
subrange
first_number_match(std::basic_string<C,T,A> s,
C digitSeparator = C(','),
C decimalPoint = C('.'),
C exponential = C('e'))
{
using string_t = std::basic_string<C,T,A>;
str::trim(s);
if(s.empty()) return subrange{};
auto i = s.find_first_of("0123456789+-");
if(i == string_t::npos) {
i = s.find(decimalPoint);
if(i == string_t::npos) return subrange{};
}
bool point = false;
bool sep = false;
auto exp = string_t::npos;
auto j = i + 1;
for(; j < s.size(); ++j) {
if(s[j] == digitSeparator) {
if(!sep) sep = true; else break;
}
else {
sep = false;
if(s[j] == decimalPoint) {
//only one decimal point before exponent allowed
if(!point && exp == string_t::npos) point = true; else break;
}
else if(std::tolower(s[j]) == std::tolower(exponential)) {
//only one exponent separator allowed
if(exp == string_t::npos) exp = j; else break;
}
else if(exp != string_t::npos && (exp+1) == j) {
//only sign or digit after exponent separator
if(s[j] != '+' && s[j] != '-' && !std::isdigit(s[j])) break;
}
else if(!std::isdigit(s[j])) {
break;
}
}
}
//if length == 1 then must be a digit
if(j-i == 1 && !std::isdigit(s[i])) return subrange{};
return subrange{i,j-i};
}
/*************************************************************************//**
*
* @brief returns first substring match (pos,len)
* that represents an integer (with optional digit separators)
*
*****************************************************************************/
template<class C, class T, class A>
subrange
first_integer_match(std::basic_string<C,T,A> s,
C digitSeparator = C(','))
{
using string_t = std::basic_string<C,T,A>;
str::trim(s);
if(s.empty()) return subrange{};
auto i = s.find_first_of("0123456789+-");
if(i == string_t::npos) return subrange{};
bool sep = false;
auto j = i + 1;
for(; j < s.size(); ++j) {
if(s[j] == digitSeparator) {
if(!sep) sep = true; else break;
}
else {
sep = false;
if(!std::isdigit(s[j])) break;
}
}
//if length == 1 then must be a digit
if(j-i == 1 && !std::isdigit(s[i])) return subrange{};
return subrange{i,j-i};
}
/*************************************************************************//**
*
* @brief returns true if candidate string represents a number
*
*****************************************************************************/
template<class C, class T, class A>
bool represents_number(const std::basic_string<C,T,A>& candidate,
C digitSeparator = C(','),
C decimalPoint = C('.'),
C exponential = C('e'))
{
const auto match = str::first_number_match(candidate, digitSeparator,
decimalPoint, exponential);
return (match && match.length() == candidate.size());
}
/*************************************************************************//**
*
* @brief returns true if candidate string represents an integer
*
*****************************************************************************/
template<class C, class T, class A>
bool represents_integer(const std::basic_string<C,T,A>& candidate,
C digitSeparator = C(','))
{
const auto match = str::first_integer_match(candidate, digitSeparator);
return (match && match.length() == candidate.size());
}
} // namespace str
/*************************************************************************//**
*
* @brief makes function object with a const char* parameter
* that assigns a value to a ref-captured object
*
*****************************************************************************/
template<class T, class V>
inline detail::assign_value<T,V>
set(T& target, V value) {
return detail::assign_value<T>{target, std::move(value)};
}
/*************************************************************************//**
*
* @brief makes parameter-less function object
* that assigns value(s) to a ref-captured object;
* value(s) are obtained by converting the const char* argument to
* the captured object types;
* bools are always set to true if the argument is not nullptr
*
*****************************************************************************/
template<class T>
inline detail::map_arg_to<T>
set(T& target) {
return detail::map_arg_to<T>{target};
}
/*************************************************************************//**
*
* @brief makes function object that sets a bool to true
*
*****************************************************************************/
inline detail::assign_value<bool>
set(bool& target) {
return detail::assign_value<bool>{target,true};
}
/*************************************************************************//**
*
* @brief makes function object that sets a bool to false
*
*****************************************************************************/
inline detail::assign_value<bool>
unset(bool& target) {
return detail::assign_value<bool>{target,false};
}
/*************************************************************************//**
*
* @brief makes function object that flips the value of a ref-captured bool
*
*****************************************************************************/
inline detail::flip_bool
flip(bool& b) {
return detail::flip_bool(b);
}
/*************************************************************************//**
*
* @brief makes function object that increments using operator ++
*
*****************************************************************************/
template<class T>
inline detail::increment<T>
increment(T& target) {
return detail::increment<T>{target};
}
/*************************************************************************//**
*
* @brief makes function object that decrements using operator --
*
*****************************************************************************/
template<class T>
inline detail::increment_by<T>
increment(T& target, T by) {
return detail::increment_by<T>{target, std::move(by)};
}
/*************************************************************************//**
*
* @brief makes function object that increments by a fixed amount using operator +=
*
*****************************************************************************/
template<class T>
inline detail::decrement<T>
decrement(T& target) {
return detail::decrement<T>{target};
}
/*************************************************************************//**
*
* @brief helpers (NOT FOR DIRECT USE IN CLIENT CODE!)
*
*****************************************************************************/
namespace detail {
/*************************************************************************//**
*
* @brief mixin that provides action definition and execution
*
*****************************************************************************/
template<class Derived>
class action_provider
{
private:
//---------------------------------------------------------------
using simple_action = std::function<void()>;
using arg_action = std::function<void(const char*)>;
using index_action = std::function<void(int)>;
//-----------------------------------------------------
class simple_action_adapter {
public:
simple_action_adapter() = default;
simple_action_adapter(const simple_action& a): action_(a) {}
simple_action_adapter(simple_action&& a): action_(std::move(a)) {}
void operator() (const char*) const { action_(); }
void operator() (int) const { action_(); }
private:
simple_action action_;
};
public:
//---------------------------------------------------------------
/** @brief adds an action that has an operator() that is callable
* with a 'const char*' argument */
Derived&
call(arg_action a) {
argActions_.push_back(std::move(a));
return *static_cast<Derived*>(this);
}
/** @brief adds an action that has an operator()() */
Derived&
call(simple_action a) {
argActions_.push_back(simple_action_adapter(std::move(a)));
return *static_cast<Derived*>(this);
}
/** @brief adds an action that has an operator() that is callable
* with a 'const char*' argument */
Derived& operator () (arg_action a) { return call(std::move(a)); }
/** @brief adds an action that has an operator()() */
Derived& operator () (simple_action a) { return call(std::move(a)); }
//---------------------------------------------------------------
/** @brief adds an action that will set the value of 't' from
* a 'const char*' arg */
template<class Target>
Derived&
set(Target& t) {
static_assert(!std::is_pointer<Target>::value,
"parameter target type must not be a pointer");
return call(clipp::set(t));
}
/** @brief adds an action that will set the value of 't' to 'v' */
template<class Target, class Value>
Derived&
set(Target& t, Value&& v) {
return call(clipp::set(t, std::forward<Value>(v)));
}
//---------------------------------------------------------------
/** @brief adds an action that will be called if a parameter
* matches an argument for the 2nd, 3rd, 4th, ... time
*/
Derived&
if_repeated(simple_action a) {
repeatActions_.push_back(simple_action_adapter{std::move(a)});
return *static_cast<Derived*>(this);
}
/** @brief adds an action that will be called with the argument's
* index if a parameter matches an argument for
* the 2nd, 3rd, 4th, ... time
*/
Derived&
if_repeated(index_action a) {
repeatActions_.push_back(std::move(a));
return *static_cast<Derived*>(this);
}
//---------------------------------------------------------------
/** @brief adds an action that will be called if a required parameter
* is missing
*/
Derived&
if_missing(simple_action a) {
missingActions_.push_back(simple_action_adapter{std::move(a)});
return *static_cast<Derived*>(this);
}
/** @brief adds an action that will be called if a required parameter
* is missing; the action will get called with the index of
* the command line argument where the missing event occured first
*/
Derived&
if_missing(index_action a) {
missingActions_.push_back(std::move(a));
return *static_cast<Derived*>(this);
}
//---------------------------------------------------------------
/** @brief adds an action that will be called if a parameter
* was matched, but was unreachable in the current scope
*/
Derived&
if_blocked(simple_action a) {
blockedActions_.push_back(simple_action_adapter{std::move(a)});
return *static_cast<Derived*>(this);
}
/** @brief adds an action that will be called if a parameter
* was matched, but was unreachable in the current scope;
* the action will be called with the index of
* the command line argument where the problem occured
*/
Derived&
if_blocked(index_action a) {
blockedActions_.push_back(std::move(a));
return *static_cast<Derived*>(this);
}
//---------------------------------------------------------------
/** @brief adds an action that will be called if a parameter match
* was in conflict with a different alternative parameter
*/
Derived&
if_conflicted(simple_action a) {
conflictActions_.push_back(simple_action_adapter{std::move(a)});
return *static_cast<Derived*>(this);
}
/** @brief adds an action that will be called if a parameter match
* was in conflict with a different alternative paramete;
* the action will be called with the index of
* the command line argument where the problem occuredr
*/
Derived&
if_conflicted(index_action a) {
conflictActions_.push_back(std::move(a));
return *static_cast<Derived*>(this);
}
//---------------------------------------------------------------
/** @brief adds targets = either objects whose values should be
* set by command line arguments or actions that should
* be called in case of a match */
template<class T, class... Ts>
Derived&
target(T&& t, Ts&&... ts) {
target(std::forward<T>(t));
target(std::forward<Ts>(ts)...);
return *static_cast<Derived*>(this);
}
/** @brief adds action that should be called in case of a match */
template<class T, class = typename std::enable_if<
!std::is_fundamental<typename std::decay<T>::type>() &&
(traits::is_callable<T,void()>() ||
traits::is_callable<T,void(const char*)>() )
>::type>
Derived&
target(T&& t) {
call(std::forward<T>(t));
return *static_cast<Derived*>(this);
}
/** @brief adds object whose value should be set by command line arguments
*/
template<class T, class = typename std::enable_if<
std::is_fundamental<typename std::decay<T>::type>() ||
(!traits::is_callable<T,void()>() &&
!traits::is_callable<T,void(const char*)>() )
>::type>
Derived&
target(T& t) {
static_assert(!std::is_pointer<T>::value,
"parameter target type must not be a pointer");
set(t);
return *static_cast<Derived*>(this);
}
//TODO remove ugly empty param list overload
Derived&
target() {
return *static_cast<Derived*>(this);
}
//---------------------------------------------------------------
/** @brief adds target, see member function 'target' */
template<class Target>
inline friend Derived&
operator << (Target&& t, Derived& p) {
p.target(std::forward<Target>(t));
return p;
}
/** @brief adds target, see member function 'target' */
template<class Target>
inline friend Derived&&
operator << (Target&& t, Derived&& p) {
p.target(std::forward<Target>(t));
return std::move(p);
}
//-----------------------------------------------------
/** @brief adds target, see member function 'target' */
template<class Target>
inline friend Derived&
operator >> (Derived& p, Target&& t) {
p.target(std::forward<Target>(t));
return p;
}
/** @brief adds target, see member function 'target' */
template<class Target>
inline friend Derived&&
operator >> (Derived&& p, Target&& t) {
p.target(std::forward<Target>(t));
return std::move(p);
}
//---------------------------------------------------------------
/** @brief executes all argument actions */
void execute_actions(const arg_string& arg) const {
int i = 0;
for(const auto& a : argActions_) {
++i;
a(arg.c_str());
}
}
/** @brief executes repeat actions */
void notify_repeated(arg_index idx) const {
for(const auto& a : repeatActions_) a(idx);
}
/** @brief executes missing error actions */
void notify_missing(arg_index idx) const {
for(const auto& a : missingActions_) a(idx);
}
/** @brief executes blocked error actions */
void notify_blocked(arg_index idx) const {
for(const auto& a : blockedActions_) a(idx);
}
/** @brief executes conflict error actions */
void notify_conflict(arg_index idx) const {
for(const auto& a : conflictActions_) a(idx);
}
private:
//---------------------------------------------------------------
std::vector<arg_action> argActions_;
std::vector<index_action> repeatActions_;
std::vector<index_action> missingActions_;
std::vector<index_action> blockedActions_;
std::vector<index_action> conflictActions_;
};
/*************************************************************************//**
*
* @brief mixin that provides basic common settings of parameters and groups
*
*****************************************************************************/
template<class Derived>
class token
{
public:
//---------------------------------------------------------------
using doc_string = clipp::doc_string;
//---------------------------------------------------------------
/** @brief returns documentation string */
const doc_string& doc() const noexcept {
return doc_;
}
/** @brief sets documentations string */
Derived& doc(const doc_string& txt) {
doc_ = txt;
return *static_cast<Derived*>(this);
}
/** @brief sets documentations string */
Derived& doc(doc_string&& txt) {
doc_ = std::move(txt);
return *static_cast<Derived*>(this);
}
//---------------------------------------------------------------
/** @brief returns if a group/parameter is repeatable */
bool repeatable() const noexcept {
return repeatable_;
}
/** @brief sets repeatability of group/parameter */
Derived& repeatable(bool yes) noexcept {
repeatable_ = yes;
return *static_cast<Derived*>(this);
}
//---------------------------------------------------------------
/** @brief returns if a group/parameter is blocking/positional */
bool blocking() const noexcept {
return blocking_;
}
/** @brief determines, if a group/parameter is blocking/positional */
Derived& blocking(bool yes) noexcept {
blocking_ = yes;
return *static_cast<Derived*>(this);
}
private:
//---------------------------------------------------------------
doc_string doc_;
bool repeatable_ = false;
bool blocking_ = false;
};
/*************************************************************************//**
*
* @brief sets documentation strings on a token
*
*****************************************************************************/
template<class T>
inline T&
operator % (doc_string docstr, token<T>& p)
{
return p.doc(std::move(docstr));
}
//---------------------------------------------------------
template<class T>
inline T&&
operator % (doc_string docstr, token<T>&& p)
{
return std::move(p.doc(std::move(docstr)));
}
//---------------------------------------------------------
template<class T>
inline T&
operator % (token<T>& p, doc_string docstr)
{
return p.doc(std::move(docstr));
}
//---------------------------------------------------------
template<class T>
inline T&&
operator % (token<T>&& p, doc_string docstr)
{
return std::move(p.doc(std::move(docstr)));
}
/*************************************************************************//**
*
* @brief sets documentation strings on a token
*
*****************************************************************************/
template<class T>
inline T&
doc(doc_string docstr, token<T>& p)
{
return p.doc(std::move(docstr));
}
//---------------------------------------------------------
template<class T>
inline T&&
doc(doc_string docstr, token<T>&& p)
{
return std::move(p.doc(std::move(docstr)));
}
} // namespace detail
/*************************************************************************//**
*
* @brief contains parameter matching functions and function classes
*
*****************************************************************************/
namespace match {
/*************************************************************************//**
*
* @brief predicate that is always true
*
*****************************************************************************/
inline bool
any(const arg_string&) { return true; }
/*************************************************************************//**
*
* @brief predicate that is always false
*
*****************************************************************************/
inline bool
none(const arg_string&) { return false; }
/*************************************************************************//**
*
* @brief predicate that returns true if the argument string is non-empty string
*
*****************************************************************************/
inline bool
nonempty(const arg_string& s) {
return !s.empty();
}
/*************************************************************************//**
*
* @brief predicate that returns true if the argument is a non-empty
* string that consists only of alphanumeric characters
*
*****************************************************************************/
inline bool
alphanumeric(const arg_string& s) {
if(s.empty()) return false;
return std::all_of(s.begin(), s.end(), [](char c) {return std::isalnum(c); });
}
/*************************************************************************//**
*
* @brief predicate that returns true if the argument is a non-empty
* string that consists only of alphabetic characters
*
*****************************************************************************/
inline bool
alphabetic(const arg_string& s) {
return std::all_of(s.begin(), s.end(), [](char c) {return std::isalpha(c); });
}
/*************************************************************************//**
*
* @brief predicate that returns false if the argument string is
* equal to any string from the exclusion list
*
*****************************************************************************/
class none_of
{
public:
none_of(arg_list strs):
excluded_{std::move(strs)}
{}
template<class... Strings>
none_of(arg_string str, Strings&&... strs):
excluded_{std::move(str), std::forward<Strings>(strs)...}
{}
template<class... Strings>
none_of(const char* str, Strings&&... strs):
excluded_{arg_string(str), std::forward<Strings>(strs)...}
{}
bool operator () (const arg_string& arg) const {
return (std::find(begin(excluded_), end(excluded_), arg)
== end(excluded_));
}
private:
arg_list excluded_;
};
/*************************************************************************//**
*
* @brief predicate that returns the first substring match within the input
* string that rmeepresents a number
* (with at maximum one decimal point and digit separators)
*
*****************************************************************************/
class numbers
{
public:
explicit
numbers(char decimalPoint = '.',
char digitSeparator = ' ',
char exponentSeparator = 'e')
:
decpoint_{decimalPoint}, separator_{digitSeparator},
exp_{exponentSeparator}
{}
subrange operator () (const arg_string& s) const {
return str::first_number_match(s, separator_, decpoint_, exp_);
}
private:
char decpoint_;
char separator_;
char exp_;
};
/*************************************************************************//**
*
* @brief predicate that returns true if the input string represents an integer
* (with optional digit separators)
*
*****************************************************************************/
class integers {
public:
explicit
integers(char digitSeparator = ' '): separator_{digitSeparator} {}
subrange operator () (const arg_string& s) const {
return str::first_integer_match(s, separator_);
}
private:
char separator_;
};
/*************************************************************************//**
*
* @brief predicate that returns true if the input string represents
* a non-negative integer (with optional digit separators)
*
*****************************************************************************/
class positive_integers {
public:
explicit
positive_integers(char digitSeparator = ' '): separator_{digitSeparator} {}
subrange operator () (const arg_string& s) const {
auto match = str::first_integer_match(s, separator_);
if(!match) return subrange{};
if(s[match.at()] == '-') return subrange{};
return match;
}
private:
char separator_;
};
/*************************************************************************//**
*
* @brief predicate that returns true if the input string
* contains a given substring
*
*****************************************************************************/
class substring
{
public:
explicit
substring(arg_string str): str_{std::move(str)} {}
subrange operator () (const arg_string& s) const {
return str::substring_match(s, str_);
}
private:
arg_string str_;
};
/*************************************************************************//**
*
* @brief predicate that returns true if the input string starts
* with a given prefix
*
*****************************************************************************/
class prefix {
public:
explicit
prefix(arg_string p): prefix_{std::move(p)} {}
bool operator () (const arg_string& s) const {
return s.find(prefix_) == 0;
}
private:
arg_string prefix_;
};
/*************************************************************************//**
*
* @brief predicate that returns true if the input string does not start
* with a given prefix
*
*****************************************************************************/
class prefix_not {
public:
explicit
prefix_not(arg_string p): prefix_{std::move(p)} {}
bool operator () (const arg_string& s) const {
return s.find(prefix_) != 0;
}
private:
arg_string prefix_;
};
/** @brief alias for prefix_not */
using noprefix = prefix_not;
/*************************************************************************//**
*
* @brief predicate that returns true if the length of the input string
* is wihtin a given interval
*
*****************************************************************************/
class length {
public:
explicit
length(std::size_t exact):
min_{exact}, max_{exact}
{}
explicit
length(std::size_t min, std::size_t max):
min_{min}, max_{max}
{}
bool operator () (const arg_string& s) const {
return s.size() >= min_ && s.size() <= max_;
}
private:
std::size_t min_;
std::size_t max_;
};
/*************************************************************************//**
*
* @brief makes function object that returns true if the input string has a
* given minimum length
*
*****************************************************************************/
inline length min_length(std::size_t min)
{
return length{min, arg_string::npos-1};
}
/*************************************************************************//**
*
* @brief makes function object that returns true if the input string is
* not longer than a given maximum length
*
*****************************************************************************/
inline length max_length(std::size_t max)
{
return length{0, max};
}
} // namespace match
/*************************************************************************//**
*
* @brief command line parameter that can match one or many arguments.
*
*****************************************************************************/
class parameter :
public detail::token<parameter>,
public detail::action_provider<parameter>
{
/** @brief adapts a 'match_predicate' to the 'match_function' interface */
class predicate_adapter {
public:
explicit
predicate_adapter(match_predicate pred): match_{std::move(pred)} {}
subrange operator () (const arg_string& arg) const {
return match_(arg) ? subrange{0,arg.size()} : subrange{};
}
private:
match_predicate match_;
};
public:
//---------------------------------------------------------------
/** @brief makes default parameter, that will match nothing */
parameter():
flags_{},
matcher_{predicate_adapter{match::none}},
label_{}, required_{false}, greedy_{false}
{}
/** @brief makes "flag" parameter */
template<class... Strings>
explicit
parameter(arg_string str, Strings&&... strs):
flags_{},
matcher_{predicate_adapter{match::none}},
label_{}, required_{false}, greedy_{false}
{
add_flags(std::move(str), std::forward<Strings>(strs)...);
}
/** @brief makes "flag" parameter from range of strings */
explicit
parameter(const arg_list& flaglist):
flags_{},
matcher_{predicate_adapter{match::none}},
label_{}, required_{false}, greedy_{false}
{
add_flags(flaglist);
}
//-----------------------------------------------------
/** @brief makes "value" parameter with custom match predicate
* (= yes/no matcher)
*/
explicit
parameter(match_predicate filter):
flags_{},
matcher_{predicate_adapter{std::move(filter)}},
label_{}, required_{false}, greedy_{false}
{}
/** @brief makes "value" parameter with custom match function
* (= partial matcher)
*/
explicit
parameter(match_function filter):
flags_{},
matcher_{std::move(filter)},
label_{}, required_{false}, greedy_{false}
{}
//---------------------------------------------------------------
/** @brief returns if a parameter is required */
bool
required() const noexcept {
return required_;
}
/** @brief determines if a parameter is required */
parameter&
required(bool yes) noexcept {
required_ = yes;
return *this;
}
//---------------------------------------------------------------
/** @brief returns if a parameter should match greedily */
bool
greedy() const noexcept {
return greedy_;
}
/** @brief determines if a parameter should match greedily */
parameter&
greedy(bool yes) noexcept {
greedy_ = yes;
return *this;
}
//---------------------------------------------------------------
/** @brief returns parameter label;
* will be used for documentation, if flags are empty
*/
const doc_string&
label() const {
return label_;
}
/** @brief sets parameter label;
* will be used for documentation, if flags are empty
*/
parameter&
label(const doc_string& lbl) {
label_ = lbl;
return *this;
}
/** @brief sets parameter label;
* will be used for documentation, if flags are empty
*/
parameter&
label(doc_string&& lbl) {
label_ = lbl;
return *this;
}
//---------------------------------------------------------------
/** @brief returns either longest matching prefix of 'arg' in any
* of the flags or the result of the custom match operation
*/
subrange
match(const arg_string& arg) const
{
if(arg.empty()) return subrange{};
if(flags_.empty()) {
return matcher_(arg);
}
else {
if(std::find(flags_.begin(), flags_.end(), arg) != flags_.end()) {
return subrange{0,arg.size()};
}
return str::longest_prefix_match(arg, flags_);
}
}
//---------------------------------------------------------------
/** @brief access range of flag strings */
const arg_list&
flags() const noexcept {
return flags_;
}
/** @brief access custom match operation */
const match_function&
matcher() const noexcept {
return matcher_;
}
//---------------------------------------------------------------
/** @brief prepend prefix to each flag */
inline friend parameter&
with_prefix(const arg_string& prefix, parameter& p)
{
if(prefix.empty() || p.flags().empty()) return p;
for(auto& f : p.flags_) {
if(f.find(prefix) != 0) f.insert(0, prefix);
}
return p;
}
/** @brief prepend prefix to each flag
*/
inline friend parameter&
with_prefixes_short_long(
const arg_string& shortpfx, const arg_string& longpfx,
parameter& p)
{
if(shortpfx.empty() && longpfx.empty()) return p;
if(p.flags().empty()) return p;
for(auto& f : p.flags_) {
if(f.size() == 1) {
if(f.find(shortpfx) != 0) f.insert(0, shortpfx);
} else {
if(f.find(longpfx) != 0) f.insert(0, longpfx);
}
}
return p;
}
private:
//---------------------------------------------------------------
void add_flags(arg_string str) {
//empty flags are not allowed
str::remove_ws(str);
if(!str.empty()) flags_.push_back(std::move(str));
}
//---------------------------------------------------------------
void add_flags(const arg_list& strs) {
if(strs.empty()) return;
flags_.reserve(flags_.size() + strs.size());
for(const auto& s : strs) add_flags(s);
}
template<class String1, class String2, class... Strings>
void
add_flags(String1&& s1, String2&& s2, Strings&&... ss) {
flags_.reserve(2 + sizeof...(ss));
add_flags(std::forward<String1>(s1));
add_flags(std::forward<String2>(s2), std::forward<Strings>(ss)...);
}
arg_list flags_;
match_function matcher_;
doc_string label_;
bool required_ = false;
bool greedy_ = false;
};
/*************************************************************************//**
*
* @brief makes required non-blocking exact match parameter
*
*****************************************************************************/
template<class String, class... Strings>
inline parameter
command(String&& flag, Strings&&... flags)
{
return parameter{std::forward<String>(flag), std::forward<Strings>(flags)...}
.required(true).blocking(true).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes required non-blocking exact match parameter
*
*****************************************************************************/
template<class String, class... Strings>
inline parameter
required(String&& flag, Strings&&... flags)
{
return parameter{std::forward<String>(flag), std::forward<Strings>(flags)...}
.required(true).blocking(false).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes optional, non-blocking exact match parameter
*
*****************************************************************************/
template<class String, class... Strings>
inline parameter
option(String&& flag, Strings&&... flags)
{
return parameter{std::forward<String>(flag), std::forward<Strings>(flags)...}
.required(false).blocking(false).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes required, blocking, repeatable value parameter;
* matches any non-empty string
*
*****************************************************************************/
template<class... Targets>
inline parameter
value(const doc_string& label, Targets&&... tgts)
{
return parameter{match::nonempty}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(false);
}
template<class Filter, class... Targets, class = typename std::enable_if<
traits::is_callable<Filter,bool(const char*)>::value ||
traits::is_callable<Filter,subrange(const char*)>::value>::type>
inline parameter
value(Filter&& filter, doc_string label, Targets&&... tgts)
{
return parameter{std::forward<Filter>(filter)}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes required, blocking, repeatable value parameter;
* matches any non-empty string
*
*****************************************************************************/
template<class... Targets>
inline parameter
values(const doc_string& label, Targets&&... tgts)
{
return parameter{match::nonempty}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(true);
}
template<class Filter, class... Targets, class = typename std::enable_if<
traits::is_callable<Filter,bool(const char*)>::value ||
traits::is_callable<Filter,subrange(const char*)>::value>::type>
inline parameter
values(Filter&& filter, doc_string label, Targets&&... tgts)
{
return parameter{std::forward<Filter>(filter)}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(true);
}
/*************************************************************************//**
*
* @brief makes optional, blocking value parameter;
* matches any non-empty string
*
*****************************************************************************/
template<class... Targets>
inline parameter
opt_value(const doc_string& label, Targets&&... tgts)
{
return parameter{match::nonempty}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(false);
}
template<class Filter, class... Targets, class = typename std::enable_if<
traits::is_callable<Filter,bool(const char*)>::value ||
traits::is_callable<Filter,subrange(const char*)>::value>::type>
inline parameter
opt_value(Filter&& filter, doc_string label, Targets&&... tgts)
{
return parameter{std::forward<Filter>(filter)}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes optional, blocking, repeatable value parameter;
* matches any non-empty string
*
*****************************************************************************/
template<class... Targets>
inline parameter
opt_values(const doc_string& label, Targets&&... tgts)
{
return parameter{match::nonempty}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(true);
}
template<class Filter, class... Targets, class = typename std::enable_if<
traits::is_callable<Filter,bool(const char*)>::value ||
traits::is_callable<Filter,subrange(const char*)>::value>::type>
inline parameter
opt_values(Filter&& filter, doc_string label, Targets&&... tgts)
{
return parameter{std::forward<Filter>(filter)}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(true);
}
/*************************************************************************//**
*
* @brief makes required, blocking value parameter;
* matches any string consisting of alphanumeric characters
*
*****************************************************************************/
template<class... Targets>
inline parameter
word(const doc_string& label, Targets&&... tgts)
{
return parameter{match::alphanumeric}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes required, blocking, repeatable value parameter;
* matches any string consisting of alphanumeric characters
*
*****************************************************************************/
template<class... Targets>
inline parameter
words(const doc_string& label, Targets&&... tgts)
{
return parameter{match::alphanumeric}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(true);
}
/*************************************************************************//**
*
* @brief makes optional, blocking value parameter;
* matches any string consisting of alphanumeric characters
*
*****************************************************************************/
template<class... Targets>
inline parameter
opt_word(const doc_string& label, Targets&&... tgts)
{
return parameter{match::alphanumeric}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes optional, blocking, repeatable value parameter;
* matches any string consisting of alphanumeric characters
*
*****************************************************************************/
template<class... Targets>
inline parameter
opt_words(const doc_string& label, Targets&&... tgts)
{
return parameter{match::alphanumeric}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(true);
}
/*************************************************************************//**
*
* @brief makes required, blocking value parameter;
* matches any string that represents a number
*
*****************************************************************************/
template<class... Targets>
inline parameter
number(const doc_string& label, Targets&&... tgts)
{
return parameter{match::numbers{}}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes required, blocking, repeatable value parameter;
* matches any string that represents a number
*
*****************************************************************************/
template<class... Targets>
inline parameter
numbers(const doc_string& label, Targets&&... tgts)
{
return parameter{match::numbers{}}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(true);
}
/*************************************************************************//**
*
* @brief makes optional, blocking value parameter;
* matches any string that represents a number
*
*****************************************************************************/
template<class... Targets>
inline parameter
opt_number(const doc_string& label, Targets&&... tgts)
{
return parameter{match::numbers{}}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes optional, blocking, repeatable value parameter;
* matches any string that represents a number
*
*****************************************************************************/
template<class... Targets>
inline parameter
opt_numbers(const doc_string& label, Targets&&... tgts)
{
return parameter{match::numbers{}}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(true);
}
/*************************************************************************//**
*
* @brief makes required, blocking value parameter;
* matches any string that represents an integer
*
*****************************************************************************/
template<class... Targets>
inline parameter
integer(const doc_string& label, Targets&&... tgts)
{
return parameter{match::integers{}}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes required, blocking, repeatable value parameter;
* matches any string that represents an integer
*
*****************************************************************************/
template<class... Targets>
inline parameter
integers(const doc_string& label, Targets&&... tgts)
{
return parameter{match::integers{}}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(true).blocking(true).repeatable(true);
}
/*************************************************************************//**
*
* @brief makes optional, blocking value parameter;
* matches any string that represents an integer
*
*****************************************************************************/
template<class... Targets>
inline parameter
opt_integer(const doc_string& label, Targets&&... tgts)
{
return parameter{match::integers{}}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(false);
}
/*************************************************************************//**
*
* @brief makes optional, blocking, repeatable value parameter;
* matches any string that represents an integer
*
*****************************************************************************/
template<class... Targets>
inline parameter
opt_integers(const doc_string& label, Targets&&... tgts)
{
return parameter{match::integers{}}
.label(label)
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(true);
}
/*************************************************************************//**
*
* @brief makes catch-all value parameter
*
*****************************************************************************/
template<class... Targets>
inline parameter
any_other(Targets&&... tgts)
{
return parameter{match::any}
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(true);
}
/*************************************************************************//**
*
* @brief makes catch-all value parameter with custom filter
*
*****************************************************************************/
template<class Filter, class... Targets, class = typename std::enable_if<
traits::is_callable<Filter,bool(const char*)>::value ||
traits::is_callable<Filter,subrange(const char*)>::value>::type>
inline parameter
any(Filter&& filter, Targets&&... tgts)
{
return parameter{std::forward<Filter>(filter)}
.target(std::forward<Targets>(tgts)...)
.required(false).blocking(false).repeatable(true);
}
/*************************************************************************//**
*
* @brief group of parameters and/or other groups;
* can be configured to act as a group of alternatives (exclusive match)
*
*****************************************************************************/
class group :
public detail::token<group>
{
//---------------------------------------------------------------
/**
* @brief tagged union type that either stores a parameter or a group
* and provides a common interface to them
* could be replaced by std::variant in the future
*
* Note to future self: do NOT try again to do this with
* dynamic polymorphism; there are a couple of
* nasty problems associated with it and the implementation
* becomes bloated and needlessly complicated.
*/
template<class Param, class Group>
struct child_t {
enum class type : char {param, group};
public:
explicit
child_t(const Param& v) : m_{v}, type_{type::param} {}
child_t( Param&& v) noexcept : m_{std::move(v)}, type_{type::param} {}
explicit
child_t(const Group& g) : m_{g}, type_{type::group} {}
child_t( Group&& g) noexcept : m_{std::move(g)}, type_{type::group} {}
child_t(const child_t& src): type_{src.type_} {
switch(type_) {
default:
case type::param: new(&m_)data{src.m_.param}; break;
case type::group: new(&m_)data{src.m_.group}; break;
}
}
child_t(child_t&& src) noexcept : type_{src.type_} {
switch(type_) {
default:
case type::param: new(&m_)data{std::move(src.m_.param)}; break;
case type::group: new(&m_)data{std::move(src.m_.group)}; break;
}
}
child_t& operator = (const child_t& src) {
destroy_content();
type_ = src.type_;
switch(type_) {
default:
case type::param: new(&m_)data{src.m_.param}; break;
case type::group: new(&m_)data{src.m_.group}; break;
}
return *this;
}
child_t& operator = (child_t&& src) noexcept {
destroy_content();
type_ = src.type_;
switch(type_) {
default:
case type::param: new(&m_)data{std::move(src.m_.param)}; break;
case type::group: new(&m_)data{std::move(src.m_.group)}; break;
}
return *this;
}
~child_t() {
destroy_content();
}
const doc_string&
doc() const noexcept {
switch(type_) {
default:
case type::param: return m_.param.doc();
case type::group: return m_.group.doc();
}
}
bool blocking() const noexcept {
switch(type_) {
case type::param: return m_.param.blocking();
case type::group: return m_.group.blocking();
default: return false;
}
}
bool repeatable() const noexcept {
switch(type_) {
case type::param: return m_.param.repeatable();
case type::group: return m_.group.repeatable();
default: return false;
}
}
bool required() const noexcept {
switch(type_) {
case type::param: return m_.param.required();
case type::group:
return (m_.group.exclusive() && m_.group.all_required() ) ||
(!m_.group.exclusive() && m_.group.any_required() );
default: return false;
}
}
bool exclusive() const noexcept {
switch(type_) {
case type::group: return m_.group.exclusive();
case type::param:
default: return false;
}
}
std::size_t param_count() const noexcept {
switch(type_) {
case type::group: return m_.group.param_count();
case type::param:
default: return std::size_t(1);
}
}
std::size_t depth() const noexcept {
switch(type_) {
case type::group: return m_.group.depth();
case type::param:
default: return std::size_t(0);
}
}
void execute_actions(const arg_string& arg) const {
switch(type_) {
default:
case type::group: return;
case type::param: m_.param.execute_actions(arg); break;
}
}
void notify_repeated(arg_index idx) const {
switch(type_) {
default:
case type::group: return;
case type::param: m_.param.notify_repeated(idx); break;
}
}
void notify_missing(arg_index idx) const {
switch(type_) {
default:
case type::group: return;
case type::param: m_.param.notify_missing(idx); break;
}
}
void notify_blocked(arg_index idx) const {
switch(type_) {
default:
case type::group: return;
case type::param: m_.param.notify_blocked(idx); break;
}
}
void notify_conflict(arg_index idx) const {
switch(type_) {
default:
case type::group: return;
case type::param: m_.param.notify_conflict(idx); break;
}
}
bool is_param() const noexcept { return type_ == type::param; }
bool is_group() const noexcept { return type_ == type::group; }
Param& as_param() noexcept { return m_.param; }
Group& as_group() noexcept { return m_.group; }
const Param& as_param() const noexcept { return m_.param; }
const Group& as_group() const noexcept { return m_.group; }
private:
void destroy_content() {
switch(type_) {
default:
case type::param: m_.param.~Param(); break;
case type::group: m_.group.~Group(); break;
}
}
union data {
data() {}
data(const Param& v) : param{v} {}
data( Param&& v) noexcept : param{std::move(v)} {}
data(const Group& g) : group{g} {}
data( Group&& g) noexcept : group{std::move(g)} {}
~data() {}
Param param;
Group group;
};
data m_;
type type_;
};
public:
//---------------------------------------------------------------
using child = child_t<parameter,group>;
using value_type = child;
private:
using children_store = std::vector<child>;
public:
using const_iterator = children_store::const_iterator;
using iterator = children_store::iterator;
using size_type = children_store::size_type;
//---------------------------------------------------------------
/**
* @brief recursively iterates over all nodes
*/
class depth_first_traverser
{
public:
//-----------------------------------------------------
struct context {
context() = default;
context(const group& p):
parent{&p}, cur{p.begin()}, end{p.end()}
{}
const group* parent = nullptr;
const_iterator cur;
const_iterator end;
};
using context_list = std::vector<context>;
//-----------------------------------------------------
class memento {
friend class depth_first_traverser;
int level_;
context context_;
public:
int level() const noexcept { return level_; }
const child* param() const noexcept { return &(*context_.cur); }
};
depth_first_traverser() = default;
explicit
depth_first_traverser(const group& cur): stack_{} {
if(!cur.empty()) stack_.emplace_back(cur);
}
explicit operator bool() const noexcept {
return !stack_.empty();
}
int level() const noexcept {
return int(stack_.size());
}
bool is_first_in_group() const noexcept {
if(stack_.empty()) return false;
return (stack_.back().cur == stack_.back().parent->begin());
}
bool is_last_in_group() const noexcept {
if(stack_.empty()) return false;
return (stack_.back().cur+1 == stack_.back().end);
}
bool is_last_in_path() const noexcept {
if(stack_.empty()) return false;
for(const auto& t : stack_) {
if(t.cur+1 != t.end) return false;
}
const auto& top = stack_.back();
//if we have to descend into group on next ++ => not last in path
if(top.cur->is_group()) return false;
return true;
}
/** @brief inside a group of alternatives >= minlevel */
bool is_alternative(int minlevel = 0) const noexcept {
if(stack_.empty()) return false;
if(minlevel > 0) minlevel -= 1;
if(minlevel >= int(stack_.size())) return false;
return std::any_of(stack_.begin() + minlevel, stack_.end(),
[](const context& c) { return c.parent->exclusive(); });
}
/** @brief repeatable or inside a repeatable group >= minlevel */
bool is_repeatable(int minlevel = 0) const noexcept {
if(stack_.empty()) return false;
if(stack_.back().cur->repeatable()) return true;
if(minlevel > 0) minlevel -= 1;
if(minlevel >= int(stack_.size())) return false;
return std::any_of(stack_.begin() + minlevel, stack_.end(),
[](const context& c) { return c.parent->repeatable(); });
}
/** @brief inside group with joinable flags */
bool joinable() const noexcept {
if(stack_.empty()) return false;
return std::any_of(stack_.begin(), stack_.end(),
[](const context& c) { return c.parent->joinable(); });
}
const context_list&
stack() const {
return stack_;
}
/** @brief innermost repeat group */
const group*
repeat_group() const noexcept {
auto i = std::find_if(stack_.rbegin(), stack_.rend(),
[](const context& c) { return c.parent->repeatable(); });
return i != stack_.rend() ? i->parent : nullptr;
}
/** @brief outermost join group */
const group*
join_group() const noexcept {
auto i = std::find_if(stack_.begin(), stack_.end(),
[](const context& c) { return c.parent->joinable(); });
return i != stack_.end() ? i->parent : nullptr;
}
const group* root() const noexcept {
return stack_.empty() ? nullptr : stack_.front().parent;
}
/** @brief common flag prefix of all flags in current group */
arg_string common_flag_prefix() const noexcept {
if(stack_.empty()) return "";
auto g = join_group();
return g ? g->common_flag_prefix() : arg_string("");
}
const child&
operator * () const noexcept {
return *stack_.back().cur;
}
const child*
operator -> () const noexcept {
return &(*stack_.back().cur);
}
const group&
parent() const noexcept {
return *(stack_.back().parent);
}
/** @brief go to next element of depth first search */
depth_first_traverser&
operator ++ () {
if(stack_.empty()) return *this;
//at group -> decend into group
if(stack_.back().cur->is_group()) {
stack_.emplace_back(stack_.back().cur->as_group());
}
else {
next_sibling();
}
return *this;
}
/** @brief go to next sibling of current */
depth_first_traverser&
next_sibling() {
if(stack_.empty()) return *this;
++stack_.back().cur;
//at the end of current group?
while(stack_.back().cur == stack_.back().end) {
//go to parent
stack_.pop_back();
if(stack_.empty()) return *this;
//go to next sibling in parent
++stack_.back().cur;
}
return *this;
}
/** @brief go to next position after siblings of current */
depth_first_traverser&
next_after_siblings() {
if(stack_.empty()) return *this;
stack_.back().cur = stack_.back().end-1;
next_sibling();
return *this;
}
/** @brief skips to next alternative in innermost group
*/
depth_first_traverser&
next_alternative() {
if(stack_.empty()) return *this;
//find first exclusive group (from the top of the stack!)
auto i = std::find_if(stack_.rbegin(), stack_.rend(),
[](const context& c) { return c.parent->exclusive(); });
if(i == stack_.rend()) return *this;
stack_.erase(i.base(), stack_.end());
next_sibling();
return *this;
}
/**
* @brief
*/
depth_first_traverser&
back_to_parent() {
if(stack_.empty()) return *this;
stack_.pop_back();
return *this;
}
/** @brief don't visit next siblings, go back to parent on next ++
* note: renders siblings unreachable for *this
**/
depth_first_traverser&
skip_siblings() {
if(stack_.empty()) return *this;
//future increments won't visit subsequent siblings:
stack_.back().end = stack_.back().cur+1;
return *this;
}
/** @brief skips all other alternatives in surrounding exclusive groups
* on next ++
* note: renders alternatives unreachable for *this
*/
depth_first_traverser&
skip_alternatives() {
if(stack_.empty()) return *this;
//exclude all other alternatives in surrounding groups
//by making their current position the last one
for(auto& c : stack_) {
if(c.parent && c.parent->exclusive() && c.cur < c.end)
c.end = c.cur+1;
}
return *this;
}
void invalidate() {
stack_.clear();
}
inline friend bool operator == (const depth_first_traverser& a,
const depth_first_traverser& b)
{
if(a.stack_.empty() || b.stack_.empty()) return false;
//parents not the same -> different position
if(a.stack_.back().parent != b.stack_.back().parent) return false;
bool aEnd = a.stack_.back().cur == a.stack_.back().end;
bool bEnd = b.stack_.back().cur == b.stack_.back().end;
//either both at the end of the same parent => same position
if(aEnd && bEnd) return true;
//or only one at the end => not at the same position
if(aEnd || bEnd) return false;
return std::addressof(*a.stack_.back().cur) ==
std::addressof(*b.stack_.back().cur);
}
inline friend bool operator != (const depth_first_traverser& a,
const depth_first_traverser& b)
{
return !(a == b);
}
memento
undo_point() const {
memento m;
m.level_ = int(stack_.size());
if(!stack_.empty()) m.context_ = stack_.back();
return m;
}
void undo(const memento& m) {
if(m.level_ < 1) return;
if(m.level_ <= int(stack_.size())) {
stack_.erase(stack_.begin() + m.level_, stack_.end());
stack_.back() = m.context_;
}
else if(stack_.empty() && m.level_ == 1) {
stack_.push_back(m.context_);
}
}
private:
context_list stack_;
};
//---------------------------------------------------------------
group() = default;
template<class Param, class... Params>
explicit
group(doc_string docstr, Param param, Params... params):
children_{}, exclusive_{false}, joinable_{false}, scoped_{true}
{
doc(std::move(docstr));
push_back(std::move(param), std::move(params)...);
}
template<class... Params>
explicit
group(parameter param, Params... params):
children_{}, exclusive_{false}, joinable_{false}, scoped_{true}
{
push_back(std::move(param), std::move(params)...);
}
template<class P2, class... Ps>
explicit
group(group p1, P2 p2, Ps... ps):
children_{}, exclusive_{false}, joinable_{false}, scoped_{true}
{
push_back(std::move(p1), std::move(p2), std::move(ps)...);
}
//-----------------------------------------------------
group(const group&) = default;
group(group&&) = default;
//---------------------------------------------------------------
group& operator = (const group&) = default;
group& operator = (group&&) = default;
//---------------------------------------------------------------
/** @brief determines if a command line argument can be matched by a
* combination of (partial) matches through any number of children
*/
group& joinable(bool yes) {
joinable_ = yes;
return *this;
}
/** @brief returns if a command line argument can be matched by a
* combination of (partial) matches through any number of children
*/
bool joinable() const noexcept {
return joinable_;
}
//---------------------------------------------------------------
/** @brief turns explicit scoping on or off
* operators , & | and other combinating functions will
* not merge groups that are marked as scoped
*/
group& scoped(bool yes) {
scoped_ = yes;
return *this;
}
/** @brief returns true if operators , & | and other combinating functions
* will merge groups and false otherwise
*/
bool scoped() const noexcept
{
return scoped_;
}
//---------------------------------------------------------------
/** @brief determines if children are mutually exclusive alternatives */
group& exclusive(bool yes) {
exclusive_ = yes;
return *this;
}
/** @brief returns if children are mutually exclusive alternatives */
bool exclusive() const noexcept {
return exclusive_;
}
//---------------------------------------------------------------
/** @brief returns true, if any child is required to match */
bool any_required() const
{
return std::any_of(children_.begin(), children_.end(),
[](const child& n){ return n.required(); });
}
/** @brief returns true, if all children are required to match */
bool all_required() const
{
return std::all_of(children_.begin(), children_.end(),
[](const child& n){ return n.required(); });
}
//---------------------------------------------------------------
/** @brief returns true if any child is optional (=non-required) */
bool any_optional() const {
return !all_required();
}
/** @brief returns true if all children are optional (=non-required) */
bool all_optional() const {
return !any_required();
}
//---------------------------------------------------------------
/** @brief returns if the entire group is blocking / positional */
bool blocking() const noexcept {
return token<group>::blocking() || (exclusive() && all_blocking());
}
//-----------------------------------------------------
/** @brief determines if the entire group is blocking / positional */
group& blocking(bool yes) {
return token<group>::blocking(yes);
}
//---------------------------------------------------------------
/** @brief returns true if any child is blocking */
bool any_blocking() const
{
return std::any_of(children_.begin(), children_.end(),
[](const child& n){ return n.blocking(); });
}
//---------------------------------------------------------------
/** @brief returns true if all children is blocking */
bool all_blocking() const
{
return std::all_of(children_.begin(), children_.end(),
[](const child& n){ return n.blocking(); });
}
//---------------------------------------------------------------
/** @brief returns if any child is a value parameter (recursive) */
bool any_flagless() const
{
return std::any_of(children_.begin(), children_.end(),
[](const child& p){
return p.is_param() && p.as_param().flags().empty();
});
}
/** @brief returns if all children are value parameters (recursive) */
bool all_flagless() const
{
return std::all_of(children_.begin(), children_.end(),
[](const child& p){
return p.is_param() && p.as_param().flags().empty();
});
}
//---------------------------------------------------------------
/** @brief adds child parameter at the end */
group&
push_back(const parameter& v) {
children_.emplace_back(v);
return *this;
}
//-----------------------------------------------------
/** @brief adds child parameter at the end */
group&
push_back(parameter&& v) {
children_.emplace_back(std::move(v));
return *this;
}
//-----------------------------------------------------
/** @brief adds child group at the end */
group&
push_back(const group& g) {
children_.emplace_back(g);
return *this;
}
//-----------------------------------------------------
/** @brief adds child group at the end */
group&
push_back(group&& g) {
children_.emplace_back(std::move(g));
return *this;
}
//-----------------------------------------------------
/** @brief adds children (groups and/or parameters) */
template<class Param1, class Param2, class... Params>
group&
push_back(Param1&& param1, Param2&& param2, Params&&... params)
{
children_.reserve(children_.size() + 2 + sizeof...(params));
push_back(std::forward<Param1>(param1));
push_back(std::forward<Param2>(param2), std::forward<Params>(params)...);
return *this;
}
//---------------------------------------------------------------
/** @brief adds child parameter at the beginning */
group&
push_front(const parameter& v) {
children_.emplace(children_.begin(), v);
return *this;
}
//-----------------------------------------------------
/** @brief adds child parameter at the beginning */
group&
push_front(parameter&& v) {
children_.emplace(children_.begin(), std::move(v));
return *this;
}
//-----------------------------------------------------
/** @brief adds child group at the beginning */
group&
push_front(const group& g) {
children_.emplace(children_.begin(), g);
return *this;
}
//-----------------------------------------------------
/** @brief adds child group at the beginning */
group&
push_front(group&& g) {
children_.emplace(children_.begin(), std::move(g));
return *this;
}
//---------------------------------------------------------------
/** @brief adds all children of other group at the end */
group&
merge(group&& g)
{
children_.insert(children_.end(),
std::make_move_iterator(g.begin()),
std::make_move_iterator(g.end()));
return *this;
}
//-----------------------------------------------------
/** @brief adds all children of several other groups at the end */
template<class... Groups>
group&
merge(group&& g1, group&& g2, Groups&&... gs)
{
merge(std::move(g1));
merge(std::move(g2), std::forward<Groups>(gs)...);
return *this;
}
//---------------------------------------------------------------
/** @brief indexed, nutable access to child */
child& operator [] (size_type index) noexcept {
return children_[index];
}
/** @brief indexed, non-nutable access to child */
const child& operator [] (size_type index) const noexcept {
return children_[index];
}
//---------------------------------------------------------------
/** @brief mutable access to first child */
child& front() noexcept { return children_.front(); }
/** @brief non-mutable access to first child */
const child& front() const noexcept { return children_.front(); }
//-----------------------------------------------------
/** @brief mutable access to last child */
child& back() noexcept { return children_.back(); }
/** @brief non-mutable access to last child */
const child& back() const noexcept { return children_.back(); }
//---------------------------------------------------------------
/** @brief returns true, if group has no children, false otherwise */
bool empty() const noexcept { return children_.empty(); }
/** @brief returns number of children */
size_type size() const noexcept { return children_.size(); }
/** @brief returns number of nested levels; 1 for a flat group */
size_type depth() const {
size_type n = 0;
for(const auto& c : children_) {
auto l = 1 + c.depth();
if(l > n) n = l;
}
return n;
}
//---------------------------------------------------------------
/** @brief returns mutating iterator to position of first element */
iterator begin() noexcept { return children_.begin(); }
/** @brief returns non-mutating iterator to position of first element */
const_iterator begin() const noexcept { return children_.begin(); }
/** @brief returns non-mutating iterator to position of first element */
const_iterator cbegin() const noexcept { return children_.begin(); }
/** @brief returns mutating iterator to position one past the last element */
iterator end() noexcept { return children_.end(); }
/** @brief returns non-mutating iterator to position one past the last element */
const_iterator end() const noexcept { return children_.end(); }
/** @brief returns non-mutating iterator to position one past the last element */
const_iterator cend() const noexcept { return children_.end(); }
//---------------------------------------------------------------
/** @brief returns augmented iterator for depth first searches
* @details taverser knows end of iteration and can skip over children
*/
depth_first_traverser
begin_dfs() const noexcept {
return depth_first_traverser{*this};
}
//---------------------------------------------------------------
/** @brief returns recursive parameter count */
size_type param_count() const {
size_type c = 0;
for(const auto& n : children_) {
c += n.param_count();
}
return c;
}
//---------------------------------------------------------------
/** @brief returns range of all flags (recursive) */
arg_list all_flags() const
{
std::vector<arg_string> all;
gather_flags(children_, all);
return all;
}
/** @brief returns true, if no flag occurs as true
* prefix of any other flag (identical flags will be ignored) */
bool flags_are_prefix_free() const
{
const auto fs = all_flags();
using std::begin; using std::end;
for(auto i = begin(fs), e = end(fs); i != e; ++i) {
if(!i->empty()) {
for(auto j = i+1; j != e; ++j) {
if(!j->empty() && *i != *j) {
if(i->find(*j) == 0) return false;
if(j->find(*i) == 0) return false;
}
}
}
}
return true;
}
//---------------------------------------------------------------
/** @brief returns longest common prefix of all flags */
arg_string common_flag_prefix() const
{
arg_list prefixes;
gather_prefixes(children_, prefixes);
return str::longest_common_prefix(prefixes);
}
private:
//---------------------------------------------------------------
static void
gather_flags(const children_store& nodes, arg_list& all)
{
for(const auto& p : nodes) {
if(p.is_group()) {
gather_flags(p.as_group().children_, all);
}
else {
const auto& pf = p.as_param().flags();
using std::begin;
using std::end;
if(!pf.empty()) all.insert(end(all), begin(pf), end(pf));
}
}
}
//---------------------------------------------------------------
static void
gather_prefixes(const children_store& nodes, arg_list& all)
{
for(const auto& p : nodes) {
if(p.is_group()) {
gather_prefixes(p.as_group().children_, all);
}
else if(!p.as_param().flags().empty()) {
auto pfx = str::longest_common_prefix(p.as_param().flags());
if(!pfx.empty()) all.push_back(std::move(pfx));
}
}
}
//---------------------------------------------------------------
children_store children_;
bool exclusive_ = false;
bool joinable_ = false;
bool scoped_ = false;
};
/*************************************************************************//**
*
* @brief group or parameter
*
*****************************************************************************/
using pattern = group::child;
/*************************************************************************//**
*
* @brief apply an action to all parameters in a group
*
*****************************************************************************/
template<class Action>
void for_all_params(group& g, Action&& action)
{
for(auto& p : g) {
if(p.is_group()) {
for_all_params(p.as_group(), action);
}
else {
action(p.as_param());
}
}
}
template<class Action>
void for_all_params(const group& g, Action&& action)
{
for(auto& p : g) {
if(p.is_group()) {
for_all_params(p.as_group(), action);
}
else {
action(p.as_param());
}
}
}
/*************************************************************************//**
*
* @brief makes a group of parameters and/or groups
*
*****************************************************************************/
inline group
operator , (parameter a, parameter b)
{
return group{std::move(a), std::move(b)}.scoped(false);
}
//---------------------------------------------------------
inline group
operator , (parameter a, group b)
{
return !b.scoped() && !b.blocking() && !b.exclusive() && !b.repeatable()
&& !b.joinable() && (b.doc().empty() || b.doc() == a.doc())
? b.push_front(std::move(a))
: group{std::move(a), std::move(b)}.scoped(false);
}
//---------------------------------------------------------
inline group
operator , (group a, parameter b)
{
return !a.scoped() && !a.blocking() && !a.exclusive() && !a.repeatable()
&& !a.joinable() && (a.doc().empty() || a.doc() == b.doc())
? a.push_back(std::move(b))
: group{std::move(a), std::move(b)}.scoped(false);
}
//---------------------------------------------------------
inline group
operator , (group a, group b)
{
return !a.scoped() && !a.blocking() && !a.exclusive() && !a.repeatable()
&& !a.joinable() && (a.doc().empty() || a.doc() == b.doc())
? a.push_back(std::move(b))
: group{std::move(a), std::move(b)}.scoped(false);
}
/*************************************************************************//**
*
* @brief makes a group of alternative parameters or groups
*
*****************************************************************************/
template<class Param, class... Params>
inline group
one_of(Param param, Params... params)
{
return group{std::move(param), std::move(params)...}.exclusive(true);
}
/*************************************************************************//**
*
* @brief makes a group of alternative parameters or groups
*
*****************************************************************************/
inline group
operator | (parameter a, parameter b)
{
return group{std::move(a), std::move(b)}.scoped(false).exclusive(true);
}
//-------------------------------------------------------------------
inline group
operator | (parameter a, group b)
{
return !b.scoped() && !b.blocking() && b.exclusive() && !b.repeatable()
&& !b.joinable()
&& (b.doc().empty() || b.doc() == a.doc())
? b.push_front(std::move(a))
: group{std::move(a), std::move(b)}.scoped(false).exclusive(true);
}
//-------------------------------------------------------------------
inline group
operator | (group a, parameter b)
{
return !a.scoped() && a.exclusive() && !a.repeatable() && !a.joinable()
&& a.blocking() == b.blocking()
&& (a.doc().empty() || a.doc() == b.doc())
? a.push_back(std::move(b))
: group{std::move(a), std::move(b)}.scoped(false).exclusive(true);
}
inline group
operator | (group a, group b)
{
return !a.scoped() && a.exclusive() &&!a.repeatable() && !a.joinable()
&& a.blocking() == b.blocking()
&& (a.doc().empty() || a.doc() == b.doc())
? a.push_back(std::move(b))
: group{std::move(a), std::move(b)}.scoped(false).exclusive(true);
}
namespace detail {
inline void set_blocking(bool) {}
template<class P, class... Ps>
void set_blocking(bool yes, P& p, Ps&... ps) {
p.blocking(yes);
set_blocking(yes, ps...);
}
} // namespace detail
/*************************************************************************//**
*
* @brief makes a parameter/group sequence by making all input objects blocking
*
*****************************************************************************/
template<class Param, class... Params>
inline group
in_sequence(Param param, Params... params)
{
detail::set_blocking(true, param, params...);
return group{std::move(param), std::move(params)...}.scoped(true);
}
/*************************************************************************//**
*
* @brief makes a parameter/group sequence by making all input objects blocking
*
*****************************************************************************/
inline group
operator & (parameter a, parameter b)
{
a.blocking(true);
b.blocking(true);
return group{std::move(a), std::move(b)}.scoped(true);
}
//---------------------------------------------------------
inline group
operator & (parameter a, group b)
{
a.blocking(true);
return group{std::move(a), std::move(b)}.scoped(true);
}
//---------------------------------------------------------
inline group
operator & (group a, parameter b)
{
b.blocking(true);
if(a.all_blocking() && !a.exclusive() && !a.repeatable() && !a.joinable()
&& (a.doc().empty() || a.doc() == b.doc()))
{
return a.push_back(std::move(b));
}
else {
if(!a.all_blocking()) a.blocking(true);
return group{std::move(a), std::move(b)}.scoped(true);
}
}
inline group
operator & (group a, group b)
{
if(!b.all_blocking()) b.blocking(true);
if(a.all_blocking() && !a.exclusive() && !a.repeatable()
&& !a.joinable() && (a.doc().empty() || a.doc() == b.doc()))
{
return a.push_back(std::move(b));
}
else {
if(!a.all_blocking()) a.blocking(true);
return group{std::move(a), std::move(b)}.scoped(true);
}
}
/*************************************************************************//**
*
* @brief makes a group of parameters and/or groups
* where all single char flag params ("-a", "b", ...) are joinable
*
*****************************************************************************/
inline group
joinable(group g) {
return g.joinable(true);
}
//-------------------------------------------------------------------
template<class... Params>
inline group
joinable(parameter param, Params... params)
{
return group{std::move(param), std::move(params)...}.joinable(true);
}
template<class P2, class... Ps>
inline group
joinable(group p1, P2 p2, Ps... ps)
{
return group{std::move(p1), std::move(p2), std::move(ps)...}.joinable(true);
}
template<class Param, class... Params>
inline group
joinable(doc_string docstr, Param param, Params... params)
{
return group{std::move(param), std::move(params)...}
.joinable(true).doc(std::move(docstr));
}
/*************************************************************************//**
*
* @brief makes a repeatable copy of a parameter
*
*****************************************************************************/
inline parameter
repeatable(parameter p) {
return p.repeatable(true);
}
/*************************************************************************//**
*
* @brief makes a repeatable copy of a group
*
*****************************************************************************/
inline group
repeatable(group g) {
return g.repeatable(true);
}
/*************************************************************************//**
*
* @brief makes a group of parameters and/or groups
* that is repeatable as a whole
* Note that a repeatable group consisting entirely of non-blocking
* children is equivalent to a non-repeatable group of
* repeatable children.
*
*****************************************************************************/
template<class P2, class... Ps>
inline group
repeatable(parameter p1, P2 p2, Ps... ps)
{
return group{std::move(p1), std::move(p2),
std::move(ps)...}.repeatable(true);
}
template<class P2, class... Ps>
inline group
repeatable(group p1, P2 p2, Ps... ps)
{
return group{std::move(p1), std::move(p2),
std::move(ps)...}.repeatable(true);
}
/*************************************************************************//**
*
* @brief makes a parameter greedy (match with top priority)
*
*****************************************************************************/
inline parameter
greedy(parameter p) {
return p.greedy(true);
}
inline parameter
operator ! (parameter p) {
return greedy(p);
}
/*************************************************************************//**
*
* @brief recursively prepends a prefix to all flags
*
*****************************************************************************/
inline parameter&&
with_prefix(const arg_string& prefix, parameter&& p) {
return std::move(with_prefix(prefix, p));
}
//-------------------------------------------------------------------
inline group&
with_prefix(const arg_string& prefix, group& g)
{
for(auto& p : g) {
if(p.is_group()) {
with_prefix(prefix, p.as_group());
} else {
with_prefix(prefix, p.as_param());
}
}
return g;
}
inline group&&
with_prefix(const arg_string& prefix, group&& params)
{
return std::move(with_prefix(prefix, params));
}
template<class Param, class... Params>
inline group
with_prefix(arg_string prefix, Param&& param, Params&&... params)
{
return with_prefix(prefix, group{std::forward<Param>(param),
std::forward<Params>(params)...});
}
/*************************************************************************//**
*
* @brief recursively prepends a prefix to all flags
*
* @param shortpfx : used for single-letter flags
* @param longpfx : used for flags with length > 1
*
*****************************************************************************/
inline parameter&&
with_prefixes_short_long(const arg_string& shortpfx, const arg_string& longpfx,
parameter&& p)
{
return std::move(with_prefixes_short_long(shortpfx, longpfx, p));
}
//-------------------------------------------------------------------
inline group&
with_prefixes_short_long(const arg_string& shortFlagPrefix,
const arg_string& longFlagPrefix,
group& g)
{
for(auto& p : g) {
if(p.is_group()) {
with_prefixes_short_long(shortFlagPrefix, longFlagPrefix, p.as_group());
} else {
with_prefixes_short_long(shortFlagPrefix, longFlagPrefix, p.as_param());
}
}
return g;
}
inline group&&
with_prefixes_short_long(const arg_string& shortFlagPrefix,
const arg_string& longFlagPrefix,
group&& params)
{
return std::move(with_prefixes_short_long(shortFlagPrefix, longFlagPrefix,
params));
}
template<class Param, class... Params>
inline group
with_prefixes_short_long(const arg_string& shortFlagPrefix,
const arg_string& longFlagPrefix,
Param&& param, Params&&... params)
{
return with_prefixes_short_long(shortFlagPrefix, longFlagPrefix,
group{std::forward<Param>(param),
std::forward<Params>(params)...});
}
/*************************************************************************//**
*
* @brief parsing implementation details
*
*****************************************************************************/
namespace detail {
/*************************************************************************//**
*
* @brief DFS traverser that keeps track of 'scopes'
* scope = all parameters that are either bounded by
* two blocking parameters on the same depth level
* or the beginning/end of the outermost group
*
*****************************************************************************/
class scoped_dfs_traverser
{
public:
using dfs_traverser = group::depth_first_traverser;
scoped_dfs_traverser() = default;
explicit
scoped_dfs_traverser(const group& g):
pos_{g}, lastMatch_{}, posAfterLastMatch_{}, scopes_{},
curMatched_{false}, ignoreBlocks_{false},
repeatGroupStarted_{false}, repeatGroupContinues_{false}
{}
const dfs_traverser& base() const noexcept { return pos_; }
const dfs_traverser& last_match() const noexcept { return lastMatch_; }
const group& parent() const noexcept { return pos_.parent(); }
const group* repeat_group() const noexcept { return pos_.repeat_group(); }
const group* join_group() const noexcept { return pos_.join_group(); }
const pattern* operator ->() const noexcept { return pos_.operator->(); }
const pattern& operator *() const noexcept { return *pos_; }
const pattern* ptr() const noexcept { return pos_.operator->(); }
explicit operator bool() const noexcept { return bool(pos_); }
bool joinable() const noexcept { return pos_.joinable(); }
arg_string common_flag_prefix() const { return pos_.common_flag_prefix(); }
void ignore_blocking(bool yes) { ignoreBlocks_ = yes; }
void invalidate() { pos_.invalidate(); curMatched_ = false; }
bool matched() const noexcept { return curMatched_; }
bool start_of_repeat_group() const noexcept { return repeatGroupStarted_; }
//-----------------------------------------------------
scoped_dfs_traverser&
next_sibling() { pos_.next_sibling(); return *this; }
scoped_dfs_traverser&
next_alternative() { pos_.next_alternative(); return *this; }
scoped_dfs_traverser&
next_after_siblings() { pos_.next_after_siblings(); return *this; }
//-----------------------------------------------------
scoped_dfs_traverser&
operator ++ ()
{
if(!pos_) return *this;
if(pos_.is_last_in_path()) {
return_to_outermost_scope();
return *this;
}
//current pattern can block if it didn't match already
if(!ignoreBlocks_ && !matched()) {
//current group can block if we didn't have any match in it
if(pos_.is_last_in_group() && pos_.parent().blocking()
&& (!posAfterLastMatch_ || &(posAfterLastMatch_.parent()) != &(pos_.parent())))
{
//ascend to parent's level
++pos_;
//skip all siblings of parent group
pos_.next_after_siblings();
if(!pos_) return_to_outermost_scope();
}
else if(pos_->blocking() && !pos_->is_group()) {
if(pos_.parent().exclusive()) { //is_alternative(pos_.level())) {
pos_.next_alternative();
} else {
//no match => skip siblings of blocking param
pos_.next_after_siblings();
}
if(!pos_) return_to_outermost_scope();
} else {
++pos_;
}
} else {
++pos_;
}
check_left_scope();
return *this;
}
//-----------------------------------------------------
void next_after_match(scoped_dfs_traverser match)
{
if(!match || ignoreBlocks_) return;
check_repeat_group_start(match);
lastMatch_ = match.base();
if(!match->blocking() && match.base().parent().blocking()) {
match.pos_.back_to_parent();
}
//if match is not in current position & current position is blocking
//=> current position has to be advanced by one so that it is
//no longer reachable within current scope
//(can happen for repeatable, blocking parameters)
if(match.base() != pos_ && pos_->blocking()) pos_.next_sibling();
if(match->blocking()) {
if(match.pos_.is_alternative()) {
//discard other alternatives
match.pos_.skip_alternatives();
}
if(is_last_in_current_scope(match.pos_)) {
//if current param is not repeatable -> back to previous scope
if(!match->repeatable() && !match->is_group()) {
curMatched_ = false;
pos_ = std::move(match.pos_);
if(!scopes_.empty()) pos_.undo(scopes_.top());
}
else { //stay at match position
curMatched_ = true;
pos_ = std::move(match.pos_);
}
}
else { //not last in current group
//if current param is not repeatable, go directly to next
if(!match->repeatable() && !match->is_group()) {
curMatched_ = false;
++match.pos_;
} else {
curMatched_ = true;
}
if(match.pos_.level() > pos_.level()) {
scopes_.push(pos_.undo_point());
pos_ = std::move(match.pos_);
}
else if(match.pos_.level() < pos_.level()) {
return_to_level(match.pos_.level());
}
else {
pos_ = std::move(match.pos_);
}
}
posAfterLastMatch_ = pos_;
}
else {
if(match.pos_.level() < pos_.level()) {
return_to_level(match.pos_.level());
}
posAfterLastMatch_ = pos_;
}
repeatGroupContinues_ = repeat_group_continues();
}
private:
//-----------------------------------------------------
bool is_last_in_current_scope(const dfs_traverser& pos)
{
if(scopes_.empty()) return pos.is_last_in_path();
//check if we would leave the current scope on ++
auto p = pos;
++p;
return p.level() < scopes_.top().level();
}
//-----------------------------------------------------
void check_repeat_group_start(const scoped_dfs_traverser& newMatch)
{
const auto newrg = newMatch.repeat_group();
if(!newrg) {
repeatGroupStarted_ = false;
}
else if(lastMatch_.repeat_group() != newrg) {
repeatGroupStarted_ = true;
}
else if(!repeatGroupContinues_ || !newMatch.repeatGroupContinues_) {
repeatGroupStarted_ = true;
}
else {
//special case: repeat group is outermost group
//=> we can never really 'leave' and 'reenter' it
//but if the current scope is the first element, then we are
//conceptually at a position 'before' the group
repeatGroupStarted_ = scopes_.empty() || (
newrg == pos_.root() &&
scopes_.top().param() == &(*pos_.root()->begin()) );
}
repeatGroupContinues_ = repeatGroupStarted_;
}
//-----------------------------------------------------
bool repeat_group_continues()
{
if(!repeatGroupContinues_) return false;
const auto curRepGroup = pos_.repeat_group();
if(!curRepGroup) return false;
if(curRepGroup != lastMatch_.repeat_group()) return false;
if(!posAfterLastMatch_) return false;
return true;
}
//-----------------------------------------------------
void check_left_scope()
{
if(posAfterLastMatch_) {
if(pos_.level() < posAfterLastMatch_.level()) {
while(!scopes_.empty() && scopes_.top().level() >= pos_.level()) {
pos_.undo(scopes_.top());
scopes_.pop();
}
posAfterLastMatch_.invalidate();
}
}
while(!scopes_.empty() && scopes_.top().level() > pos_.level()) {
pos_.undo(scopes_.top());
scopes_.pop();
}
repeatGroupContinues_ = repeat_group_continues();
}
//-----------------------------------------------------
void return_to_outermost_scope()
{
posAfterLastMatch_.invalidate();
if(scopes_.empty()) {
pos_.invalidate();
repeatGroupContinues_ = false;
return;
}
while(!scopes_.empty() && (!pos_ || pos_.level() >= 1)) {
pos_.undo(scopes_.top());
scopes_.pop();
}
while(!scopes_.empty()) scopes_.pop();
repeatGroupContinues_ = repeat_group_continues();
}
//-----------------------------------------------------
void return_to_level(int level)
{
if(pos_.level() <= level) return;
while(!scopes_.empty() && pos_.level() > level) {
pos_.undo(scopes_.top());
scopes_.pop();
}
};
dfs_traverser pos_;
dfs_traverser lastMatch_;
dfs_traverser posAfterLastMatch_;
std::stack<dfs_traverser::memento> scopes_;
bool curMatched_ = false;
bool ignoreBlocks_ = false;
bool repeatGroupStarted_ = false;
bool repeatGroupContinues_ = false;
};
/*****************************************************************************
*
* some parameter property predicates
*
*****************************************************************************/
struct select_all {
bool operator () (const parameter&) const noexcept { return true; }
};
struct select_flags {
bool operator () (const parameter& p) const noexcept {
return !p.flags().empty();
}
};
struct select_values {
bool operator () (const parameter& p) const noexcept {
return p.flags().empty();
}
};
/*************************************************************************//**
*
* @brief result of a matching operation
*
*****************************************************************************/
class match_t {
public:
match_t() = default;
match_t(arg_string s, scoped_dfs_traverser p):
str_{std::move(s)}, pos_{std::move(p)}
{}
const arg_string& str() const noexcept { return str_; }
const scoped_dfs_traverser& pos() const noexcept { return pos_; }
explicit operator bool() const noexcept { return !str_.empty(); }
private:
arg_string str_;
scoped_dfs_traverser pos_;
};
/*************************************************************************//**
*
* @brief finds the first parameter that matches a given string
* candidate parameters are traversed using a scoped DFS traverser
*
*****************************************************************************/
template<class ParamSelector>
match_t
full_match(scoped_dfs_traverser pos, const arg_string& arg,
const ParamSelector& select)
{
if(arg.empty()) return match_t{};
while(pos) {
if(pos->is_param()) {
const auto& param = pos->as_param();
if(select(param)) {
const auto match = param.match(arg);
if(match && match.length() == arg.size()) {
return match_t{arg, std::move(pos)};
}
}
}
++pos;
}
return match_t{};
}
/*************************************************************************//**
*
* @brief finds the first parameter that matches any (non-empty) prefix
* of a given string;
* candidate parameters are traversed using a scoped DFS traverser
*
*****************************************************************************/
template<class ParamSelector>
match_t
prefix_match(scoped_dfs_traverser pos, const arg_string& arg,
const ParamSelector& select)
{
if(arg.empty()) return match_t{};
while(pos) {
if(pos->is_param()) {
const auto& param = pos->as_param();
if(select(param)) {
const auto match = param.match(arg);
if(match.prefix()) {
if(match.length() == arg.size()) {
return match_t{arg, std::move(pos)};
}
else {
return match_t{arg.substr(match.at(), match.length()),
std::move(pos)};
}
}
}
}
++pos;
}
return match_t{};
}
/*************************************************************************//**
*
* @brief finds the first parameter that partially matches a given string;
* candidate parameters are traversed using a scoped DFS traverser
*
*****************************************************************************/
template<class ParamSelector>
match_t
partial_match(scoped_dfs_traverser pos, const arg_string& arg,
const ParamSelector& select)
{
if(arg.empty()) return match_t{};
while(pos) {
if(pos->is_param()) {
const auto& param = pos->as_param();
if(select(param)) {
const auto match = param.match(arg);
if(match) {
return match_t{arg.substr(match.at(), match.length()),
std::move(pos)};
}
}
}
++pos;
}
return match_t{};
}
} //namespace detail
/***************************************************************//**
*
* @brief default command line arguments parser
*
*******************************************************************/
class parser
{
public:
using dfs_traverser = group::depth_first_traverser;
using scoped_dfs_traverser = detail::scoped_dfs_traverser;
/*****************************************************//**
* @brief arg -> parameter mapping
*********************************************************/
class arg_mapping {
public:
friend class parser;
explicit
arg_mapping(arg_index idx, arg_string s,
const dfs_traverser& match)
:
index_{idx}, arg_{std::move(s)}, match_{match},
repeat_{0}, startsRepeatGroup_{false},
blocked_{false}, conflict_{false}
{}
explicit
arg_mapping(arg_index idx, arg_string s) :
index_{idx}, arg_{std::move(s)}, match_{},
repeat_{0}, startsRepeatGroup_{false},
blocked_{false}, conflict_{false}
{}
arg_index index() const noexcept { return index_; }
const arg_string& arg() const noexcept { return arg_; }
const parameter* param() const noexcept {
return match_ && match_->is_param()
? &(match_->as_param()) : nullptr;
}
std::size_t repeat() const noexcept { return repeat_; }
bool blocked() const noexcept { return blocked_; }
bool conflict() const noexcept { return conflict_; }
bool bad_repeat() const noexcept {
if(!param()) return false;
return repeat_ > 0 && !param()->repeatable()
&& !match_.repeat_group();
}
bool any_error() const noexcept {
return !match_ || blocked() || conflict() || bad_repeat();
}
private:
arg_index index_;
arg_string arg_;
dfs_traverser match_;
std::size_t repeat_;
bool startsRepeatGroup_;
bool blocked_;
bool conflict_;
};
/*****************************************************//**
* @brief references a non-matched, required parameter
*********************************************************/
class missing_event {
public:
explicit
missing_event(const parameter* p, arg_index after):
param_{p}, aftIndex_{after}
{}
const parameter* param() const noexcept { return param_; }
arg_index after_index() const noexcept { return aftIndex_; }
private:
const parameter* param_;
arg_index aftIndex_;
};
//-----------------------------------------------------
using missing_events = std::vector<missing_event>;
using arg_mappings = std::vector<arg_mapping>;
private:
struct miss_candidate {
miss_candidate(dfs_traverser p, arg_index idx,
bool firstInRepeatGroup = false):
pos{std::move(p)}, index{idx},
startsRepeatGroup{firstInRepeatGroup}
{}
dfs_traverser pos;
arg_index index;
bool startsRepeatGroup;
};
using miss_candidates = std::vector<miss_candidate>;
public:
//---------------------------------------------------------------
/** @brief initializes parser with a command line interface
* @param offset = argument index offset used for reports
* */
explicit
parser(const group& root, arg_index offset = 0):
root_{&root}, pos_{root},
index_{offset-1}, eaten_{0},
args_{}, missCand_{}, blocked_{false}
{
for_each_potential_miss(dfs_traverser{root},
[this](const dfs_traverser& p){
missCand_.emplace_back(p, index_);
});
}
//---------------------------------------------------------------
/** @brief processes one command line argument */
bool operator() (const arg_string& arg)
{
++eaten_;
++index_;
if(!valid() || arg.empty()) return false;
if(!blocked_ && try_match(arg)) return true;
if(try_match_blocked(arg)) return false;
//skipping of blocking & required patterns is not allowed
if(!blocked_ && !pos_.matched() && pos_->required() && pos_->blocking()) {
blocked_ = true;
}
add_nomatch(arg);
return false;
}
//---------------------------------------------------------------
/** @brief returns range of argument -> parameter mappings */
const arg_mappings& args() const {
return args_;
}
/** @brief returns list of missing events */
missing_events missed() const {
missing_events misses;
misses.reserve(missCand_.size());
for(auto i = missCand_.begin(); i != missCand_.end(); ++i) {
misses.emplace_back(&(i->pos->as_param()), i->index);
}
return misses;
}
/** @brief returns number of processed command line arguments */
arg_index parse_count() const noexcept { return eaten_; }
/** @brief returns false if previously processed command line arguments
* lead to an invalid / inconsistent parsing result
*/
bool valid() const noexcept { return bool(pos_); }
/** @brief returns false if previously processed command line arguments
* lead to an invalid / inconsistent parsing result
*/
explicit operator bool() const noexcept { return valid(); }
private:
//---------------------------------------------------------------
using match_t = detail::match_t;
//---------------------------------------------------------------
/** @brief try to match argument with unreachable parameter */
bool try_match_blocked(const arg_string& arg)
{
//try to match ahead (using temporary parser)
if(pos_) {
auto ahead = *this;
if(try_match_blocked(std::move(ahead), arg)) return true;
}
//try to match from the beginning (using temporary parser)
if(root_) {
parser all{*root_, index_+1};
if(try_match_blocked(std::move(all), arg)) return true;
}
return false;
}
//---------------------------------------------------------------
bool try_match_blocked(parser&& parse, const arg_string& arg)
{
const auto nold = int(parse.args_.size());
parse.pos_.ignore_blocking(true);
if(!parse.try_match(arg)) return false;
for(auto i = parse.args_.begin() + nold; i != parse.args_.end(); ++i) {
args_.push_back(*i);
args_.back().blocked_ = true;
}
return true;
}
//---------------------------------------------------------------
/** @brief try to find a parameter/pattern that matches 'arg' */
bool try_match(const arg_string& arg)
{
//match greedy parameters before everything else
if(pos_->is_param() && pos_->blocking() && pos_->as_param().greedy()) {
const auto match = pos_->as_param().match(arg);
if(match && match.length() == arg.size()) {
add_match(detail::match_t{arg,pos_});
return true;
}
}
//try flags first (alone, joinable or strict sequence)
if(try_match_full(arg, detail::select_flags{})) return true;
if(try_match_joined_flags(arg)) return true;
if(try_match_joined_sequence(arg, detail::select_flags{})) return true;
//try value params (alone or strict sequence)
if(try_match_full(arg, detail::select_values{})) return true;
if(try_match_joined_sequence(arg, detail::select_all{})) return true;
//try joinable params + values in any order
if(try_match_joined_params(arg)) return true;
return false;
}
//---------------------------------------------------------------
/**
* @brief try to match full argument
* @param select : predicate that candidate parameters must satisfy
*/
template<class ParamSelector>
bool try_match_full(const arg_string& arg, const ParamSelector& select)
{
auto match = detail::full_match(pos_, arg, select);
if(!match) return false;
add_match(match);
return true;
}
//---------------------------------------------------------------
/**
* @brief try to match argument as blocking sequence of parameters
* @param select : predicate that a parameter matching the prefix of
* 'arg' must satisfy
*/
template<class ParamSelector>
bool try_match_joined_sequence(arg_string arg,
const ParamSelector& acceptFirst)
{
auto fstMatch = detail::prefix_match(pos_, arg, acceptFirst);
if(!fstMatch) return false;
if(fstMatch.str().size() == arg.size()) {
add_match(fstMatch);
return true;
}
if(!fstMatch.pos()->blocking()) return false;
auto pos = fstMatch.pos();
pos.ignore_blocking(true);
const auto parent = &pos.parent();
if(!pos->repeatable()) ++pos;
arg.erase(0, fstMatch.str().size());
std::vector<match_t> matches { std::move(fstMatch) };
while(!arg.empty() && pos &&
pos->blocking() && pos->is_param() &&
(&pos.parent() == parent))
{
auto match = pos->as_param().match(arg);
if(match.prefix()) {
matches.emplace_back(arg.substr(0,match.length()), pos);
arg.erase(0, match.length());
if(!pos->repeatable()) ++pos;
}
else {
if(!pos->repeatable()) return false;
++pos;
}
}
//if arg not fully covered => discard temporary matches
if(!arg.empty() || matches.empty()) return false;
for(const auto& m : matches) add_match(m);
return true;
}
//-----------------------------------------------------
/** @brief try to match 'arg' as a concatenation of joinable flags */
bool try_match_joined_flags(const arg_string& arg)
{
return find_join_group(pos_, [&](const group& g) {
return try_match_joined(g, arg, detail::select_flags{},
g.common_flag_prefix());
});
}
//---------------------------------------------------------------
/** @brief try to match 'arg' as a concatenation of joinable parameters */
bool try_match_joined_params(const arg_string& arg)
{
return find_join_group(pos_, [&](const group& g) {
return try_match_joined(g, arg, detail::select_all{});
});
}
//-----------------------------------------------------
/** @brief try to match 'arg' as concatenation of joinable parameters
* that are all contaied within one group
*/
template<class ParamSelector>
bool try_match_joined(const group& joinGroup, arg_string arg,
const ParamSelector& select,
const arg_string& prefix = "")
{
//temporary parser with 'joinGroup' as top-level group
parser parse {joinGroup};
//records temporary matches
std::vector<match_t> matches;
while(!arg.empty()) {
auto match = detail::prefix_match(parse.pos_, arg, select);
if(!match) return false;
arg.erase(0, match.str().size());
//make sure prefix is always present after the first match
//so that, e.g., flags "-a" and "-b" will be found in "-ab"
if(!arg.empty() && !prefix.empty() && arg.find(prefix) != 0 &&
prefix != match.str())
{
arg.insert(0,prefix);
}
parse.add_match(match);
matches.push_back(std::move(match));
}
if(!arg.empty() || matches.empty()) return false;
if(!parse.missCand_.empty()) return false;
for(const auto& a : parse.args_) if(a.any_error()) return false;
//replay matches onto *this
for(const auto& m : matches) add_match(m);
return true;
}
//-----------------------------------------------------
template<class GroupSelector>
bool find_join_group(const scoped_dfs_traverser& start,
const GroupSelector& accept) const
{
if(start && start.parent().joinable()) {
const auto& g = start.parent();
if(accept(g)) return true;
return false;
}
auto pos = start;
while(pos) {
if(pos->is_group() && pos->as_group().joinable()) {
const auto& g = pos->as_group();
if(accept(g)) return true;
pos.next_sibling();
}
else {
++pos;
}
}
return false;
}
//---------------------------------------------------------------
void add_nomatch(const arg_string& arg) {
args_.emplace_back(index_, arg);
}
//---------------------------------------------------------------
void add_match(const match_t& match)
{
const auto& pos = match.pos();
if(!pos || !pos->is_param() || match.str().empty()) return;
pos_.next_after_match(pos);
arg_mapping newArg{index_, match.str(), pos.base()};
newArg.repeat_ = occurrences_of(&pos->as_param());
newArg.conflict_ = check_conflicts(pos.base());
newArg.startsRepeatGroup_ = pos_.start_of_repeat_group();
args_.push_back(std::move(newArg));
add_miss_candidates_after(pos);
clean_miss_candidates_for(pos.base());
discard_alternative_miss_candidates(pos.base());
}
//-----------------------------------------------------
bool check_conflicts(const dfs_traverser& match)
{
if(pos_.start_of_repeat_group()) return false;
bool conflict = false;
for(const auto& m : match.stack()) {
if(m.parent->exclusive()) {
for(auto i = args_.rbegin(); i != args_.rend(); ++i) {
if(!i->blocked()) {
for(const auto& c : i->match_.stack()) {
//sibling within same exclusive group => conflict
if(c.parent == m.parent && c.cur != m.cur) {
conflict = true;
i->conflict_ = true;
}
}
}
//check for conflicts only within current repeat cycle
if(i->startsRepeatGroup_) break;
}
}
}
return conflict;
}
//-----------------------------------------------------
void clean_miss_candidates_for(const dfs_traverser& match)
{
auto i = std::find_if(missCand_.rbegin(), missCand_.rend(),
[&](const miss_candidate& m) {
return &(*m.pos) == &(*match);
});
if(i != missCand_.rend()) {
missCand_.erase(prev(i.base()));
}
}
//-----------------------------------------------------
void discard_alternative_miss_candidates(const dfs_traverser& match)
{
if(missCand_.empty()) return;
//find out, if miss candidate is sibling of one of the same
//alternative groups that the current match is a member of
//if so, we can discard the miss
//go through all exclusive groups of matching pattern
for(const auto& m : match.stack()) {
if(m.parent->exclusive()) {
for(auto i = int(missCand_.size())-1; i >= 0; --i) {
bool removed = false;
for(const auto& c : missCand_[i].pos.stack()) {
//sibling within same exclusive group => discard
if(c.parent == m.parent && c.cur != m.cur) {
missCand_.erase(missCand_.begin() + i);
if(missCand_.empty()) return;
removed = true;
break;
}
}
//remove miss candidates only within current repeat cycle
if(i > 0 && removed) {
if(missCand_[i-1].startsRepeatGroup) break;
} else {
if(missCand_[i].startsRepeatGroup) break;
}
}
}
}
}
//-----------------------------------------------------
void add_miss_candidates_after(const scoped_dfs_traverser& match)
{
auto npos = match.base();
if(npos.is_alternative()) npos.skip_alternatives();
++npos;
//need to add potential misses if:
//either new repeat group was started
const auto newRepGroup = match.repeat_group();
if(newRepGroup) {
if(pos_.start_of_repeat_group()) {
for_each_potential_miss(std::move(npos),
[&,this](const dfs_traverser& pos) {
//only add candidates within repeat group
if(newRepGroup == pos.repeat_group()) {
missCand_.emplace_back(pos, index_, true);
}
});
}
}
//... or an optional blocking param was hit
else if(match->blocking() && !match->required() &&
npos.level() >= match.base().level())
{
for_each_potential_miss(std::move(npos),
[&,this](const dfs_traverser& pos) {
//only add new candidates
if(std::find_if(missCand_.begin(), missCand_.end(),
[&](const miss_candidate& c){
return &(*c.pos) == &(*pos);
}) == missCand_.end())
{
missCand_.emplace_back(pos, index_);
}
});
}
}
//-----------------------------------------------------
template<class Action>
static void
for_each_potential_miss(dfs_traverser pos, Action&& action)
{
const auto level = pos.level();
while(pos && pos.level() >= level) {
if(pos->is_group() ) {
const auto& g = pos->as_group();
if(g.all_optional() || (g.exclusive() && g.any_optional())) {
pos.next_sibling();
} else {
++pos;
}
} else { //param
if(pos->required()) {
action(pos);
++pos;
} else if(pos->blocking()) { //optional + blocking
pos.next_after_siblings();
} else {
++pos;
}
}
}
}
//---------------------------------------------------------------
std::size_t occurrences_of(const parameter* p) const
{
auto i = std::find_if(args_.rbegin(), args_.rend(),
[p](const arg_mapping& a){ return a.param() == p; });
if(i != args_.rend()) return i->repeat() + 1;
return 0;
}
//---------------------------------------------------------------
const group* root_;
scoped_dfs_traverser pos_;
arg_index index_;
arg_index eaten_;
arg_mappings args_;
miss_candidates missCand_;
bool blocked_;
};
/*************************************************************************//**
*
* @brief contains argument -> parameter mappings
* and missing parameters
*
*****************************************************************************/
class parsing_result
{
public:
using arg_mapping = parser::arg_mapping;
using arg_mappings = parser::arg_mappings;
using missing_event = parser::missing_event;
using missing_events = parser::missing_events;
using iterator = arg_mappings::const_iterator;
//-----------------------------------------------------
/** @brief default: empty redult */
parsing_result() = default;
parsing_result(arg_mappings arg2param, missing_events misses):
arg2param_{std::move(arg2param)}, missing_{std::move(misses)}
{}
//-----------------------------------------------------
/** @brief returns number of arguments that could not be mapped to
* a parameter
*/
arg_mappings::size_type
unmapped_args_count() const noexcept {
return std::count_if(arg2param_.begin(), arg2param_.end(),
[](const arg_mapping& a){ return !a.param(); });
}
/** @brief returns if any argument could only be matched by an
* unreachable parameter
*/
bool any_blocked() const noexcept {
return std::any_of(arg2param_.begin(), arg2param_.end(),
[](const arg_mapping& a){ return a.blocked(); });
}
/** @brief returns if any argument matched more than one parameter
* that were mutually exclusive */
bool any_conflict() const noexcept {
return std::any_of(arg2param_.begin(), arg2param_.end(),
[](const arg_mapping& a){ return a.conflict(); });
}
/** @brief returns if any parameter matched repeatedly although
* it was not allowed to */
bool any_bad_repeat() const noexcept {
return std::any_of(arg2param_.begin(), arg2param_.end(),
[](const arg_mapping& a){ return a.bad_repeat(); });
}
/** @brief returns true if any parsing error / violation of the
* command line interface definition occured */
bool any_error() const noexcept {
return unmapped_args_count() > 0 || !missing().empty() ||
any_blocked() || any_conflict() || any_bad_repeat();
}
/** @brief returns true if no parsing error / violation of the
* command line interface definition occured */
explicit operator bool() const noexcept { return !any_error(); }
/** @brief access to range of missing parameter match events */
const missing_events& missing() const noexcept { return missing_; }
/** @brief returns non-mutating iterator to position of
* first argument -> parameter mapping */
iterator begin() const noexcept { return arg2param_.begin(); }
/** @brief returns non-mutating iterator to position one past the
* last argument -> parameter mapping */
iterator end() const noexcept { return arg2param_.end(); }
private:
//-----------------------------------------------------
arg_mappings arg2param_;
missing_events missing_;
};
namespace detail {
namespace {
/*************************************************************************//**
*
* @brief correct some common problems
* does not - and MUST NOT - change the number of arguments
* (no insertion, no deletion)
*
*****************************************************************************/
void sanitize_args(arg_list& args)
{
//e.g. {"-o12", ".34"} -> {"-o", "12.34"}
if(args.empty()) return;
for(auto i = begin(args)+1; i != end(args); ++i) {
if(i != begin(args) && i->size() > 1 &&
i->find('.') == 0 && std::isdigit((*i)[1]) )
{
//find trailing digits in previous arg
using std::prev;
auto& prv = *prev(i);
auto fstDigit = std::find_if_not(prv.rbegin(), prv.rend(),
[](arg_string::value_type c){
return std::isdigit(c);
}).base();
//handle leading sign
if(fstDigit > prv.begin() &&
(*prev(fstDigit) == '+' || *prev(fstDigit) == '-'))
{
--fstDigit;
}
//prepend digits from previous arg
i->insert(begin(*i), fstDigit, end(prv));
//erase digits in previous arg
prv.erase(fstDigit, end(prv));
}
}
}
/*************************************************************************//**
*
* @brief executes actions based on a parsing result
*
*****************************************************************************/
void execute_actions(const parsing_result& res)
{
for(const auto& m : res) {
if(m.param()) {
const auto& param = *(m.param());
if(m.repeat() > 0) param.notify_repeated(m.index());
if(m.blocked()) param.notify_blocked(m.index());
if(m.conflict()) param.notify_conflict(m.index());
//main action
if(!m.any_error()) param.execute_actions(m.arg());
}
}
for(auto m : res.missing()) {
if(m.param()) m.param()->notify_missing(m.after_index());
}
}
/*************************************************************************//**
*
* @brief parses input args
*
*****************************************************************************/
static parsing_result
parse_args(const arg_list& args, const group& cli,
arg_index offset = 0)
{
//parse args and store unrecognized arg indices
parser parse{cli, offset};
for(const auto& arg : args) {
parse(arg);
if(!parse.valid()) break;
}
return parsing_result{parse.args(), parse.missed()};
}
/*************************************************************************//**
*
* @brief parses input args & executes actions
*
*****************************************************************************/
static parsing_result
parse_and_execute(const arg_list& args, const group& cli,
arg_index offset = 0)
{
auto result = parse_args(args, cli, offset);
execute_actions(result);
return result;
}
} //anonymous namespace
} // namespace detail
/*************************************************************************//**
*
* @brief parses vector of arg strings and executes actions
*
*****************************************************************************/
inline parsing_result
parse(arg_list args, const group& cli)
{
detail::sanitize_args(args);
return detail::parse_and_execute(args, cli);
}
/*************************************************************************//**
*
* @brief parses initializer_list of C-style arg strings and executes actions
*
*****************************************************************************/
inline parsing_result
parse(std::initializer_list<const char*> arglist, const group& cli)
{
arg_list args;
args.reserve(arglist.size());
for(auto a : arglist) {
if(std::strlen(a) > 0) args.push_back(a);
}
return parse(std::move(args), cli);
}
/*************************************************************************//**
*
* @brief parses range of arg strings and executes actions
*
*****************************************************************************/
template<class InputIterator>
inline parsing_result
parse(InputIterator first, InputIterator last, const group& cli)
{
return parse(arg_list(first,last), cli);
}
/*************************************************************************//**
*
* @brief parses the standard array of command line arguments; omits argv[0]
*
*****************************************************************************/
inline parsing_result
parse(const int argc, char* argv[], const group& cli, arg_index offset = 1)
{
arg_list args;
if(offset < argc) args.assign(argv+offset, argv+argc);
detail::sanitize_args(args);
return detail::parse_and_execute(args, cli, offset);
}
/*************************************************************************//**
*
* @brief filter predicate for parameters and groups;
* Can be used to limit documentation generation to parameter subsets.
*
*****************************************************************************/
class param_filter
{
public:
/** @brief only allow parameters with given prefix */
param_filter& prefix(const arg_string& p) noexcept {
prefix_ = p; return *this;
}
/** @brief only allow parameters with given prefix */
param_filter& prefix(arg_string&& p) noexcept {
prefix_ = std::move(p); return *this;
}
const arg_string& prefix() const noexcept { return prefix_; }
/** @brief only allow parameters with given requirement status */
param_filter& required(tri t) noexcept { required_ = t; return *this; }
tri required() const noexcept { return required_; }
/** @brief only allow parameters with given blocking status */
param_filter& blocking(tri t) noexcept { blocking_ = t; return *this; }
tri blocking() const noexcept { return blocking_; }
/** @brief only allow parameters with given repeatable status */
param_filter& repeatable(tri t) noexcept { repeatable_ = t; return *this; }
tri repeatable() const noexcept { return repeatable_; }
/** @brief only allow parameters with given docstring status */
param_filter& has_doc(tri t) noexcept { hasDoc_ = t; return *this; }
tri has_doc() const noexcept { return hasDoc_; }
/** @brief returns true, if parameter satisfies all filters */
bool operator() (const parameter& p) const noexcept {
if(!prefix_.empty()) {
if(!std::any_of(p.flags().begin(), p.flags().end(),
[&](const arg_string& flag){
return str::has_prefix(flag, prefix_);
})) return false;
}
if(required() != p.required()) return false;
if(blocking() != p.blocking()) return false;
if(repeatable() != p.repeatable()) return false;
if(has_doc() != !p.doc().empty()) return false;
return true;
}
private:
arg_string prefix_;
tri required_ = tri::either;
tri blocking_ = tri::either;
tri repeatable_ = tri::either;
tri exclusive_ = tri::either;
tri hasDoc_ = tri::yes;
};
/*************************************************************************//**
*
* @brief documentation formatting options
*
*****************************************************************************/
class doc_formatting
{
public:
using string = doc_string;
/** @brief determines column where documentation printing starts */
doc_formatting& start_column(int col) { startCol_ = col; return *this; }
int start_column() const noexcept { return startCol_; }
/** @brief determines column where docstrings start */
doc_formatting& doc_column(int col) { docCol_ = col; return *this; }
int doc_column() const noexcept { return docCol_; }
/** @brief determines indent of documentation lines
* for children of a documented group */
doc_formatting& indent_size(int indent) { indentSize_ = indent; return *this; }
int indent_size() const noexcept { return indentSize_; }
/** @brief determines string to be used
* if a parameter has no flags and no label */
doc_formatting& empty_label(const string& label) {
emptyLabel_ = label;
return *this;
}
const string& empty_label() const noexcept { return emptyLabel_; }
/** @brief determines string for separating parameters */
doc_formatting& param_separator(const string& sep) {
paramSep_ = sep;
return *this;
}
const string& param_separator() const noexcept { return paramSep_; }
/** @brief determines string for separating groups (in usage lines) */
doc_formatting& group_separator(const string& sep) {
groupSep_ = sep;
return *this;
}
const string& group_separator() const noexcept { return groupSep_; }
/** @brief determines string for separating alternative parameters */
doc_formatting& alternative_param_separator(const string& sep) {
altParamSep_ = sep;
return *this;
}
const string& alternative_param_separator() const noexcept { return altParamSep_; }
/** @brief determines string for separating alternative groups */
doc_formatting& alternative_group_separator(const string& sep) {
altGroupSep_ = sep;
return *this;
}
const string& alternative_group_separator() const noexcept { return altGroupSep_; }
/** @brief determines string for separating flags of the same parameter */
doc_formatting& flag_separator(const string& sep) {
flagSep_ = sep;
return *this;
}
const string& flag_separator() const noexcept { return flagSep_; }
/** @brief determnines strings surrounding parameter labels */
doc_formatting&
surround_labels(const string& prefix, const string& postfix) {
labelPre_ = prefix;
labelPst_ = postfix;
return *this;
}
const string& label_prefix() const noexcept { return labelPre_; }
const string& label_postfix() const noexcept { return labelPst_; }
/** @brief determnines strings surrounding optional parameters/groups */
doc_formatting&
surround_optional(const string& prefix, const string& postfix) {
optionPre_ = prefix;
optionPst_ = postfix;
return *this;
}
const string& optional_prefix() const noexcept { return optionPre_; }
const string& optional_postfix() const noexcept { return optionPst_; }
/** @brief determnines strings surrounding repeatable parameters/groups */
doc_formatting&
surround_repeat(const string& prefix, const string& postfix) {
repeatPre_ = prefix;
repeatPst_ = postfix;
return *this;
}
const string& repeat_prefix() const noexcept { return repeatPre_; }
const string& repeat_postfix() const noexcept { return repeatPst_; }
/** @brief determnines strings surrounding exclusive groups */
doc_formatting&
surround_alternatives(const string& prefix, const string& postfix) {
alternPre_ = prefix;
alternPst_ = postfix;
return *this;
}
const string& alternatives_prefix() const noexcept { return alternPre_; }
const string& alternatives_postfix() const noexcept { return alternPst_; }
/** @brief determnines strings surrounding alternative flags */
doc_formatting&
surround_alternative_flags(const string& prefix, const string& postfix) {
alternFlagPre_ = prefix;
alternFlagPst_ = postfix;
return *this;
}
const string& alternative_flags_prefix() const noexcept { return alternFlagPre_; }
const string& alternative_flags_postfix() const noexcept { return alternFlagPst_; }
/** @brief determnines strings surrounding non-exclusive groups */
doc_formatting&
surround_group(const string& prefix, const string& postfix) {
groupPre_ = prefix;
groupPst_ = postfix;
return *this;
}
const string& group_prefix() const noexcept { return groupPre_; }
const string& group_postfix() const noexcept { return groupPst_; }
/** @brief determnines strings surrounding joinable groups */
doc_formatting&
surround_joinable(const string& prefix, const string& postfix) {
joinablePre_ = prefix;
joinablePst_ = postfix;
return *this;
}
const string& joinable_prefix() const noexcept { return joinablePre_; }
const string& joinable_postfix() const noexcept { return joinablePst_; }
/** @brief determines maximum number of flags per parameter to be printed
* in detailed parameter documentation lines */
doc_formatting& max_flags_per_param_in_doc(int max) {
maxAltInDocs_ = max > 0 ? max : 0;
return *this;
}
int max_flags_per_param_in_doc() const noexcept { return maxAltInDocs_; }
/** @brief determines maximum number of flags per parameter to be printed
* in usage lines */
doc_formatting& max_flags_per_param_in_usage(int max) {
maxAltInUsage_ = max > 0 ? max : 0;
return *this;
}
int max_flags_per_param_in_usage() const noexcept { return maxAltInUsage_; }
/** @brief determines number of empty rows after one single-line
* documentation entry */
doc_formatting& line_spacing(int lines) {
lineSpc_ = lines > 0 ? lines : 0;
return *this;
}
int line_spacing() const noexcept { return lineSpc_; }
/** @brief determines number of empty rows before and after a paragraph;
* a paragraph is defined by a documented group or if
* a parameter documentation entry used more than one line */
doc_formatting& paragraph_spacing(int lines) {
paragraphSpc_ = lines > 0 ? lines : 0;
return *this;
}
int paragraph_spacing() const noexcept { return paragraphSpc_; }
/** @brief determines if alternative flags with a common prefix should
* be printed in a merged fashion */
doc_formatting& merge_alternative_flags_with_common_prefix(bool yes = true) {
mergeAltCommonPfx_ = yes;
return *this;
}
bool merge_alternative_flags_with_common_prefix() const noexcept {
return mergeAltCommonPfx_;
}
/** @brief determines if joinable flags with a common prefix should
* be printed in a merged fashion */
doc_formatting& merge_joinable_with_common_prefix(bool yes = true) {
mergeJoinableCommonPfx_ = yes;
return *this;
}
bool merge_joinable_with_common_prefix() const noexcept {
return mergeJoinableCommonPfx_;
}
/** @brief determines if children of exclusive groups should be printed
* on individual lines if the exceed 'alternatives_min_split_size'
*/
doc_formatting& split_alternatives(bool yes = true) {
splitTopAlt_ = yes;
return *this;
}
bool split_alternatives() const noexcept {
return splitTopAlt_;
}
/** @brief determines how many children exclusive groups can have before
* their children are printed on individual usage lines */
doc_formatting& alternatives_min_split_size(int size) {
groupSplitSize_ = size > 0 ? size : 0;
return *this;
}
int alternatives_min_split_size() const noexcept { return groupSplitSize_; }
private:
string paramSep_ = string(" ");
string groupSep_ = string(" ");
string altParamSep_ = string("|");
string altGroupSep_ = string(" | ");
string flagSep_ = string(", ");
string labelPre_ = string("<");
string labelPst_ = string(">");
string optionPre_ = string("[");
string optionPst_ = string("]");
string repeatPre_ = string("");
string repeatPst_ = string("...");
string groupPre_ = string("(");
string groupPst_ = string(")");
string alternPre_ = string("(");
string alternPst_ = string(")");
string alternFlagPre_ = string("");
string alternFlagPst_ = string("");
string joinablePre_ = string("(");
string joinablePst_ = string(")");
string emptyLabel_ = string("");
int startCol_ = 8;
int docCol_ = 20;
int indentSize_ = 4;
int maxAltInUsage_ = 1;
int maxAltInDocs_ = 32;
int lineSpc_ = 0;
int paragraphSpc_ = 1;
int groupSplitSize_ = 3;
bool splitTopAlt_ = true;
bool mergeAltCommonPfx_ = false;
bool mergeJoinableCommonPfx_ = true;
};
/*************************************************************************//**
*
* @brief generates usage lines
*
* @details lazily evaluated
*
*****************************************************************************/
class usage_lines
{
public:
using string = doc_string;
usage_lines(const group& cli, string prefix = "",
const doc_formatting& fmt = doc_formatting{})
:
cli_(cli), fmt_(fmt), prefix_(std::move(prefix))
{
if(!prefix_.empty()) prefix_ += ' ';
if(fmt_.start_column() > 0) prefix_.insert(0, fmt.start_column(), ' ');
}
usage_lines(const group& cli, const doc_formatting& fmt):
usage_lines(cli, "", fmt)
{}
usage_lines& ommit_outermost_group_surrounders(bool yes) {
ommitOutermostSurrounders_ = yes;
return *this;
}
bool ommit_outermost_group_surrounders() const {
return ommitOutermostSurrounders_;
}
template<class OStream>
inline friend OStream& operator << (OStream& os, const usage_lines& p) {
p.print_usage(os);
return os;
}
string str() const {
std::ostringstream os; os << *this; return os.str();
}
private:
const group& cli_;
doc_formatting fmt_;
string prefix_;
bool ommitOutermostSurrounders_ = false;
//-----------------------------------------------------
struct context {
group::depth_first_traverser pos;
std::stack<string> separators;
std::stack<string> postfixes;
int level = 0;
const group* outermost = nullptr;
bool linestart = false;
bool useOutermost = true;
int line = 0;
bool is_singleton() const noexcept {
return linestart && pos.is_last_in_path();
}
bool is_alternative() const noexcept {
return pos.parent().exclusive();
}
};
/***************************************************************//**
*
* @brief writes usage text for command line parameters
*
*******************************************************************/
template<class OStream>
void print_usage(OStream& os) const
{
context cur;
cur.pos = cli_.begin_dfs();
cur.linestart = true;
cur.level = cur.pos.level();
cur.outermost = &cli_;
print_usage(os, cur, prefix_);
}
/***************************************************************//**
*
* @brief writes usage text for command line parameters
*
* @param prefix all that goes in front of current things to print
*
*******************************************************************/
template<class OStream>
void print_usage(OStream& os, context cur, string prefix) const
{
if(!cur.pos) return;
std::ostringstream buf;
if(cur.linestart) buf << prefix;
const auto initPos = buf.tellp();
cur.level = cur.pos.level();
if(cur.useOutermost) {
//we cannot start outside of the outermost group
//so we have to treat it separately
start_group(buf, cur.pos.parent(), cur);
if(!cur.pos) {
os << buf.str();
return;
}
}
else {
//don't visit siblings of starter node
cur.pos.skip_siblings();
}
check_end_group(buf, cur);
do {
if(buf.tellp() > initPos) cur.linestart = false;
if(!cur.linestart && !cur.pos.is_first_in_group()) {
buf << cur.separators.top();
}
if(cur.pos->is_group()) {
start_group(buf, cur.pos->as_group(), cur);
if(!cur.pos) {
os << buf.str();
return;
}
}
else {
buf << param_label(cur.pos->as_param(), cur);
++cur.pos;
}
check_end_group(buf, cur);
} while(cur.pos);
os << buf.str();
}
/***************************************************************//**
*
* @brief handles pattern group surrounders and separators
* and alternative splitting
*
*******************************************************************/
void start_group(std::ostringstream& os,
const group& group, context& cur) const
{
//does cur.pos already point to a member or to group itself?
//needed for special treatment of outermost group
const bool alreadyInside = &(cur.pos.parent()) == &group;
auto lbl = joined_label(group, cur);
if(!lbl.empty()) {
os << lbl;
cur.linestart = false;
//skip over entire group as its label has already been created
if(alreadyInside) {
cur.pos.next_after_siblings();
} else {
cur.pos.next_sibling();
}
}
else {
const bool splitAlternatives = group.exclusive() &&
fmt_.split_alternatives() &&
std::any_of(group.begin(), group.end(),
[this](const pattern& p) {
return int(p.param_count()) >= fmt_.alternatives_min_split_size();
});
if(splitAlternatives) {
cur.postfixes.push("");
cur.separators.push("");
//recursively print alternative paths in decision-DAG
//enter group?
if(!alreadyInside) ++cur.pos;
cur.linestart = true;
cur.useOutermost = false;
auto pfx = os.str();
os.str("");
//print paths in DAG starting at each group member
for(std::size_t i = 0; i < group.size(); ++i) {
std::stringstream buf;
cur.outermost = cur.pos->is_group() ? &(cur.pos->as_group()) : nullptr;
print_usage(buf, cur, pfx);
if(buf.tellp() > int(pfx.size())) {
os << buf.str();
if(i < group.size()-1) {
if(cur.line > 0) {
os << string(fmt_.line_spacing(), '\n');
}
++cur.line;
os << '\n';
}
}
cur.pos.next_sibling(); //do not descend into memebers
}
cur.pos.invalidate(); //signal end-of-path
return;
}
else {
//pre & postfixes, separators
auto surround = group_surrounders(group, cur);
os << surround.first;
cur.postfixes.push(std::move(surround.second));
cur.separators.push(group_separator(group, fmt_));
//descend into group?
if(!alreadyInside) ++cur.pos;
}
}
cur.level = cur.pos.level();
}
/***************************************************************//**
*
*******************************************************************/
void check_end_group(std::ostringstream& os, context& cur) const
{
for(; cur.level > cur.pos.level(); --cur.level) {
os << cur.postfixes.top();
cur.postfixes.pop();
cur.separators.pop();
}
cur.level = cur.pos.level();
}
/***************************************************************//**
*
* @brief makes usage label for one command line parameter
*
*******************************************************************/
string param_label(const parameter& p, const context& cur) const
{
const auto& parent = cur.pos.parent();
const bool startsOptionalSequence =
parent.size() > 1 && p.blocking() && cur.pos.is_first_in_group();
const bool outermost =
ommitOutermostSurrounders_ && cur.outermost == &parent;
const bool showopt = !cur.is_alternative() && !p.required()
&& !startsOptionalSequence && !outermost;
const bool showrep = p.repeatable() && !outermost;
string lbl;
if(showrep) lbl += fmt_.repeat_prefix();
if(showopt) lbl += fmt_.optional_prefix();
const auto& flags = p.flags();
if(!flags.empty()) {
const int n = std::min(fmt_.max_flags_per_param_in_usage(),
int(flags.size()));
const bool surrAlt = n > 1 && !showopt && !cur.is_singleton();
if(surrAlt) lbl += fmt_.alternative_flags_prefix();
bool sep = false;
for(int i = 0; i < n; ++i) {
if(sep) {
if(cur.is_singleton())
lbl += fmt_.alternative_group_separator();
else
lbl += fmt_.flag_separator();
}
lbl += flags[i];
sep = true;
}
if(surrAlt) lbl += fmt_.alternative_flags_postfix();
}
else {
if(!p.label().empty()) {
lbl += fmt_.label_prefix()
+ p.label()
+ fmt_.label_postfix();
} else if(!fmt_.empty_label().empty()) {
lbl += fmt_.label_prefix()
+ fmt_.empty_label()
+ fmt_.label_postfix();
} else {
return "";
}
}
if(showopt) lbl += fmt_.optional_postfix();
if(showrep) lbl += fmt_.repeat_postfix();
return lbl;
}
/***************************************************************//**
*
* @brief prints flags in one group in a merged fashion
*
*******************************************************************/
string joined_label(const group& g, const context& cur) const
{
if(!fmt_.merge_alternative_flags_with_common_prefix() &&
!fmt_.merge_joinable_with_common_prefix()) return "";
const bool flagsonly = std::all_of(g.begin(), g.end(),
[](const pattern& p){
return p.is_param() && !p.as_param().flags().empty();
});
if(!flagsonly) return "";
const bool showOpt = g.all_optional() &&
!(ommitOutermostSurrounders_ && cur.outermost == &g);
auto pfx = g.common_flag_prefix();
if(pfx.empty()) return "";
const auto n = pfx.size();
if(g.exclusive() &&
fmt_.merge_alternative_flags_with_common_prefix())
{
string lbl;
if(showOpt) lbl += fmt_.optional_prefix();
lbl += pfx + fmt_.alternatives_prefix();
bool first = true;
for(const auto& p : g) {
if(p.is_param()) {
if(first)
first = false;
else
lbl += fmt_.alternative_param_separator();
lbl += p.as_param().flags().front().substr(n);
}
}
lbl += fmt_.alternatives_postfix();
if(showOpt) lbl += fmt_.optional_postfix();
return lbl;
}
//no alternatives, but joinable flags
else if(g.joinable() &&
fmt_.merge_joinable_with_common_prefix())
{
const bool allSingleChar = std::all_of(g.begin(), g.end(),
[&](const pattern& p){
return p.is_param() &&
p.as_param().flags().front().substr(n).size() == 1;
});
if(allSingleChar) {
string lbl;
if(showOpt) lbl += fmt_.optional_prefix();
lbl += pfx;
for(const auto& p : g) {
if(p.is_param())
lbl += p.as_param().flags().front().substr(n);
}
if(showOpt) lbl += fmt_.optional_postfix();
return lbl;
}
}
return "";
}
/***************************************************************//**
*
* @return symbols with which to surround a group
*
*******************************************************************/
std::pair<string,string>
group_surrounders(const group& group, const context& cur) const
{
string prefix;
string postfix;
const bool isOutermost = &group == cur.outermost;
if(isOutermost && ommitOutermostSurrounders_)
return {string{}, string{}};
if(group.exclusive()) {
if(group.all_optional()) {
prefix = fmt_.optional_prefix();
postfix = fmt_.optional_postfix();
if(group.all_flagless()) {
prefix += fmt_.label_prefix();
postfix = fmt_.label_prefix() + postfix;
}
} else if(group.all_flagless()) {
prefix = fmt_.label_prefix();
postfix = fmt_.label_postfix();
} else if(!cur.is_singleton() || !isOutermost) {
prefix = fmt_.alternatives_prefix();
postfix = fmt_.alternatives_postfix();
}
}
else if(group.size() > 1 &&
group.front().blocking() && !group.front().required())
{
prefix = fmt_.optional_prefix();
postfix = fmt_.optional_postfix();
}
else if(group.size() > 1 && cur.is_alternative() &&
&group != cur.outermost)
{
prefix = fmt_.group_prefix();
postfix = fmt_.group_postfix();
}
else if(!group.exclusive() &&
group.joinable() && !cur.linestart)
{
prefix = fmt_.joinable_prefix();
postfix = fmt_.joinable_postfix();
}
if(group.repeatable()) {
if(prefix.empty()) prefix = fmt_.group_prefix();
prefix = fmt_.repeat_prefix() + prefix;
if(postfix.empty()) postfix = fmt_.group_postfix();
postfix += fmt_.repeat_postfix();
}
return {std::move(prefix), std::move(postfix)};
}
/***************************************************************//**
*
* @return symbol that separates members of a group
*
*******************************************************************/
static string
group_separator(const group& group, const doc_formatting& fmt)
{
const bool only1ParamPerMember = std::all_of(group.begin(), group.end(),
[](const pattern& p) { return p.param_count() < 2; });
if(only1ParamPerMember) {
if(group.exclusive()) {
return fmt.alternative_param_separator();
} else {
return fmt.param_separator();
}
}
else { //there is at least one large group inside
if(group.exclusive()) {
return fmt.alternative_group_separator();
} else {
return fmt.group_separator();
}
}
}
};
/*************************************************************************//**
*
* @brief generates parameter and group documentation from docstrings
*
* @details lazily evaluated
*
*****************************************************************************/
class documentation
{
public:
using string = doc_string;
documentation(const group& cli,
const doc_formatting& fmt = doc_formatting{},
const param_filter& filter = param_filter{})
:
cli_(cli), fmt_{fmt}, usgFmt_{fmt}, filter_{filter}
{
//necessary, because we re-use "usage_lines" to generate
//labels for documented groups
usgFmt_.max_flags_per_param_in_usage(
usgFmt_.max_flags_per_param_in_doc());
}
documentation(const group& cli,
const param_filter& filter,
const doc_formatting& fmt = doc_formatting{})
:
documentation(cli, fmt, filter)
{}
template<class OStream>
inline friend OStream& operator << (OStream& os, const documentation& p) {
printed prn = printed::nothing;
p.print_doc(os, p.cli_, prn);
return os;
}
string str() const {
std::ostringstream os; os << *this; return os.str();
}
private:
using dfs_traverser = group::depth_first_traverser;
enum class printed { nothing, line, paragraph };
const group& cli_;
doc_formatting fmt_;
doc_formatting usgFmt_;
param_filter filter_;
/***************************************************************//**
*
* @brief writes full documentation text for command line parameters
*
*******************************************************************/
template<class OStream>
void print_doc(OStream& os, const group& cli,
printed& sofar,
int indentLvl = 0) const
{
if(cli.empty()) return;
//if group itself doesn't have docstring
if(cli.doc().empty()) {
for(const auto& p : cli) {
print_doc(os, p, sofar, indentLvl);
}
}
else { //group itself does have docstring
bool anyDocInside = std::any_of(cli.begin(), cli.end(),
[](const pattern& p){ return !p.doc().empty(); });
if(anyDocInside) { //group docstring as title, then child entries
if(sofar != printed::nothing) {
os << string(fmt_.paragraph_spacing() + 1, '\n');
}
auto indent = string(fmt_.start_column(), ' ');
if(indentLvl > 0) indent += string(fmt_.indent_size() * indentLvl, ' ');
os << indent << cli.doc() << '\n';
sofar = printed::nothing;
for(const auto& p : cli) {
print_doc(os, p, sofar, indentLvl + 1);
}
sofar = printed::paragraph;
}
else { //group label first then group docstring
auto lbl = usage_lines(cli, usgFmt_)
.ommit_outermost_group_surrounders(true).str();
str::trim(lbl);
print_entry(os, lbl, cli.doc(), fmt_, sofar, indentLvl);
}
}
}
/***************************************************************//**
*
* @brief writes documentation text for one group or parameter
*
*******************************************************************/
template<class OStream>
void print_doc(OStream& os, const pattern& ptrn,
printed& sofar, int indentLvl) const
{
if(ptrn.is_group()) {
print_doc(os, ptrn.as_group(), sofar, indentLvl);
}
else {
const auto& p = ptrn.as_param();
if(!filter_(p)) return;
print_entry(os, param_label(p, fmt_), p.doc(), fmt_, sofar, indentLvl);
}
}
/*********************************************************************//**
*
* @brief prints one entry = label + docstring
*
************************************************************************/
template<class OStream>
static void
print_entry(OStream& os,
const string& label, const string& docstr,
const doc_formatting& fmt, printed& sofar, int indentLvl)
{
if(label.empty()) return;
auto indent = string(fmt.start_column(), ' ');
if(indentLvl > 0) indent += string(fmt.indent_size() * indentLvl, ' ');
const auto len = int(indent.size() + label.size());
const bool oneline = len < fmt.doc_column();
if(oneline) {
if(sofar == printed::line)
os << string(fmt.line_spacing() + 1, '\n');
else if(sofar == printed::paragraph)
os << string(fmt.paragraph_spacing() + 1, '\n');
}
else if(sofar != printed::nothing) {
os << string(fmt.paragraph_spacing() + 1, '\n');
}
sofar = oneline ? printed::line : printed::paragraph;
os << indent << label;
if(!docstr.empty()) {
if(oneline) {
os << string(fmt.doc_column() - len, ' ');
} else {
os << '\n' << string(fmt.doc_column(), ' ');
}
os << docstr;
}
}
/*********************************************************************//**
*
* @brief makes label for one parameter
*
************************************************************************/
static doc_string
param_label(const parameter& param, const doc_formatting& fmt)
{
doc_string lbl;
if(param.repeatable()) lbl += fmt.repeat_prefix();
const auto& flags = param.flags();
if(!flags.empty()) {
lbl += flags[0];
const int n = std::min(fmt.max_flags_per_param_in_doc(),
int(flags.size()));
for(int i = 1; i < n; ++i) {
lbl += fmt.flag_separator() + flags[i];
}
}
else if(!param.label().empty() || !fmt.empty_label().empty()) {
lbl += fmt.label_prefix();
if(!param.label().empty()) {
lbl += param.label();
} else {
lbl += fmt.empty_label();
}
lbl += fmt.label_postfix();
}
if(param.repeatable()) lbl += fmt.repeat_postfix();
return lbl;
}
};
/*************************************************************************//**
*
* @brief stores strings for man page sections
*
*****************************************************************************/
class man_page
{
public:
//---------------------------------------------------------------
using string = doc_string;
//---------------------------------------------------------------
/** @brief man page section */
class section {
public:
using string = doc_string;
section(string stitle, string scontent):
title_{std::move(stitle)}, content_{std::move(scontent)}
{}
const string& title() const noexcept { return title_; }
const string& content() const noexcept { return content_; }
private:
string title_;
string content_;
};
private:
using section_store = std::vector<section>;
public:
//---------------------------------------------------------------
using value_type = section;
using const_iterator = section_store::const_iterator;
using size_type = section_store::size_type;
//---------------------------------------------------------------
man_page&
append_section(string title, string content)
{
sections_.emplace_back(std::move(title), std::move(content));
return *this;
}
//-----------------------------------------------------
man_page&
prepend_section(string title, string content)
{
sections_.emplace(sections_.begin(),
std::move(title), std::move(content));
return *this;
}
//---------------------------------------------------------------
const section& operator [] (size_type index) const noexcept {
return sections_[index];
}
//---------------------------------------------------------------
size_type size() const noexcept { return sections_.size(); }
bool empty() const noexcept { return sections_.empty(); }
//---------------------------------------------------------------
const_iterator begin() const noexcept { return sections_.begin(); }
const_iterator end() const noexcept { return sections_.end(); }
//---------------------------------------------------------------
man_page& program_name(const string& n) {
progName_ = n;
return *this;
}
man_page& program_name(string&& n) {
progName_ = std::move(n);
return *this;
}
const string& program_name() const noexcept {
return progName_;
}
//---------------------------------------------------------------
man_page& section_row_spacing(int rows) {
sectionSpc_ = rows > 0 ? rows : 0;
return *this;
}
int section_row_spacing() const noexcept { return sectionSpc_; }
private:
int sectionSpc_ = 1;
section_store sections_;
string progName_;
};
/*************************************************************************//**
*
* @brief generates man sections from command line parameters
* with sections "synopsis" and "options"
*
*****************************************************************************/
inline man_page
make_man_page(const group& cli,
doc_string progname = "",
const doc_formatting& fmt = doc_formatting{})
{
man_page man;
man.append_section("SYNOPSIS", usage_lines(cli,progname,fmt).str());
man.append_section("OPTIONS", documentation(cli,fmt).str());
return man;
}
/*************************************************************************//**
*
* @brief generates man page based on command line parameters
*
*****************************************************************************/
template<class OStream>
OStream&
operator << (OStream& os, const man_page& man)
{
bool first = true;
const auto secSpc = doc_string(man.section_row_spacing() + 1, '\n');
for(const auto& section : man) {
if(!section.content().empty()) {
if(first) first = false; else os << secSpc;
if(!section.title().empty()) os << section.title() << '\n';
os << section.content();
}
}
os << '\n';
return os;
}
/*************************************************************************//**
*
* @brief printing methods for debugging command line interfaces
*
*****************************************************************************/
namespace debug {
/*************************************************************************//**
*
* @brief prints first flag or value label of a parameter
*
*****************************************************************************/
inline doc_string doc_label(const parameter& p)
{
if(!p.flags().empty()) return p.flags().front();
if(!p.label().empty()) return p.label();
return doc_string{"<?>"};
}
inline doc_string doc_label(const group&)
{
return "<group>";
}
inline doc_string doc_label(const pattern& p)
{
return p.is_group() ? doc_label(p.as_group()) : doc_label(p.as_param());
}
/*************************************************************************//**
*
* @brief prints parsing result
*
*****************************************************************************/
template<class OStream>
void print(OStream& os, const parsing_result& result)
{
for(const auto& m : result) {
os << "#" << m.index() << " " << m.arg() << " -> ";
auto p = m.param();
if(p) {
os << doc_label(*p) << " \t";
if(m.repeat() > 0) {
os << (m.bad_repeat() ? "[bad repeat " : "[repeat ")
<< m.repeat() << "]";
}
if(m.blocked()) os << " [blocked]";
if(m.conflict()) os << " [conflict]";
os << '\n';
}
else {
os << " [unmapped]\n";
}
}
for(const auto& m : result.missing()) {
auto p = m.param();
if(p) {
os << doc_label(*p) << " \t";
os << " [missing after " << m.after_index() << "]\n";
}
}
}
/*************************************************************************//**
*
* @brief prints parameter label and some properties
*
*****************************************************************************/
template<class OStream>
void print(OStream& os, const parameter& p)
{
if(p.blocking()) os << '!';
if(!p.required()) os << '[';
os << doc_label(p);
if(p.repeatable()) os << "...";
if(!p.required()) os << "]";
}
//-------------------------------------------------------------------
template<class OStream>
void print(OStream& os, const group& g, int level = 0);
/*************************************************************************//**
*
* @brief prints group or parameter; uses indentation
*
*****************************************************************************/
template<class OStream>
void print(OStream& os, const pattern& param, int level = 0)
{
if(param.is_group()) {
print(os, param.as_group(), level);
}
else {
os << doc_string(4*level, ' ');
print(os, param.as_param());
}
}
/*************************************************************************//**
*
* @brief prints group and its contents; uses indentation
*
*****************************************************************************/
template<class OStream>
void print(OStream& os, const group& g, int level)
{
auto indent = doc_string(4*level, ' ');
os << indent;
if(g.blocking()) os << '!';
if(g.joinable()) os << 'J';
os << (g.exclusive() ? "(|\n" : "(\n");
for(const auto& p : g) {
print(os, p, level+1);
}
os << '\n' << indent << (g.exclusive() ? "|)" : ")");
if(g.repeatable()) os << "...";
os << '\n';
}
} // namespace debug
} //namespace clipp
#endif
|