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
|
\input texinfo @c -*-texinfo-*-
@c %**start of header
@setfilename genparse.info
@settitle Genparse
@c For double-sided printing, uncomment:
@c @setchapternewpage odd
@c %**end of header
@include version.texi
@iftex
@finalout
@end iftex
@ifinfo
@format
INFO-DIR-SECTION Development
START-INFO-DIR-ENTRY
* Genparse: (genparse). Command line parser generator.
END-INFO-DIR-ENTRY
@end format
Genparse: command line parser generator, by Mike Borella and Michael Geng
This file documents the Genparse package for creating command line parser
generators in C, C++ and Java.
Copyright (C) 1997-2016, Mike Borella, Michael Geng
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.
@ignore
Permission is granted to process this file through TeX and print the
results, provided the printed document carries copying permission
notice identical to this one except for the removal of this paragraph
(this paragraph not being relevant to the printed manual).
@end ignore
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.
Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation approved
by the Author.
@end ifinfo
@titlepage
@title Genparse
@subtitle Command Line Parser Generator
@subtitle Edition @value{EDITION}, for Genparse version @value{VERSION}
@subtitle @value{UPDATED}
@author Mike Borella, Michael Geng
@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1997-2016, Mike Borella, Michael Geng
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.
Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation approved
by the Author.
@end titlepage
@c TABLE OF CONTENTS
@contents
@c Define an environment variable index.
@defcodeindex ev
@c Define an output variable index.
@defcodeindex ov
@c Define a CPP variable index.
@defcodeindex cv
@c Define a macro index that @@defmac doesn't write to.
@defcodeindex ma
@node Top, Introduction, (dir), (dir)
@comment node-name, next, previous, up
@ifinfo
This file documents the Genparse package for creating command line
parsing routines in C, C++ and Java using a simple descriptive file.
This is edition @value{EDITION}, for Genparse version @value{VERSION}.
@end ifinfo
@c The master menu, created with texinfo-master-menu, goes here.
@menu
* Introduction:: Overview of Genparse
* Making Genparse Files:: Step-by-Step Instructions for Writing Genparse Files
* Genparse Options::
* Genparse File Syntax::
* The Future::
* Some History::
* Index::
@end menu
@c CHAPTER
@node Introduction, Making Genparse Files, Top, Top
@chapter Introduction
The Genparse package allows the automated creation of command line
parsing routines, based on a command line option description file.
Given a target language, Genparse outputs a suitable parser. For
example, in C, a function is created that reads the command line
parameters and stores their values in a data structure. In C++ and
Java, a command line parsing class is created, with member functions
that return parameter values.
@cindex Genparse file
The goal of Genparse is to eliminate the effort required to write a
command line parser for every newly-developed program. Typically, these
parsers all follow a very similar format, with a series of calls to the
@code{getopt ()} or @code{getopt_long ()} library functions. Genparse
allows users to specify their program's command line options in a
concise text file (hereafter, a "Genparse File"). Genparse reads this
file, and produces the appropriate parsing routines in the user's
language of choice. Users may call the parser's functions from their
main code in order to obtain the values of the parameters.
In addition to providing a simple interface to the parameters, Genparse
also has the following features:
@itemize @bullet
@item
A default value may be provided for each parameter.
@item
Both short (@code{-o}) and long (@code{--option}) parameters are supported.
@item
For parameters that take numerical values, Genparse can make sure that
the input values fall within a given range.
@cindex Usage function
@item
A @code{usage ()} function is automatically created, which can be used to
describe a program's command line parameters. Genparse also allows a
description string to be associated with each parameter. These strings
will be displayed in the @code{usage ()} function.
@item
For C and C++ extra include files may be added to any command line parser.
@item
Each parameter can have a callback function associated with it.
Genparse will automatically create a skeleton for callback functions,
which the user can fill in. Also, global callback functions can be
specified.
@item
The generated parser is 100% GNU compatible because the parsing itself
is done by the GNU getopt_long function.
@item
The generated code is internationalizable (@xref{internationalize}.).
@end itemize
@cindex Limitations
Currently, we do not believe that Genparse has any significant
limitations. It cannot handle dependencies between different options,
but the user can write callback function to accomplish this task. A
virtually unlimited number of long command line options are available,
but only 52 single-character options can be used by a given program.
@cindex Contact info
Mail suggestions and bug reports for Genparse to
@email{mike@@borella.net}. The latest version of Genparse can always be
found at @uref{http://genparse.sourceforge.net}.
@c CHAPTER
@node Making Genparse Files, Genparse Options, Introduction, Top
@chapter Making Genparse Files
@cindex Genparse files, making
In this section we discuss how to write Genparse files and how to invoke
Genparse on these files. We take a pedagogical approach, walking through
a very simple example program and showing how Genparse can simplify
its development.
@menu
* A Simple Application::
* Adding Command Line Options::
* Simplifying Command Line Parsing with Genparse::
* Include Files and Callbacks::
* C++ Output::
* Java Output::
* Idiosyncrasies::
@end menu
@node A Simple Application, Adding Command Line Options, Making Genparse Files, Making Genparse Files
@section A Simple Application
Suppose that we want to write a C program that outputs a given text file
some number of times. This is a simple, and perhaps not terribly
useful program, but its simplicity will help illustrate the utility
of Genparse.
Our program, @command{mycopy1}, might look like this:
@example
/* mycopy1.c */
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
@{
int c, i, n;
FILE *fp;
n = atoi (argv[1]);
fp = fopen (argv[2],"r");
for (i = 0; i < n; i++)
@{
while ((c = fgetc (fp)) != EOF)
fputc (c, stdout);
rewind (fp);
@}
fclose (fp);
return 0;
@}
@end example
The user is expected to invoke @command{mycopy1} with two items on the
command line: an integer followed by a filename. The former is the
number of times that the latter should be displayed. While this program
accomplishes what we set out to do, it is not very robust nor user
friendly. For example, if the user specifies a negative integer, the
program does not display a warning or error message (in fact, it
displays nothing). If the user does not know what is expected on the
command line, how will he or she find this information out (assuming
that nice documentation, such as what you are now reading, does not
exist for @command{mycopy1}). Furthermore, wouldn't this program be
more flexible if there were a default number of iterations, the user
could specify the command line parameters in any order or omit some
altogether?
All of these issues, and perhaps others, can be addressed in a number of
ways. Traditionally, the author of @command{mycopy1} would publish the
command line format, typically in a @command{man} page, and write a
routine to pull the command line parameters out of the @code{argv}
array, assuming that the format was followed (not unlike what we've done
for @command{mycopy1}). However, as the number of command line
parameters increases, this task becomes much more difficult and
cumbersome.
@cindex getopt ()
With the introduction of the @code{getopt ()} and @code{getopt_long ()}
functions, now part of the GNU C Library, a great deal of the command
line parsing burden was lifted from programmers. The @code{getopt ()}
function takes in an @code{argv}-style command line and assumes that it
contains a series of command line options. An option is indicated with a
single character preceded by a dash - for example, @option{-o} or
@option{-Z}. These options may be followed by a command line parameter -
for example, @option{-o} or @option{-Z 3}. Using @code{getopt}
we could add an @option{-i} to allow the number of iterations to be
specified. The advantage to doing so is that it would no longer matter
where on the command line @option{-i} appears, and if @option{-i} does
not appear at all, we can assign a default number of iterations.
@cindex getopt_long ()
The @code{getopt_long ()} function extends @code{getopt ()}, by allowing
long options to coexist with single character options. Long options are
preceded by two dashes and may be more than one character long - for
example @option{--iterations}. Long options may also take parameters,
in the form @option{--option param} or @option{--option=param}.
@node Adding Command Line Options, Simplifying Command Line Parsing with Genparse, A Simple Application, Making Genparse Files
@section Adding Command Line Options
From the previous section's @command{mycopy1}, we will now add command
line option parsing with @code{getopt_long ()} to create
@command{mycopy2}. Along the way we'll add a small number of useful
features.
@example
/* mycopy2.c */
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
int main (int argc, char *argv[])
@{
int c, i;
FILE *fp;
extern char *optarg;
extern int optind;
int option_index = 0;
char ch;
int help, iterations;
int errflg = 0;
static struct option long_options[] =
@{
@{"help", no_argument, NULL, 'h'@},
@{"iterations", required_argument, NULL, 'i'@},
@{NULL, 0, NULL, 0@}
@};
help = 0;
iterations = 1;
while ((ch = getopt_long (argc, argv, "hi:", long_options,
&option_index)) != EOF)
@{
switch (ch)
@{
case 'h':
help = 1;
break;
case 'i':
iterations = atoi (optarg);
if (iterations < 0)
@{
fprintf (stderr, "error: iterations must be >= 0\n");
errflg ++;
@}
break;
default:
errflg++;
@}
@} /* while */
if (errflg || help)
@{
printf ("usage: %s [ -i ] <file>\n", argv[0]);
printf (" [ -h ] [ --help ] Print help screen \n");
printf (" [ -i ] [ --iterations ] Number of times to \
output <file>\n");
exit (1);
@}
if (optind >= argc)
fp = stdin;
else
fp = fopen (argv[optind],"r");
for (i = 0; i < iterations; i++)
@{
while ((c = fgetc (fp)) != EOF)
fputc (c, stdout);
rewind (fp);
@}
fclose (fp);
return 0;
@}
@end example
This program performs the same function as @command{mycopy1} but does so
in a more flexible and reliable fashion. Two command line options are
supported, @option{-h} and @option{-i}. When @option{-h}, or its long
form, @option{--help}, appears on the command line, all other options
are ignored and a usage message is displayed. The @option{-i} option
allows the user to specify the number of iterations, as discussed above.
It also has a long form, @option{--iterations}. The number of
iterations defaults to 1 if @option{-i} does not appear on the command
line, and the program prevents negative values from being specified with
@option{-i}.
The usage message is a useful way of summarizing a program's options
without needed a @command{man} or @command{info} page. There are three
ways that the usage message for @command{mycopy2} will be displayed:
@itemize @bullet
@item
If the @option{-h} or @option{--help} options appear on the command line.
@item
If an unknown option appears on the command line.
@item
If the @option{-i} option appears with a negative value.
@end itemize
@cindex Command line, rearranging
@cindex Optind
A nice feature of @code{getopt ()} and @code{getopt_long ()} is that they
will rearrange the command line within @code{argv} so that all
non-options follow all of the options@footnote{@code{argv[0]} is not
rearranged - it remains in its place.}. The external variable
@code{optind} is set to point to the first non-option in the re-arranged
@code{argv}. Thus, by comparing @code{optind} to @code{argc}, we can
determine whether or not an input file has been specified. If there is
no input file on the command line, we can redirect @command{mycopy2} to
use @emph{stdin}.
While @command{mycopy2} is an improvement over @command{mycopy1},
there are a number of drawbacks to using @code{getopt ()} in all
of your programs. The most obvious is time. In @command{mycopy2},
two-thirds (about 50 lines) of the code does the command line parsing,
and only two options are supported. If there we're 10 options, the
command line parsing code could easily reach 200 lines or more.
Additionally, since each option's parameter may need to be checked
for validity and assigned to a variable, this becomes a tedious
process that can be error prone.
Observing the source code for @code{mycopy2}, it becomes clear that,
like any repetitive task, the command line parsing code follows
a number of simple patterns. If these patterns can be abstracted and
generalized so that the user can indicate option use in a concise format,
most, if not all, of the parsing code can be automatically generated.
With this thought in mind, we turn our attention to Genparse.
@node Simplifying Command Line Parsing with Genparse, Include Files and Callbacks, Adding Command Line Options, Making Genparse Files
@section Simplifying Command Line Parsing with Genparse
Genparse automatically creates command line parsing code, not unlike
the code in @code{mycopy2.c}. It creates two or three files: a header
file, a parsing file, and an optional callback file. In this section,
we'll write a Genparse specification for our file copying program and
examine the parser that it creates.
Genparse runs on a simple input file, which we'll call a Genparse file.
In a Genparse file, each command line option is specified on one or more
lines. The following code is a Genparse file for @command{mycopy3}.
@cindex Genparse file, simple example
@example
@group
/* mycopy3.gp */
i / iterations int 1 [0...] "Number of times to output <file>."
"File should be text format!"
o / outfile string @{""@} "Output file name."
#usage_begin
usage: __PROGRAM_NAME__ __OPTIONS_SHORT__ file
Print a file for a number of times to stdout.
__GLOSSARY__
#usage_end
@end group
@end example
@noindent
The naming of this file follows the convention of all Genparse files
ending in the extension @code{.gp}.
Let's walk through @code{mycopy3.gp}. The first line is a comment. It
is ignored by Genparse.
The second line is the first option specification. This is the
@option{-i} option, which, as before, may be specified in long form as
@option{--iterations}. Our @code{mycopy3.gp} file indicates that
@option{-i} must take an integer parameter, the default value of which
is 1. The allowed range is non-negative. The final part of the third
line is a description of the option's usage (to appear in the
@code{usage ()} function).
The third line introduces a new option, that was not in
@command{mycopy2}. The @option{-o} option takes a string parameter
(where a "string" is any series of characters) with a default value of
empty. As indicated by the description, this option is used
to specify an output file to which @command{mycopy3}'s output will
be directed.
Default values for strings must be specified within braces and quotes
like @{"This is a stupid comment"@}, for chars it must be enclosed in
single quotes, e.g. 'a' or '\0x13'. For other integers use the plain
default value.
Starting in the third line the help screen is defined which will be
printed if @option{-h} or @option{--help} is set or if an invalid
command line is given. @code{__PROGRAM_NAME__} will be replaced with
the name of the executable (probably mycopy3), @code{__OPTIONS_SHORT__}
will be replaced with a list of allowed short options ("[ -iohv ]" in
this example). "Print a file for a number of times to stdout." will
be printed verbatim. @code{__GLOSSARY__} will be replaced with a list
explanations for each of the command line parameters. For more
explanations on the @code{#usage} section @xref{Usage Function}.
@code{mycopy3 --help} will print the following help screen:
@cindex Genparse, invoking, example
@example
usage: mycopy3 [ -iohv ] file
Print file for a number of times to stdout.
[ -i ] [ --iterations ] (type=INTEGER, range=0..., default=1)
Number of times to output <file>.
File should be text format!
[ -o ] [ --outfile ] (type=STRING)
Output file name.
[ -h ] [ --help ] (type=FLAG)
Display this help and exit.
[ -v ] [ --version ] (type=FLAG)
Output version information and exit.
@end example
Genparse can be invoked on @code{mycopy3.gp} in a number of ways (Yes,
Genparse has its own command line options! @xref{Genparse Options}.), but
we'll invoke it as follows.
@cindex Genparse, invoking, example
@example
genparse -o mycopy3_clp mycopy3.gp
@end example
@cindex C output
@noindent
This command tells Genparse to run on @code{mycopy3.gp} and to output
program files named with @code{mycopy3_clp}. This particular Genparse
file creates only a header file and a parser file since no callbacks are
specified. Let's first take a look at the header file,
@code{mycopy3_clp.h}.
@menu
* Header Files::
* Parser Files::
* Main Program::
@end menu
@node Header Files, Parser Files, Simplifying Command Line Parsing with Genparse, Simplifying Command Line Parsing with Genparse
@subsection Header Files
@cindex C header file
Below, we walk through @code{mycopy3_clp.h}, an example header file
created by Genparse. Header files, such as this one, @emph{must} be
included in all linked code that needs to access the command line
parameter values.
@example
/* mycopy3_clp.h */
#include <stdio.h>
#ifndef bool
typedef bool bool_t;
#endif
/* customized structure for command line parameters */
struct arg_t
@{
int i;
char * o;
bool h;
bool v;
int optind;
@};
/* function prototypes */
void Cmdline (struct arg_t *my_args, int argc, char *argv[]);
void usage (int status, char *program_name);
@end example
Although "real" Genparse output files begin with a section of comments,
for purposes of saving space, we'll replace all of those with a short
comment containing only the file's name.
A Genparse-created header file contains four major sections: (1) includes
and type definitions, (2) the definition of @code{struct arg_t}, (3)
parsing function prototypes, and (4) callback function prototypes. Since
we are not using callbacks in this example, only the first three
sections appear in this header file.
The file begins with a list of header files to include. Including
@code{stdio.h} is the default, and other includes may be specified in
the Genparse file. Then the @code{bool} type is conditionally defined.
While @code{bool} is typically predefined in C++, it is not in C. It
comes in handy as a type for all flag options, which can only be on or
off (true or false).
The @code{struct arg_t} structure contains a variable for each of the
options defined in @code{mycopy3.gp}. This include @code{i}, an
integer, and @code{o}, a character pointer. For C output, all variables
defined to be strings in Genparse files are declared as character
pointers. For C++ output, the C++ string type from the standard C++
library is used.
@cindex Option, help
@cindex Option, quiet
@cindex Option, version
In addition to the user-defined options, Genparse adds two extra flag
options, @option{-h} and @option{-v}. The @option{-h} option (long form
of @option{--help}) will cause the @code{usage ()} function to be called,
and the program to terminate. The @option{-v} option (long form of
@option{--version}) will be passed back for the calling function to
process. It is intended that the caller will display the program's
version number if this option is set. Note that if the calling program
does not process the @option{-v} flag, its behavior
will not be affected by this flag.
The @code{optind} variable records the value of the @code{optind} static
variable that is used by @code{getopt ()} and @code{getopt_long ()}.
However, Genparse has changed the behavior of this variable slightly.
(@xref{Parser Files}.)
The final section of @code{mycopy3_clp.h} consists of function
prototypes for the command line parser @code{Cmdline ()}@footnote{The
name of the command line parsing function can be
user-defined. @xref{Genparse Options}.}, and the @code{usage ()} function.
The @code{Cmdline ()} function is where the meat of Genparse processing
occurs. It takes as arguments a pointer to an @code{arg_t} struct which
will be filled with the values of the options, and @code{argc} and
@code{argv} which should be passed as the @code{main ()} function
receives them. Genparse asumes that @code{arg_t} is a valid pointer to
an @code{arg_t} struct, the calling program is responsible for properly
allocating memory for it. Typically, the parsing function should be
called at the beginning of the program.
The usage function lists the command line options for the program, as
well as any mandatory command line parameters. Once this information is
displayed, the program is terminated. For example, the usage function
output for @command{mycopy3}, as invoked by the @option{-h} option, is
as follows:
@example
usage: mycopy3 [ -iohqv ] file
[ -i ] [ --iterations ] Number of times to output <file>. (default = 1)
[ -o ] [ --outfile ] Output file.
[ -h ] [ --help ] Display help information. (default = 0)
[ -v ] [ --version ] Output version. (default = 0)
@end example
After displaying a brief list of all single-character options and
mandatory options, the usage message lists all options in short and long
forms, along with user-defined descriptions and each option's default
value.
@node Parser Files, Main Program, Header Files, Simplifying Command Line Parsing with Genparse
@subsection Parser Files
@cindex C parser file
In this section we examine the parser file generated from running
Genparse on @code{mycopy3.gp}.
@example
/* mycopy3_clp.c */
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include "mycopy3_clp.h"
static struct option const long_options[] =
@{
@{"iterations", required_argument, NULL, 'i'@},
@{"outfile", required_argument, NULL, 'o'@},
@{"help", no_argument, NULL, 'h'@},
@{"version", no_argument, NULL, 'v'@},
@{NULL, 0, NULL, 0@}
@};
/*----------------------------------------------------------------------------
**
** Cmdline ()
**
** Parse the argv array of command line parameters
**
**--------------------------------------------------------------------------*/
void Cmdline (struct arg_t *my_args, int argc, char *argv[])
@{
extern char *optarg;
extern int optind;
int c;
int errflg = 0;
my_args->i = 1;
my_args->o = NULL;
my_args->h = false;
my_args->v = false;
optind = 0;
while ((c = getopt_long (argc, argv, "i:o:hv", long_options, &optind)) != EOF)
@{
switch (c)
@{
case 'i':
my_args->i = atoi (optarg);
if (my_args->i < 0)
@{
fprintf (stderr, "parameter range error: i must be >= 0\n");
errflg++;
@}
break;
case 'o':
my_args->o = optarg;
break;
case 'h':
my_args->h = true;
usage (EXIT_SUCCESS, argv[0]);
break;
case 'v':
my_args->v = true;
break;
default:
usage (EXIT_FAILURE, argv[0]);
@}
@} /* while */
if (errflg)
usage (EXIT_FAILURE, argv[0]);
if (optind >= argc)
my_args->optind = 0;
else
my_args->optind = optind;
@}
/*----------------------------------------------------------------------------
**
** usage ()
**
** Print out usage information, then exit
**
**--------------------------------------------------------------------------*/
void usage (int status, char *program_name)
@{
if (status != EXIT_SUCCESS)
fprintf (stderr, "Try `%s --help' for more information.\n",
program_name);
else
@{
printf ("\
usage: %s [ -iohv ] file\n\
Print a file for a number of times to stdout.\n\
[ -i ] [ --iterations ] (type=INTEGER, range=0..., default=1)\n\
Number of times to output <file>.\n\
File should be text format!\n\
[ -o ] [ --outfile ] (type=STRING)\n\
Output file name.\n\
[ -h ] [ --help ] (type=FLAG)\n\
Display this help and exit.\n\
[ -v ] [ --version ] (type=FLAG)\n\
Output version information and exit.\n", program_name);
@}
exit (status);
@}
@end example
The parser file consists of two main functions. The @code{usage ()}
function displays the program's usage information, then terminates.
The parsing function, named @code{Cmdline ()} in this
case@footnote{The name of the parser function can be set by the user.
@xref{Genparse Options}.}, reads the command line and fills an
@code{arg_t} struct with the command line parameters.
Since the @code{usage ()} function is straightforward, we will not examine
it in detail. Instead, we will focus our attention on @code{Cmdline ()}.
This function begins by defining a @code{struct long_options} array based
on the specification in the @code{mycopy3.gp} file. This array will tell
@code{getopt_long ()} what options to expect on the command line. The
@code{struct arg_t} is then initialized and the default parameter values
from @code{mycopy3.gp} are set. Once this is complete,
@code{getopt_long ()} is looped through until all command line options have
been processed. Each option has its own @code{case} in the @code{switch}
statement. While this processing is fairly simple, there are several
options worth examining in more detail.
@itemize @bullet
@item
For the @option{-h}
option, the @code{usage ()} function is automatically called.
@item
Range checking for
@option{-i} occurs. If @option{-i} has a negative value, an error
message is printed to @emph{stderr} and the error flag is raised.
@end itemize
@noindent
After the loop over @code{getopt_long ()} is complete, the error flag
is checked. If it is raised, or if the help option has been set, the
@code{usage ()} function is called.
At the end of @code{Cmdline ()}, the behavior of @code{optind} is
modified slightly. While @code{optind} is returned to the caller in the
@code{struct arg_t}, we set it to 0 if there are no non-option command
line parameters. Otherwise, we pass it back as is, so that it can be
used as a pointer into @code{argv}.
@node Main Program, , Parser Files, Simplifying Command Line Parsing with Genparse
@subsection Main Program
@cindex C main program
Next to specification of the Genparse file, the most important part of
using Genparse is interfacing it with user code. In this section, we
show the main program code for @code{mycopy3.c} and describe how
the routines created by Genparse are used.
@example
/* mycopy3.c */
#include <stdio.h>
#include <stdlib.h>
#include "mycopy3_clp.h"
#define VERSION "3.0"
int main (int argc, char *argv[])
@{
int c, i;
FILE *fp, *ofp;
struct arg_t a;
Cmdline (&a, argc, argv);
if (a.v)
@{
printf ("%s version %s\n", argv[0], VERSION);
exit (0);
@}
if (a.o)
ofp = fopen (a.o, "w");
else
ofp = stdout;
if (!a.optind)
fp = stdin;
else
fp = fopen (argv[a.optind],"r");
for (i = 0; i < a.i; i++)
@{
while ((c = fgetc (fp)) != EOF)
fputc (c, ofp);
rewind (fp);
@}
fclose (fp);
return 0;
@}
@end example
The @code{mycopy3.c} module begins by including @code{mycopy3_clp.h},
which is necessary for the definition of the @code{arg_t} struct and
the parser function prototypes. The @code{Cmdline ()} function fills an
@code{arg_t} struct with the command line options. While the parsing
function does not always have to be called before all other processing,
it must be called before any command line parameters are used.
The program then checks a number of the parameters, as returned in the
structure. In particular, if the @option{-v} option is set, the version
number is displayed and then the program is terminated.
If the @code{optind} pointer is set to 0, indicating that there are no
non-option parameters on the command line, the input is redirected to
@emph{stdin}, If the output file is not specified with the @option{-o}
option, output is redirected to @emph{stdout}.
@node Include Files and Callbacks, C++ Output, Simplifying Command Line Parsing with Genparse, Making Genparse Files
@section Include Files and Callbacks
So far, our examples have only considered the basic features of Genparse.
In fact, these features are probably more than enough for 90% of all
command line parsing needs. However, some programs require additional
flexibility. In this section, we explore some of the advanced features
of Genparse.
@cindex Include files
Include files may be specified at the beginning of a Genparse file.
They are listed in C style, e.g., @code{#include <file.h>} or
@code{#include "file.h"}. One of the possible uses of
include files are for when a macro needs to be used in a Genparse
file. Consider the following modification to @code{mycopy3.gp}.
@example
@group
/* mycopy3.gp */
#include <mycopy3.h>
i / iterations int 1 [0...MAX] "Number of times to output <file>."
o / outfile string @{""@} "Output file."
#usage_begin
usage: __PROGRAM_NAME__ __OPTIONS_SHORT__ file
Print a file for a number of times to stdout.
__GLOSSARY__
#usage_end
@end group
@end example
@noindent
This example assumes that the macro @code{MAX} is defined in
@code{mycopy3.h}.
@cindex Callback functions
In order to demonstrate the utility of callback functions, let's further
modify @code{mycopy3.gp}. In fact, let's just call it
@code{mycopy4.gp}.
@example
@group
/* mycopy4.gp */
#include <mycopy4.h>
my_callback ()
i / iterations int 1 [1..MAX] "Number of times to output <file>."
o / outfile string @{""@} outfile_cb () "Output file."
#usage_begin
usage: __PROGRAM_NAME__ __OPTIONS_SHORT__ file
Print a file for a number of times to stdout.
__GLOSSARY__
#usage_end
@end group
@end example
This file instructs Genparse to create a global callback function
@code{my_callback ()} and the option callback function
@code{outfile_cb ()}.
For these callbacks, Genparse adds prototypes to the header file, a call
to the parser file, and callback skeletons in a callback file. Rather than
display the whole header and parse files, we'll just show the lines
that are added.
Callback functions are useful if extra processing needs to occur before
one or more parameters are used by the main program. For example, if one
parameter is dependent on the values of two others, a user-defined
global callback function can contain the logic to check for the proper
conditions.
@example
@group
/* mycopy4_clp.h */
/* global and local callbacks */
int my_callback (struct arg_t *);
int outfile_cb (char *);
@end group
@end example
In the @code{mycopy4_clp.h} file, prototypes for the global and the
option callback functions are added.
@example
/* mycopy4_clp.c */
@group
case 'o':
my_args->o = optarg;
if (!outfile_cb (my_args->o))
usage (EXIT_FAILURE, argv[0]);
break;
@end group
...
@group
if (!my_callback (my_args))
usage (argv[0]);
@end group
@end example
In the @code{mycopy4_clp.c} file, a call to the callback functions is made.
If a 0 is returned, an error is assumed and the usage function is
called.
The main difference in Genparse behavior that including callbacks
produces is the creation of a callback file. This file contains
skeletons of all of the callback functions. It is up to the user
to fill them in. Note that callbacks should return 0 on error and
non-zero otherwise.
@example
/* mycopy4_clp_cb.c */
#include <stdio.h>
#include "mycopy4_clp.h"
/*----------------------------------------------------------------------------
**
** my_callback ()
**
** User defined global callback.
**
**--------------------------------------------------------------------------*/
int my_callback (struct arg_t *a)
@{
return 1;
@}
/*----------------------------------------------------------------------------
**
** outfile_cb ()
**
** User defined parameter callback.
**
**--------------------------------------------------------------------------*/
int outfile_cb (char * var)
@{
return 1;
@}
@end example
Note that the @code{struct arg_t} structure must be passed to the global
callback, while the option value is expected to be passed in character
array format to option callbacks.
@node C++ Output, Java Output, Include Files and Callbacks, Making Genparse Files
@section C++ Output
@cindex C++ output
All of our example so far have shown Genparse creating C code. Genparse
also supports C++ output. This section examines the difference between
C and C++ output and how to interface a program with a command line
parsing class created by Genparse.
As with C output, Genparse creates two or three C++ output files: a
header file, a parser class file, and a callback file. We'll use
@code{mycopy4.gp} as input to create these files. We invoke Genparse as
follows.
@example
genparse -l cpp -o mycopy4_clp mycopy4.gp
@end example
The three created files are named, @code{mycopy4_clp.h},
@code{mycopy4_clp.cc}, and @code{mycopy4_clp_cb.cc}. We'll walk through
each one in turn.
@menu
* Header File::
* Parser File::
* Callback File::
* Main C++ Program::
@end menu
@node Header File, Parser File, C++ Output, C++ Output
@subsection Header File
@cindex C++ header file
The code for @code{mycopy4_clp.h} appears below.
@example
/* mycopy4_clp.h */
#ifndef CMDLINE_H
#define CMDLINE_H
#include <iostream>
#include <string>
#include "mycopy4.h"
/*----------------------------------------------------------------------------
**
** class Cmdline
**
** command line parser class
**
**--------------------------------------------------------------------------*/
class Cmdline
@{
private:
/* parameters */
int _i;
std::string _o;
bool _h;
bool _v;
/* other stuff to keep track of */
std::string _program_name;
int _optind;
public:
/* constructor and destructor */
Cmdline (int, char **) throw (std::string);
~Cmdline ()@{@}
/* usage function */
void usage (int status);
/* return next (non-option) parameter */
int next_param () @{ return _optind; @}
/* callback functions */
bool my_callback ();
bool outfile_cb ();
int i () @{ return _i; @}
std::string o () @{ return _o; @}
bool h () @{ return _h; @}
bool v () @{ return _v; @}
@};
#endif
@end example
The header file contains the definition of the command line parser
class. The class defines a logical structure that puts different
requirements on the main program than when the output code is in C.
We summarize the differences between C and C++ output below.
@itemize @bullet
@item
Each parameter value is stored in a private member variable, and must be
accessed through a call to the member function named with the short
form of the option. If Genparse was called with the option
@option{--longmembers} then this function is named by the long form of
the option.
@item
The name of the executable is stored in a private member variable,
but is not available to the via the interface (the main program has
access to @code{argv[0]}).
@item
A copy of the @code{optind} variable is stored in a private member
variable, and is accessible through the @code{next_param ()} member
function.
@item
All callbacks are public member functions.
@item
The usage function is a public member function.
@item
The constructor throws a string exception if command line parsing
fails.
@end itemize
@node Parser File, Callback File, Header File, C++ Output
@subsection Parser File
@cindex C++ parser file
The parser file defines the non-inlined member functions; i.e., the
constructor and the usage function. The code for @code{mycopy4_clp.cc}
appears below.
@example
/* mycopy4_clp.cc */
#include <getopt.h>
#include <stdlib.h>
#include "mycopy4_clp.h"
/*----------------------------------------------------------------------------
**
** Cmdline::Cmdline ()
**
** Constructor method.
**
**--------------------------------------------------------------------------*/
Cmdline::Cmdline (int argc, char *argv[]) throw (std::string )
@{
extern char *optarg;
extern int optind;
int c;
static struct option long_options[] =
@{
@{"iterations", required_argument, NULL, 'i'@},
@{"outfile", required_argument, NULL, 'o'@},
@{"help", no_argument, NULL, 'h'@},
@{"version", no_argument, NULL, 'v'@},
@{NULL, 0, NULL, 0@}
@};
_program_name += argv[0];
/* default values */
_i = 1;
_h = false;
_v = false;
optind = 0;
while ((c = getopt_long (argc, argv, "i:o:hv", long_options, &optind)) != EOF)
@{
switch (c)
@{
case 'i':
_i = atoi (optarg);
if (_i < 1)
@{
std::string s;
s += "parameter range error: i must be >= 1";
throw (s);
@}
if (_i > MAX)
@{
std::string s;
s += "parameter range error: i must be <= MAX";
throw (s);
@}
break;
case 'o':
_o = optarg;
if (!outfile_cb ())
this->usage (EXIT_FAILURE);
break;
case 'h':
_h = true;
this->usage (EXIT_SUCCESS);
break;
case 'v':
_v = true;
break;
default:
this->usage (EXIT_FAILURE);
@}
@} /* while */
_optind = optind;
if (!my_callback ())
usage (EXIT_FAILURE);
@}
/*----------------------------------------------------------------------------
**
** Cmdline::usage ()
**
** Print out usage information, then exit.
**
**--------------------------------------------------------------------------*/
void Cmdline::usage (int status)
@{
if (status != EXIT_SUCCESS)
std::cerr << "Try `" << _program_name << " --help' for more information.\n";
else
@{
std::cout << "\
usage: " << _program_name << " [ -iohv ] file\n\
Print a file for a number of times to stdout.\n\
[ -i ] [ --iterations ] (type=INTEGER, range=1...MAX, default=1)\n\
Number of times to output <file>.\n\
do it like this\n\
[ -o ] [ --outfile ] (type=STRING)\n\
Output file.\n\
[ -h ] [ --help ] (type=FLAG)\n\
Display this help and exit.\n\
[ -v ] [ --version ] (type=FLAG)\n\
Output version information and exit.\n";
@}
exit (status);
@}
@end example
As can be seen from this example, the C++ parser is very similar to the
C parser we discussed in @ref{Parser Files}. The main differences are
that all strings are stored in C++ @code{string} format@footnote{Older
C++ compilers may not support built-in strings. If this is a problem,
upgrade your compiler! It's too old anyway.}.
It is important to note that the callback file is actually included
into the parser file. This is because callbacks are implemented as
member functions of the parser class, and most C++ compilers will
not allow splitting a class's member functions across more than one
file. The bottom line of all this is that you don't have to link
in the callback file, just the parser file.
@node Callback File, Main C++ Program, Parser File, C++ Output
@subsection Callback File
@cindex C++ callback file
The callback file defines skeleton callback routines for the user to
fill in. Their syntax is virtually identical to the C output case,
except that their return values are @code{bool} rather than
@code{int}. The code for @code{mycopy4_clp_cb.cc} appears below.
@example
/* mycopy4_clp_cb.cc */
#include "mycopy4_clp.h"
/*----------------------------------------------------------------------------
**
** Cmdline::my_callback ()
**
** Global callback.
**
**--------------------------------------------------------------------------*/
bool Cmdline::my_callback ()
@{
return true;
@}
/*----------------------------------------------------------------------------
**
** Cmdline::outfile_cb ()
**
** Parameter callback.
**
**--------------------------------------------------------------------------*/
bool Cmdline::outfile_cb ()
@{
return true;
@}
@end example
@node Main C++ Program, , Callback File, C++ Output
@subsection Main Program
@cindex C++ main program
Due to the syntactic differences between C and C++, the C++ main program
must interact with the command line parser class in a different fashion
than in the C case. The code for @code{mycopy4.cc} appears below.
@example
/* mycopy4.cc */
#include <cstdlib>
#include <iostream>
#include <fstream>
#include "mycopy4_clp.h"
using namespace std;
#define VERSION "3.0"
int main (int argc, char *argv[])
@{
int i;
char c;
ifstream input_file;
ofstream output_file;
bool ofile = false, ifile = false;
Cmdline cl (argc, argv);
if (cl.v ())
@{
cout << argv[0] << " version " << VERSION << endl;
exit (0);
@}
if (!cl.o ().empty ())
@{
output_file.open (cl.o ().c_str ());
ofile = true;
@}
if (cl.next_param ())
@{
input_file.open (argv[cl.next_param ()]);
ifile = true;
@}
for (i = 0; i < cl.i (); i++)
@{
if (ifile) c = input_file.get ();
else cin >> c;
while (c != EOF)
@{
if (ofile) output_file.put (c);
else cout << c;
if (ifile) c = input_file.get ();
else cin >> c;
@}
if (ifile)
@{
input_file.clear ();
input_file.seekg (0);
@}
@}
input_file.close ();
output_file.close ();
return 0;
@}
@end example
Although @code{mycopy4} provide almost identical output and
functionality as that of @code{mycopy3}, it must access all command line
parameters and related information through the command line parser class
interface.
@node Java Output, Idiosyncrasies, C++ Output, Making Genparse Files
@section Java Output
@cindex Java output
This section shows the Java output and how to interface a Java program
with a command line parsing class created by Genparse.
For Java, Genparse creates a Java interface, a parser class that implements
it and an exception class that may be thrown by the parser. A separate output
file is written for each of them. We'll use @code{mycopy5.gp} as input to
create the two output files. Genparse generates Java code as follows.
@example
genparse -l java -o Cmdline mycopy5.gp
@end example
The three created files are named, @code{CmdlineInterface.java},
@code{Cmdline.java} and @code{CmdlineEx.java}. We'll walk through each one
in turn.
@menu
* Java Interface::
* Java Implementation::
* Java Exception Class::
* Main Java Program::
@end menu
@node Java Interface, Java Implementation, , Java Output
@subsection Java Interface
@cindex Java interface
@example
/* CmdlineInterface.java */
/*----------------------------------------------------------------------------
**
** interface CmdlineInterface
**
** Interface of the command line parser class
**
**--------------------------------------------------------------------------*/
public interface CmdlineInterface
@{
/* usage function */
void usage (int status, String program_name);
/* return next (non-option) parameter */
int next_param ();
/* callback functions */
boolean my_callback ();
boolean outfile_cb ();
/* getter functions for command line parameters */
int i ();
String o ();
boolean h ();
boolean v ();
@};
@end example
Each parameter value is stored in a private member variable, and must be
accessed through a call to the member function named with the short
form of the option. If Genparse was called with the option
@option{--longmembers} then this function is named by the long form
of the option.
A copy of the @code{optind} variable is stored in a private member
variable, and is accessible through the @code{next_param ()} member
function.
@node Java Implementation, Java Exception Class, Java Interface, Java Output
@subsection Java Implementation
@cindex Java implementation
@example
/* Cmdline.java */
import gnu.getopt.LongOpt;
import gnu.getopt.Getopt;
/*----------------------------------------------------------------------------
**
** class Cmdline ()
**
** Command line parser class.
**
**--------------------------------------------------------------------------*/
public class Cmdline implements CmdlineInterface
@{
/* parameters */
private int _i;
private String _o;
private boolean _h;
private boolean _v;
/* Name of the calling program */
private String _executable;
/* next (non-option) parameter */
private int _optind;
/* Must be constructed with parameters. */
public Cmdline (String[] argv) throws CmdlineEx
@{
/* character returned by optind () */
int c;
LongOpt[] longopts = new LongOpt[4];
longopts[0] = new LongOpt ("iterations", LongOpt.REQUIRED_ARGUMENT, null, 'i');
longopts[1] = new LongOpt ("outfile", LongOpt.REQUIRED_ARGUMENT, null, 'o');
longopts[2] = new LongOpt ("help", LongOpt.NO_ARGUMENT, null, 'h');
longopts[3] = new LongOpt ("version", LongOpt.NO_ARGUMENT, null, 'v');
_executable = Cmdline.class.getName ();
/* default values */
_i = 1;
_h = false;
_v = false;
Getopt g = new Getopt (_executable, argv, "i:o:hv", longopts);
while ((c = g.getopt ()) != -1)
@{
switch (c)
@{
case 'i':
_i = Integer.parseInt (g.getOptarg ());
if (_i < 1)
throw new CmdlineEx ("parameter range error: i must be >= 1");
if (_i > 10)
throw new CmdlineEx ("parameter range error: i must be <= 10");
break;
case 'o':
_o = g.getOptarg ();
if (!outfile_cb ())
usage (-1, _executable);
break;
case 'h':
_h = true;
usage (0, _executable);
break;
case 'v':
_v = true;
break;
default:
usage (-1, _executable);
@}
@} /* while */
_optind = g.getOptind ();
if (!my_callback ())
usage (-1, _executable);
@}
public void usage (int status, String program_name)
@{
if (status != 0)
@{
System.err.println ("Try `" + program_name + " --help' for more information.");
@}
else
@{
System.out.println (
"usage: " + program_name + " [ -iohv ] file\n" +
"Print a file for a number of times to stdout.\n" +
" [ -i ] [ --iterations ] (type=INTEGER, range=1...10, default=1)\n" +
" Number of times to output <file>.\n" +
" do it like this\n" +
" [ -o ] [ --outfile ] (type=STRING)\n" +
" Output file.\n" +
" [ -h ] [ --help ] (type=FLAG)\n" +
" Display this help and exit.\n" +
" [ -v ] [ --version ] (type=FLAG)\n" +
" Output version information and exit.");
@}
System.exit (status);
@}
/* return next (non-option) parameter */
public int next_param () @{ return _optind; @}
/* Callback functions */
/* Derive your own class and overwrite any of the callback */
/* functions if you need customized callbacks. */
public boolean my_callback () @{ return true; @}
public boolean outfile_cb () @{ return true; @}
/* getter functions for command line parameters */
public int i () @{ return _i; @}
public String o () @{ return _o; @}
public boolean h () @{ return _h; @}
public boolean v () @{ return _v; @}
@}
@end example
There is no default constructor. Instead the parser class must be
constructed with an array of strings which is usually the argument
to the @code{main ()} function.
The constructor throws an exception if command line parsing
fails. The exception type is defined in @xref{Java Exception Class}.
Note that no separate callback file is generated like for C or C++. The parser
class contains default implementations for each of the callback functions,
if you need customized callbacks then simply derive your own class from
the generated parser class.
@node Java Exception Class, Main Java Program, Java Implementation, Java Output
@subsection Java Exception Class
@cindex Java exception class
@example
/* CmdlineEx.java */
/*----------------------------------------------------------------------------
**
** class CmdlineEx
**
** Exception class thrown by the command line parser class
**
**--------------------------------------------------------------------------*/
public class CmdlineEx extends RuntimeException
@{
public CmdlineEx (String text) @{ super (text); @}
@}
@end example
This exception class is always the same of course. Only the
name of the class would change if --parsefunc was set with a
different name than Cmdline.
@node Main Java Program, , Java Exception Class, Java Output
@subsection Main Java Program
@cindex Java main program
The example code for Java is very similar to the C++ example
(@xref{Main C++ Program}.).
@example
/* mycopy5.java */
import gnu.getopt.LongOpt;
import gnu.getopt.Getopt;
import java.io.*;
class mycopy5
@{
public static void main (String args[])
@{
final String _executable = "mycopy5"; /* Don't know how to set this automatically in Java */
final String VERSION = "3.0";
final int EOF = - 1; /* Is EOF predefined in Java? */
int i;
int c;
int length;
OutputStreamWriter output_file;
InputStreamReader input_file;
boolean ofile = false, ifile = false;
Cmdline cl = new Cmdline (args);
if (cl.v ())
@{
System.out.println (_executable + " version " + VERSION);
System.exit (0);
@}
try
@{
length = cl.o ().length ();
if (length != 0)
@{
output_file = new OutputStreamWriter (new FileOutputStream (cl.o ()));
ofile = true;
@}
else
@{
output_file = new OutputStreamWriter (System.out);
@}
if (cl.next_param () != 0)
@{
input_file = new InputStreamReader (new FileInputStream (args[cl.next_param ()]));
ifile = true;
@}
else
@{
input_file = new InputStreamReader (System.in);
@}
for (i = 0; i < cl.i (); i++)
@{
c = input_file.read ();
while (c != EOF)
@{
output_file.write (c);
c = input_file.read ();
@}
if (ifile)
@{
input_file.close ();
input_file = new InputStreamReader (new FileInputStream (args[cl.next_param ()]));
@}
@}
input_file.close ();
output_file.close ();
@}
catch (IOException ex)
@{
System.out.println ("File I/O error: " + ex);
@}
System.exit (0);
@}
@}
@end example
@node Idiosyncrasies, , Java Output, Making Genparse Files
@section Idiosyncrasies
@cindex Idiosyncrasies
Although Genparse has been designed to be as flexible as possible, it
will always be more limited than manual command line parsing or using
@code{getopt ()}. In this section, we document some of the strange
and unusual behavior of Genparse.
@itemize @bullet
@item
In order to specify an option that only has a long form, you must specify
the token "NONE" in place of the short option. For example
@example
NONE / longonly flag
@end example
specified a flag option that only has a long form (@option{--longonly}).
@item
The @option{-h} and @option{-v} options will always exist.
Their default behavior can be overridden, but Genparse cannot create
parsers without them. (@xref{Genparse Options}.)
@item
In a parser, the @option{-h} option will automatically call the usage
function if and only if the long form of the option is @option{--help}.
Otherwise, Genparse assumes that the user has overridden @option{-h} and
treats it like any other option.
@cindex Linking
@item For C output you must link in both the parser and the callback
files. For C++ output, you only need to link in the parser file.
@xref{Parser File}.
@end itemize
@c CHAPTER
@node Genparse Options, Genparse File Syntax, Making Genparse Files, Top
@chapter Genparse Options
@cindex Options
In this section we present the command line options that Genparse
accepts, along with their default values. Genparse's command line
parsing functions were created by Genparse (talk about bootstrapping),
so you can expect Genparse to behave like any other program with
Genparse-enabled command line parsing.
@itemize @bullet
@cindex C++ filename extensions
@item
@strong{@option{-c} / @option{--cppext}}: C++ file extension. There are
a number of valid C++ file extensions, such as "C", "cc", "cpp",and
"cxx". This option allows the user to specify which one should be used
for the C++ files created by Genparse. The default value is "cc". If
C++ is not the output language, this option is ignored.
@item
@strong{@option{-d}}: Debug mode. Setting this flag turns on debugging
in the form of logging to a file and @command{bison} debug output to
@emph{stderr}. The name of the debug/log file can be specified with the
@option{-f} option (see below). The default value is off. Only useful
for debugging Genparse itself.
@item
@strong{@option{-f} / @option{--logfile}}: Name of log file. Only used
if debugging (@option{-d} option) is turned on. All debug output will
be written to this file. Currently this consists of the processing of
the Genparse file and dumping the state of the command line parameter
list class. The default value is "genparse.log". Only useful for
debugging Genparse itself.
@item
@anchor{gnulib}@strong{@option{-g} / @option{--gnulib}}: Use GNU Compatibility Library
(Gnulib, see @uref{http://www.gnu.org/software/gnulib/}). Only available
for C output. Allows some more types (unsigned long, intmax_t etc.) for
which Gnulib provides conversion functions.
@item
@strong{@option{-h} / @option{--help}}: Help instructions. This option
displays the usage of Genparse with a list of all command line options,
then terminates the program. The default is off.
@item
@anchor{internationalize}@strong{@option{-i} / @option{--internationalize}}:
Put internationalization macro _() around text output so that the generated
program can be internationalized using the GNU gettext command. Presently
only implemented for C output.
@item
@strong{@option{-l} / @option{--language}}: Output language. The
programming language in which Genparse writes the output files.
Currently only C, C++ and Java are supported. The default is C.
To indicate C++, the following strings may be used: "c++", "cpp", "cc",
and "cxx". In order to generate Java code use "java" or "Java".
@item
@strong{@option{-m} / @option{--longmembers}}: Use long options for the
members of the parser class (struct). The default is to use the short
representation except if there is only a long representation defined in
the genparse file. If this option is set then the behavior is reverted.
The long representation is used then except if there is only a short
representation defined.
@item
@strong{@option{-o} / @option{--outfile}}: Output file name. Specifies
the main part of the output file name. The extension will be determined
by the output language and possibly by other options. For example, when
the output language is C, giving this option an argument of "file" will
result in output file names of "file.h", "file.c" and "file_cb.c" for
the header, parser, and callback files, respectively. Default value is
"parse_cl". Use the @option{-D} option in order to specify a directory
for the results.
@item
@strong{@option{-p} / @option{--parsefunc}}: Name of the parsing
function/class. This option allows the user to specify the name of the
function (for C) or class (for C++ and Java) that does the actual command
line parsing. Default value is "Cmdline". In Java this value is also
used as a prefix for the names of the interface and the exception class.
Leaving the default names the interface "CmdlineInterface" and the exception
class "CmdlineEx".
@item
@strong{@option{-P} / @option{--manyprints}}: Output help text for every
command line parameter in a separate print command.
@item
@strong{@option{-q} / @option{--quiet}}: Quiet mode.
@item
@strong{@option{-s} / @option{--static-headers}}: Keep the descriptive
header on top of the generated files static. Without this option
genparse prints creation date and time, Linux kernel version, kernel
build time, computer architecture name, host name and user name.
@item
@strong{@option{-v} / @option{--version}}: Version. If this option is
set, the version number is displayed, then the program is terminated.
The default value is off.
@item
@strong{@option{-D} / @option{--directory}}: Directory for storing results.
@end itemize
@cindex Overriding default options
The @option{-h} and @option{-v} options can be overridden
by defining them to be something else in the Genparse file. However,
they cannot be turned off completely. In other words, you can define
your own @option{-h} and @option{-v} options or let
Genparse create them with the default behavior.
@c CHAPTER
@node Genparse File Syntax, The Future, Genparse Options, Top
@chapter Genparse File Syntax
@cindex Genparse file syntax
@menu
* Global Definitions::
* Parameter Definitions::
* Usage Function::
* Genparse File Grammar::
@end menu
@node Global Definitions, Parameter Definitions, , Genparse File Syntax
@section Global Definitions
The following definitions are allowed on top of the parameter definitions.
All of them are optional. They may appear in any order.
@itemize @bullet
@item
@anchor{Include files}@strong{Include files}: Include statements in the
C syntax, e.g. @code{#include "file.h"} or @code{#include <file.h>}.
Ignored in languages other than C and C++. Only 1 include statement per
line.
@item
@strong{Mandatory parameters}: Parameters which must be specified.
They are not bound to any command line options. Example:
@code{#mandatory x}. Use multiple @code{#mandatory} statements
in order to specify multiple mandatory parameters.
Only 1 @code{#mandatory} statement per line. Note that Genparse
does not check for mandatory parameters, they are only printed
in the @code{usage ()} function with the @code{__MANDATORIES__}
directive (@xref{__MANDATORIES__}.). @strong{Deprecated: add mandatory
parameters in the #usage section instead.}
@item
@strong{Exit value}: Defines the exit value in case of an error. Default
is @code{EXIT_FAILURE}. Example: @code{#exit_value -1} or
@code{#exit_value MY_FAILURE}.
@item
@anchor{#break_lines}@strong{#break_lines}: Width to which lines shall
be broken on the help screen. If no @code{#break_lines} directive is
specified then lines will be printed exactly as given in the genparse file.
Note that genparse doesn't know the width of macros included from other
files, so automatic line breaking will probably not work properly if for
example @code{__STRING__} macros (@xref{__STRING__}.) are used. Lines
can still be broken manually using the @code{__NL__} macro (@xref{__NL__}.)
in places where Genparse doesn't break lines as expected.
@item
@strong{#no_struct}: If @code{#no_struct} is specified then no struct
will be defined which will be filled with the command line parameters in
the generated parser. This may be useful if you want to add your own code
with @code{__CODE__} statements instead (@xref{__CODE__}.) Only supported
for C output.
@item
@strong{#export_long_options}: If @code{#export_long_options} is defined
then a function @code{get_long_options ()} is added which exports the
longoptions array used by @code{getopt_long ()}. This directive is only available
for C output, for other languages it is ignored.
@item
@strong{Global callback}: The name of a global callback function
which will be called after all parameter specific callback functions.
Example: @code{my_callback ()}. Only 1 global callback function is allowed.
@end itemize
@node Parameter Definitions, Usage Function, Global Definitions, Genparse File Syntax
@section Parameter Definitions
Each command line parameter must be defined in the form
@example
short_names[*|!] [/ long_name[*|!][=opt_name]] type [ options ]
@end example
A short_name is a single letter (small or capital) or a single digit. long_name
is a longer (more descriptive) option name. On the command line a short name
will be preceded by a single dash (e.g. @code{-a}) and a long version will
be preceded by two dashes (e.g. @code{--all}). If a long parameter name is not
necessary, you may specify only the short one (and the slash need not appear).
In order to specify a parameter that only has a long name set short_names to @code{NONE}.
It is possible to have multiple short options, so for example setting short_name to 'aA'
and long_name to 'all' would allow to specify the command line switch as @code{-a}
or @code{-A} or @code{--all}, all of them doing the same thing. long options can
be followed by a descriptive designation (@xref{opt_name}.).
@anchor{optional_arguments}A @code{*} after @code{short_name} or @code{long_name}
makes the argument optional. This can be specified for short and long options
separately.
A @code{!} after @code{short_name} or @code{long_name} makes the option boolean.
This allows one to combine a boolean short option with a long option with an optional
or mandatory argument or to combine a boolean long option with a short option with
an optional or mandatory argument. A @code{!} doesn't make sense if the option's
type is @code{flag}.
Examples:
@example
o* / oparam* string "Both short and long option have an optional"
"argument"
p* / pparam string "Short option has an optional argument,"
"long option requires an argument."
q / qparam* string "Short option reqires an argument,"
"long option has an optional argument."
P* / Pparam! string "Short option has an optional argument,"
"long option none."
Q!/ Qparam* string "Short option has no argument, long option has an"
"optional argument."
@end example
type must be one of @code{int} @code{float} @code{char} @code{string} or
@code{flag}. The first four should be self-explanatory. The last is a "switch"
option that takes no arguments. For C output and if @option{--gnulib}
(@xref{gnulib}.) is set on the command line additionally the following types are
allowed: @code{long} (for long int), @code{ulong} (for unsigned long int),
@code{intmax} (for intmax_t, defined in Gnulib), @code{uintmax} (for uintmax_t),
@code{double}.
The following four options are supported. They may appear in any order and except
for descriptions only one of each field may be defined per option.
@itemize @bullet
@item
A @strong{default value} for the parameter. For a string this is just the plain
default value, whatever it is. For strings, a default must be specified within
braces and quotes, and may include whitespace, e.g. @{"my default value"@}. For a
char parameter it must be enclosed in single quotes, e.g. 'a' or '\n'.
@item
@anchor{range}A @strong{range} of values within brackets. The low and high values
are specified between a range specifier (either '...' or '..'). Either the high or
the low value may be omitted for a range bounded on one side only. The parameter
will be checked to make sure that it lies within this range.
@item
A @strong{callback function}. This function is called after any range checking is
performed. The purpose of the callback to do validity checking that is more
complicated than can be specified in the genparse file. For example, you might
write a program that requires input to be prime numbers, strings of a certain
length, etc.
@item
A @anchor{parameter-description}@strong{description} in double quotes. It is
printed by the @code{usage ()} function. If one line is not enough then specify
multiple descriptions, one per line and each of them in double quotes. If the
description starts in the 1st column in the Genparse file then it will also
be printed in the 1st column in the @code{usage ()} function.
@item
A @strong{Genparse include file}. Includes another Genparse (.gp) file,
e.g @code{#gp_include another.gp}. Only parameter definitions are allowed in
the included file, no global directives.
@item
An @strong{__ERR_MSG__(err_txt)} directive. Specifies the error message which
is printed when the argument could not be converted. Example:
@code{__ERR_MSG__("%s: invalid argument")}. This message will be printed when
either the conversion function failed or when the argument was out of range
(@xref{range}.). Assumes to contain one @code{%s} which will be replaced with
the agrument which could not be converted. Only available when Genparse is
invoked with @option{--gnulib} (@xref{gnulib}.), ignored otherwise.
Optionally a conversion function can be added as a second argument, e. g.
@code{__ERR_MSG__("%s: invalid argument", quotearg)}. This would lead to an
error message like
@code{error (EXIT_FAILURE, 0, "%s: invalid argument", quotearg (optind))}.
@item
An @strong{__ADD_FLAG__} directive. Makes sense only if the command line
parameter is not already a flag, in this case an additional flag parameter
is added which will be set if the command line parameter was specified on
the command line. This option is automatically set if a parameter has
an optional argument.
@item
@anchor{__CODE__}A @strong{__CODE__(statements)} directive. The specified code
statements are copied literally. Example:
@code{__CODE__(printf ("Parameter x was set");)}. The specified code can extend
over more than one line. In order to give Genparse the chance to indent the
code properly, do not mix space and tab indentations in one @code{__CODE__}
statement.
@item
A @strong{__STORE_LONGINDEX__} directive. Instructs Genparse to add an interer
type field to the result class which will be set to the longindex variable
(last argument in the call to @code{getopt_long ()}). This new field will get
the same name as the result field it is related to but with an @code{_li}
postfix.
@end itemize
@node Usage Function, Genparse File Grammar, Parameter Definitions, Genparse File Syntax
@section Usage Function
Genparse also generates a usage () function which prints a help text
to stdout about the usage of the program for which Genparse is
generating the parser. It is automatically executed when
@itemize @bullet
@item
The command line option -h is set.
@item
An invalid command line option is given.
@item
The optind_long function call (which is the heart of every Genparse generated
parser) returns an error code.
@end itemize
This usage function can be customized by specifying a usage section at
the bottom of the Genparse file. If no such section is specified it
defaults to
@example
#usage_begin
usage: __PROGRAM_NAME__ __OPTIONS_SHORT__ __MANDATORIES__
__GLOSSARY__
#usage_end
@end example
The usage section starts with @code{#usage_begin} and ends with
@code{#usage_end}. Any text between is printed verbatim except
for the following keywords, which will be replaced as listed below:
@itemize @bullet
@item
@code{__PROGRAM_NAME__}: The program name. In C and C++ the program
name is given in @code{argv[0]}.
@item
@code{__OPTIONS_SHORT__}: A list of available short form options, e.g.
@code{[ -abc ]}.
@item
@anchor{__MANDATORIES__}@code{__MANDATORIES__}: A list of all
mandatory parameters as defined with @code{#mandatory} commands
(@xref{Global Definitions}.). @strong{Deprecated: List mandatory
parameters here directly.}
@item
@anchor{__GLOSSARY__}@code{__GLOSSARY__}: A description of all
command line options. This is the information given for the parameter
definitons (see @xref{Parameter Definitions}.) in human readable form.
It includes the parameter type, default, range and any comments. A line
which contains @code{__GLOSSARY__} is replaced by the glossary of the
parameters, any other text in the same line is ignored. Example:
@example
[ -h ] [ --help ] (type=FLAG)
Display help information.
@end example
@item
@anchor{__GLOSSARY_GNU__}@code{__GLOSSARY_GNU__}: Same as
@code{__GLOSSARY__} but in GNU style. Optionally followed by an
integer in brackets which specifies the indentation of the descriptive
text (e.g. @code{__GLOSSARY__(30)}). Default indentation is 24.
Example:
@example
-h, --help Display help information.
@end example
@item
@anchor{__STRING__}@code{__STRING__(s)}: A string constant, in C probably a string macro
defined with the #define preprocessor command. This macro can be
imported from another file using the include directive in the genparse file
(@xref{Include files}.). Ignored when generating Java output.
@item
@code{__INT__(x)}: An integer constant, in C probably an integer macro
defined with the #define preprocessor command. This macro can be
imported from another file using the include directive in the genparse file
(@xref{Include files}.). Ignored when generating Java output.
@item
@code{__CODE__(statements)}: @xref{__CODE__}.
@item
@code{__DO_NOT_DOCUMENT__}: Any line which contains this macro will not be
printed in the @code{usage ()} function. Can be used for implementing command
line parameters without listing them on the help screen.
@item
@anchor{__NL__}@code{__NL__}: New line. Useful for breaking lines manually
while automatic line breaking is on (@xref{#break_lines}.). Ignored when
generating Java output.
@item
@code{__NEW_PRINT__}: Close the active print command and start a new one.
@item
@code{__COMMENT__(text)}: Comment in the code for printing the usage text.
@end itemize
@anchor{opt_name}long options can be followed by an @code{=} sign and
an optional designation @code{opt_name} in the genparse file
(@xref{Parameter Definitions}.) which can be referred to in the following
description (@xref{parameter-description}.). It will be used in the
@code{usage ()} function only. For example the following genparse line
@example
s / block-size=SIZE int "use SIZE-byte blocks"
@end example
will lead to the following line in the help screen
@example
[ -s ] [ --block-size=SIZE ] (type=INTEGER)
use SIZE-byte blocks
@end example
in genparse style (@xref{__GLOSSARY__}.) or
@example
-s, --block-size=SIZE use SIZE-byte blocks
@end example
in GNU style (@xref{__GLOSSARY_GNU__}.).
It is also possible to put square braces around the optional name in order
to indicate that the argument is optional. This has no meaning for the
generated parser however. Use @code{*} postfixes in order to make an
argument optional (@xref{optional_arguments}.).
@example
s* / block*[=SIZE] int "use blocks."
"If SIZE is not given then they will get a size of 1kB."
@end example
will lead to the following line in the help screen
@example
-s, --block[=SIZE] use blocks.
If SIZE is not given then they will get a size of 1kB.
@end example
For an example of the generated default usage () function in C
@xref{Parser Files}.
@node Genparse File Grammar, , Usage Function, Genparse File Syntax
@section Genparse File Grammar
@cindex Genparse File Grammar
In order to better understand the subtleties of the Genparse file format
and its parsing, in the section we provide the formal grammar of
Genparse files. This is a slightly edited version of the @command{bison}
grammar. Items in capitals are tokens that are defined in the lex file.
@example
all: globals entries usages
globals: /* empty */
| globals global
| global
global: include
| mandatory
| exit_value
| break_lines
| export_long_options
| no_struct
| global_callback
include: #include <FILENAME>
mandatory: #mandatory <FILENAME>
exit_value: #exit_value <VALUE>
break_lines: #break_lines <WIDTH>
export_long_options: #export_long_options
no_struct: #no_struct
global_callback: callback
entries: entries entry
| entry
entry: new_entry
| gp_include
new_entry: param type options
options: options option
| option
option: default
| range
| callback
| descs
| store_longindex
| err_msg
| comment
| code_lines
descs: descs desc
| desc
err_msg: __ERR_MSG__ ( ALNUM )
| __ERR_MSG__ ( QUOTED )
comment: __COMMENT__ ( COMMENT_STR )
gp_include: #gp_include <FILE>
param: short_params
| NONE / long_param
| short_params / long_param
short_params: VAR
| VAR *
| VAR !
long_param: multi_long_option
| multi_long_option mandatory_opt_name
| multi_long_option optional_opt_name
mandatory_opt_name: EQUAL C_VAR
| EQUAL OPT_NAME
optional_opt_name: [ mandatory_opt_name ]
multi_long_option: VAR
| VAR *
| VAR !
type: INT
| LONG
| ULONG
| INTMAX
| UINTMAX
| FLOAT
| DOUBLE
| STRING
| CHAR
| FLAG
default: ALNUM
| CHAR_VAL
| QUOTED_STR
range: [ contiguous_range ]
contiguous_range: ALNUM range_spec more_range
| range_spec more_range
more_range: ALNUM
| C_VAR
|
range_spec: ..
| ...
callback: VAR ()
description: QUOTED_STR
usages: /* empty */
| usages usage
| usage
usage: USAGE_STR
code_lines: code_lines code_line
| code_line
code_line: single_code_line CODE_END
| CODE_END
;
single_code_line: CODE_LINE
| OPEN_ROUND_BRACE
| CLOSE_ROUND_BRACE
| single_code_line single_code_line
@end example
@c CHAPTER
@node The Future, Some History, Genparse File Syntax, Top
@chapter The Future
While there's practically no limit to the number of enhancements that
could be made to Genparse, I'll limit this section to a number of
features that actually have a chance of being implemented.
@itemize @bullet
@item
Back up output files before overwriting them. Minimally, old callback
files should be saved, because those are meant to be modified by the
user. This isn't hard, but I'd like to do it "right" by encapsulating
the functionality into a general-purpose file manipulation class.
@item
Enumerated types for strings. Currently command line strings are not
checked for any sort of validity. This would allow the user to specify
a list of valid values for a particular string. The syntax would
probably be like an enumerated type in C.
@item
A way to distinguish between optional and mandatory non-option
command line parameters.
@item
Support for more output languages. Perhaps tcl and perl first, and
other scripting languages afterwards. This should be pretty easy to
do since it would only require adding the appropriate member functions
to the command line parameter list class and a little bit of supporting
code here and there.
@item
Place @command{getopt.h}, @command{getopt.c}, and
@command{getopt_internal.c} in a neutral shared directory so that others
can copy them locally for their own use.
@end itemize
@c CHAPTER
@node Some History, Index, The Future, Top
@chapter Some History
@cindex History
Long, long ago in a lab far, far away, I became frustrated with the time
required to write command line parsing routines, even with
@code{getopt ()}, for all of the new programs that I developed. I felt
that it was tedious work that offered too many opportunities to cut
corners and produce error-prone code. In late 1997, the seeds of
Genparse fell together in my head, and I released version 0.1, written in
C, on New Year's Day, 1998. The only output language supported was C,
and it did not allow long options. Parameter types were limited to
flags, integers, floats, and strings, and range checking was supported.
It soon became clear that although Genparse was fairly useful (I was
already using it to create parsers for my own projects), it was severely
limited and could use a number of additional features. With the help of
a handful of people who provided feedback and constructive criticism,
version 0.2 was soon released. New features included a more flexible
Genparse file format (essentially, the current format) which was
parsed by @command{lex} and @command{bison} rather than by my C code.
Parameter descriptions and callback functions were now supported.
A few bug fixes later, version 0.2.2 was released. It was to remain
current for over a year. In June 1999, I revisited Genparse to add the
@code{#include} and @code{#mandatory} directives, as well as to clean
up the code a bit and perform some minor bug stomping. The resulting
version 0.3 was distributed with Debian/GNU Linux.
During my revision that produced 0.3, I became aware of the acute coding
slop that had evolved. To call the output functions "spaghetti logic"
would have been an understatement. Naturally, I needed to modularize
Genparse, and the best way of doing so seemed to be a re-write in C++.
In December 1999, I undertook this task. The code became separated
into three logical sections:
@itemize @bullet
@item
The parser, a @command{bison} grammar with supporting code.
@item
An internal representation, encapsulated in a C++ class.
@item
Output functions for each supported language, built into the C++ class.
@end itemize
This design greatly improved the extensibility of Genparse. In order to
support a new output language, one only needs to add appropriate member
functions to the C++ class. This implementation became version 0.4.
An important part of 0.4 was support for C++ as an output language.
Rather than returning a @code{struct} containing the command line
parameter values, a C++ command line parser would be encapsulated by a
C++ class. The user would call the member functions of this class to
access parameter values, making for a cleaner interface than C can
support.
Version 0.4 also included a more comprehensive set of test suites along
with the documentation that you currently are reading.
In Fall 2000, I revisited Genparse. Version 0.4 did not support options
with no short form, and thus was limited to 52 options at most. Version
0.5 lifted this restriction, included @command{<stdlib.h>} rather than
the depreciated @command{<malloc.h>} in output files, and fixed up
user-defined include files so that they worked with quotes as well as
"<>". Also, I finally figured out how to get Genparse to reliably
compile on systems both with and without the @command{getopt_long ()}
function.
Version 0.5.1 fixed a few problems with the lexical analyzer that
resulted in default values for floats not being used properly. This
version also eliminated the mandatory use of the @option{-q} option.
@node Index, , Some History, Top
@chapter Index
@printindex cp
@bye
|