Skip to content
Snippets Groups Projects
clipp.h 188 KiB
Newer Older
/*****************************************************************************
 *
 * CLIPP - command line interfaces for modern C++
 *
 * released under MIT license
 *
 * (c) 2017 André Müller; foss@andremueller-online.de
 *
 *****************************************************************************/

#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))
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
{};

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;

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) {
        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) {
        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 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>
{
    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}
    {}

    /** @brief makes "flag" parameter */
    template<class... Strings>
    explicit
    parameter(arg_string str, Strings&&... strs):
        flags_{},
        matcher_{predicate_adapter{match::none}},
        label_{}, required_{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}
    {
        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}
    {}

    /** @brief makes "value" parameter with custom match function
     *         (= partial matcher)
     */
    explicit
    parameter(match_function filter):
        flags_{},
        matcher_{std::move(filter)},
        label_{}, required_{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 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;
};




/*************************************************************************//**
 *
 * @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;
Loading
Loading full blame...