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
|
#!/usr/bin/env perl
# Flex(1) XML processor scanner generator.
# Copyright (C) 1999 Kristoffer Rose. All rights reserved.
#
# This file is part of the FleXML XML processor generator system.
# Copyright (C) 1999 Kristoffer Rose. All rights reserved.
# Copyright (C) 2003-2006 Martin Quinson. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place, Suite 330, Boston, MA 02111-1307 USA.
use warnings;
my $Id = '$Id: flexml.pl,v 1.62 2007/10/11 10:00:14 mquinson Exp $ ';
$Id =~ s/\s*\$\s*//go;
# IMPORTS.
use Getopt::Long;
use LWP::UserAgent;
use Carp qw/cluck confess/;
use strict;
# FILES (must be global).
use vars qw/ $SKELETON /; # the skeleton scanner
use vars qw/ $SCANNER /; # generated XML processor (+ application if requested)
use vars qw/ $HEADER /; # generated XML processor API header
use vars qw/ $ACTIONS /; # the actions file
use vars qw/ $APPLICATION /; # generated XML application
$SKELETON = "./skel"; # default value
# OPTIONS (and other globals).
my $Use; # usage string
my $debug; # -d option flag
my $verbose; # -v option flag
my $lineno; # -L option flag
my $nofail; # -X option flag
my $quiet_parser; # -q option flag
my $uri; # -u option uri
my $pubid; # -p option string
my $sysid; # --sysid option string
my $stacksize=100000; # -b option flag
my $tagprefix=""; # -P option flag
my $actbin="./flexml-act"; # -T option content
my $init_header=""; # -i option string
my $header; # -H option flag/content
my $dummy; # -D option flag/content
my $standalone; # -A option flag/content
my $scanner; # -S option flag/content
my $actions; # -a option content
my $dryrun; # -n option flag
my $dtd; # DTD file name (or URI)
my $dtdrevision; # DTD version pruned from file
my $cdtd; # C identifier derived from DTD name
my @inputs = (); # input data stack (array of arrays of lines)
my @inputnames = (); # names of files on input data stack
my @inputlinenos = (); # line number in input files
# DTD regular expressions (extended to not mess up the counting).
my $NameChar = '[A-Za-z0-9.:_-]';
my $Name = "[A-Za-z_:]$NameChar*";
my $Names = "$Name(?:\\s+$Name)*";
my $Nmtoken = "$NameChar+";
my $Nmtokens = "$Nmtoken(?:\\s+$Nmtoken)*";
my $Eq = '\s*=\s*';
my $Literal = '(?:\'[^\']*\'|"[^"]*")';
# DTD DESCRIPTION STRUCTURES.
my %source = (); # DTD source lines associated to tag and tag/attribute.
my @tags = (); # Tags of the DTD.
my %roottags = (); # Tags that may be the root tag.
my %ctag = (); # C variable name of each tag.
my %allstates = (); # all existing states are key of this hash
my %states = (); # $states{tag} is list of states used by tag element.
my %emptytrans = (); # $emptytrans{state} contains empty transitions in automaton.
my %instates = (); # $instates{tag} is list of states for element start/empty tag.
my %startstate = (); # $startstate{tag} is the state entered after the start tag.
my %endstates = (); # $endstates{tag} is list of states for element end tag.
my %exittrans = (); # $exittrans{tag} is state transitions after end tag.
my %empty = (); # $empty{tag} == true if the tag may be empty.
my %properempty = (); # $empty{tag} == true if the tag is declared EMPTY
my %any = (); # $any{tag} == true if the tag has ANY contents.
my %mixed = (); # $mixed{tag} == true if the tag has Mixed (or ANY) contents.
my %children = (); # $children{tag} == true if the tag has Element contents
my %inmixed = (); # $inmixed{tag} == true if the tag occurs *in* Mixed contents.
my @attributes = (); # Attributes of the DTD.
my %catt = (); # C variable name for attribute.
my %atttype = (); # XML AttType (type) of tag/attribute
my %enumtype = (); # whether the tag/attribute is an enumeration type
my %literaltype = (); # whether the tag/attribute is a tokenized type
my %entitytype = (); # whether the tag/attribute is of entity type
my %typeof = (); # C type of tag/attribute
my %attdef = (); # XML AttDef (default value) of tag/attribute
my %required = (); # true if tag/attribute is required
my %fixed = (); # true if tag/attribute has fixed default
my %initof = (); # C initial attribute value of tag/attribute, if any
my %attlist = (); # $attlist{tag} is comma-separated list of attribute
# names allowed in tag elements.
my %withattr = (); # $withattr{attribute} is comma-separated list of
# elements within which the tag element may occur.
my %entity = (); # general entity table (C strings)
my %parameter = (); # parameter entity table (raw string)
my %external = (); # external entity table (uris)
my %startok = (); # start tag action already dumped
my %endok = (); # end tag action already dumped
# UTILITIES.
sub printsource { # Print source lines of argument.
my ($key) = @_;
local $_ = $source{$key};
return if not $_;
s:[*][/]:* /:g; # avoid */ in output [sic]
s/\n/\n * /mg;
print "\n /* " . $_ . " */\n";
}
sub cquote { # Convert a string to C source format.
local ($_) = @_;
s/\\/\\\\/go; # First replace \ to avoid interference...
s/\"/\\\"/go;
s/\n/\\n/go; s/\r/\\r/g; s/\t/\\t/g; s/\f/\\f/go;
s/[\0-\037\200-\377]/ sprintf("\\%.3o",ord($&)) /ge;
$_
}
sub variablify { # Change XML Name to legal C variable name.
local ($_) = @_;
s|-|_d_|go;
s|:|_c_|go;
s|/|__|go;
$_
}
sub redistribute { # Print C comment with generated file "license".
# Notice that this is not intended to affect
# flexml.pl itself.
my ($pre) = @_;
print <<EOT;
$pre This program was generated with the FleXML XML processor generator.
$pre FleXML is Copyright (C) 1999-2005 Kristoffer Rose. All rights reserved.
$pre FleXML is Copyright (C) 2003-2006 Martin Quinson. All rights reserved.
$pre ($Id).
$pre
$pre There are two, intertwined parts to this program, part A and part B.
$pre
$pre Part A
$pre ------
$pre
$pre Some parts, here collectively called "Part A", are found in the
$pre FleXML package. They are Copyright (C) 1999-2005 Kristoffer Rose
$pre and Copyright (C) 2003-2006 Martin Quinson. All rights reserved.
$pre
$pre You can redistribute, use, perform, display and/or modify "Part A"
$pre provided the following two conditions hold:
$pre
$pre 1. The program is distributed WITHOUT ANY WARRANTY from the author of
$pre FleXML; without even the implied warranty of MERCHANTABILITY or
$pre FITNESS FOR A PARTICULAR PURPOSE.
$pre
$pre 2. The program distribution conditions do not in any way affect the
$pre distribution conditions of the FleXML system used to generate this
$pre file or any version of FleXML derived from that system.
$pre
$pre Notice that these are explicit rights granted to you for files
$pre generated by the FleXML system. For your rights in connection with
$pre the FleXML system itself please consult the GNU General Public License.
$pre
$pre Part B
$pre ------
$pre
$pre The other parts, here collectively called "Part B", and which came
$pre from the DTD used by FleXML to generate this program, can be
$pre distributed (or not, as the case may be) under the terms of whoever
$pre wrote them, provided these terms respect and obey the two conditions
$pre above under the heading "Part A".
$pre
$pre The author of and contributors to FleXML specifically disclaim
$pre any copyright interest in "Part B", unless "Part B" was written
$pre by the author of or contributors to FleXML.
$pre
EOT
}
sub api_functions { # Print XML application interface functions.
my ($pre,$post) = @_;
print "/* XML application entry points. */\n" if @tags;
for (@tags) {
print $pre . "void STag_${tagprefix}$ctag{$_}(void)$post\n" unless $startok{$_};
print $pre . "void ETag_${tagprefix}$ctag{$_}(void)$post\n" unless $endok{$_};
}
}
sub api_types { # Print XML application interface types.
print "/* XML application data. */\n" if %atttype;
for (keys %atttype) {
if (m.($Nmtoken)[/]($Nmtoken).xo) {
my ($tag,$attribute) = ($1,$2);
print "typedef $typeof{$_} AT_${tagprefix}$ctag{$tag}_$catt{$attribute};\n";
print "#define AU_${tagprefix}$ctag{$tag}_$catt{$attribute} NULL\n"
if not $enumtype{$_};
}
}
}
sub api_data { # Print XML application interface parameters.
my ($pre) = @_; # pre should be a storage class spec like 'static' or 'extern'
print "/* FleXML-provided data. */\n";
print $pre . "int ${tagprefix}pcdata_ix;\n";
print "extern char *${tagprefix}bufferstack;\n";
print "#define ${tagprefix}pcdata (${tagprefix}bufferstack + ${tagprefix}pcdata_ix)\n";
for (keys %atttype) {
if (m.($Nmtoken)[/]($Nmtoken).xo) {
print $pre . "AT_${tagprefix}$ctag{$1}_$catt{$2} AX_${tagprefix}$ctag{$1}_$catt{$2};\n";
print "#define A_${tagprefix}$ctag{$1}_$catt{$2} ";
if ($enumtype{$_}) {
print "AX_${tagprefix}$ctag{$1}_$catt{$2}\n";
}
else {
print "(${tagprefix}bufferstack + AX_${tagprefix}$ctag{$1}_$catt{$2})\n";
}
}
}
}
sub expandparametersat { # Expand parameter entities in $_ at $place.
my ($place) = @_;
while ( m/$place\s*%($Name);/ ) {
if (defined $parameter{$1}) {
s/$place(\s*)%($Name);/ ' '. $1 . $parameter{$2} . ' ' /xe;
}
}
}
sub geturl { # Insert contents of URL into input stream at current point
my ($url) = @_;
$url = "file:$url" if not $url =~ m/:/;
local $_ = $url;
s.([^/:]*[/:])*..g;
s/\.dtd$//;
print STDOUT "Fetching URL <$url>.\n" if $verbose;
my $ua = new LWP::UserAgent; # Create a user agent object
$ua->agent("FleXML/1 " . $ua->agent);
my $req = new HTTP::Request GET => $url; # Create a request
my $res = $ua->request($req); # Pass request to the user agent and get a response
if ($res->is_error) {
die place()."URL <$url> could not be fetched.\n";
}
# Make the data available...
push @inputs, [ split /\r?\n/, $res->content ];
if (@{$inputs[$#inputs]}) {
push @inputnames, "$url";
push @inputlinenos, 0;
}
else {
pop @inputs; # oops, empty.
}
# print STDOUT "Testing:\n";
# my $i = 0;
# for my $ref (@inputs) {
# print STDOUT " inputs[" . $i++ . "] =\n";
# for my $line (@{$ref}) {
# print " | $line\n";
# }
# }
# $i = 0;
# for my $name (@inputnames) {
# print STDOUT " inputnames[" . $i++ . "] = `$name'\n";
# }
# $i = 0;
# for my $no (@inputlinenos) {
# print STDOUT " inputlinenos[" . $i++ . "] = `$no'\n";
# }
}
# add attribute to list of all default attributes
my @default_attributes;
my $next_att_loc = 1;
sub add_def_att {
my ($att) = @_;
my $retval = $next_att_loc;
push @default_attributes, ($att);
$next_att_loc += length($att) + 1;
return $retval;
}
sub nextline { # return one input line
return undef unless @inputs;
my $line = shift @{$inputs[$#inputs]};
$inputlinenos[$#inputs]++;
while (@inputs and not @{$inputs[$#inputs]}) { # discard exhausted inputs
pop @inputs;
pop @inputnames;
pop @inputlinenos;
}
return $line;
}
sub place {
if (@inputs) {
local $_ = "\"$inputnames[$#inputs]\", line $inputlinenos[$#inputs]: ";
s/"file:/"/;
return $_;
}
else {
return "";
}
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# extractcp($str) - Split argument in one cp[48] (content particles) and the rest.
#
# returns ($cp,$rest)
#
sub extractcp {
# $_ stores the remainder of the string we're looking at
local ($_) = @_;
# shack - I noticed that the 'match one Name' pattern below
# does not accept leading spaces, but the ( pattern does
# This is a little warning that will enlighten me if this occurs
m/^\s+/ and do {
cluck("extractcp matching leading spaces! '$_'");
};
if ( m/^($Name[+?*]?)\s*/o ) { # match one Name
return ($1,$'); #'
}
if ( m/^\s*\(/o ) { # match the start of a choice or seq
# build up one CP my matching parens
my $cp = '('; $_ = $'; #'
my $level = 1;
# match nested parenthesis
while ($level > 0 and $_) {
if ( m/^\s*\(\s*/o ) { # open paren
$level++;
$cp .= '(';
$_ = $'; #'
}
elsif ( m/^\s*(\)[+?*]?)\s*/o ) { # close paren
$level--;
$cp .= $1;
$_ = $'; #'
}
elsif ( m/^\s+/o ) { # skip white space
$_ = $'; #'
}
else { # everything else
m/[^()\s]+/o;
$cp .= $&;
$_ = $'; #'
}
}
return ($cp,$_);
}
confess ("should not get here!");
}
my $statecounter;
sub analysechildren { # Analyse DTD children specification; return
# true if it may be empty. Uses global $statecounter.
my ($tag,$re,$in,$out) = @_;
$allstates{$in} = 1;
$allstates{$out} = 1;
print "analysechildren [ $tag, $re, $in, $out ] \n" if $debug;
local $_ = $re;
if ( m/^\s*($Name)\s*$/o ) { # tag
my $thetag = $1;
my %ins = ();
if (exists $instates{$thetag}) {
for (split /,/,$instates{$thetag}) { $ins{$_} = 'true'; }
}
$ins{$in} = 'true';
$instates{$thetag} = join(',',keys %ins);
$exittrans{$thetag} .= ($exittrans{$thetag}?',':'') . "$in=>$out" if $in ne $out;
return undef;
}
elsif ( m/^((.|\n)+)\?\s*$/o ) { # re ?
$emptytrans{$in} .= ($emptytrans{$in}?',':'') . $out unless $in eq $out;
analysechildren($tag,$1,$in,$out);
return 'true';
}
elsif ( m/^((.|\n)+)\+\s*$/o ) { # re +
my $re = $1;
my $s1 = "S_$ctag{$tag}_" . (++$statecounter);
my $s2 = "S_$ctag{$tag}_" . (++$statecounter);
$states{$tag} .= ",$s1,$s2";
$emptytrans{$in} .= ($emptytrans{$in}?',':'') . $s1;
$emptytrans{$s2} = "$s1,$out";
return analysechildren($tag,$re,$s1,$s2);
}
elsif ( m/^((.|\n)+)\*\s*$/o ) { # re *
return analysechildren($tag,"$1+?",$in,$out);
}
elsif ( m/^\s*\(\s*((.|\n)+)\s*\)\s*$/xo ) { # choice or seq
local $_;
my $cp;
($cp,$_) = extractcp($1);
if ( m/^\s*$/ ) { # () with single member.
return analysechildren($tag,$cp,$in,$out);
}
elsif ( m/^\s*([|,])\s*/m ) {
my $type = "[$1]";
my $maybeempty = ($type eq '[,]');
my $state = $in;
while ( m/^\s*$type\s*/ ) {
$_ = $'; #'
if ($type eq '[|]') { # $cp is choice
$maybeempty = 'true' if analysechildren($tag,$cp,$in,$out);
}
else { # $cp is seq component
my $oldstate = $state;
$state = "S_$ctag{$tag}_" . (++$statecounter);
$states{$tag} .= ",$state";
$maybeempty = undef unless analysechildren($tag,$cp,$oldstate,$state);
}
($cp,$_) = extractcp($_);
}
# Last cp needs special treatment in sequence.
if ($type eq '[|]') { # $cp is choice
$maybeempty = 'true' if analysechildren($tag,$cp,$in,$out);
}
else { # $cp is seq component
$maybeempty = undef unless analysechildren($tag,$cp,$state,$out);
}
$emptytrans{$in} .= ($emptytrans{$in}?',':'') . $out
if $maybeempty and $in ne $out;
return $maybeempty unless $_;
}
}
die place()."DTD element `$tag' has nonsense fragment `$_'.\n";
}
# OPTIONS PROCESSING (explained in manual).
# Parse options.
$Use = "Usage: flexml [-ASHDvdqnLXV] [-s skel] [-T actbin] [--sysid sysid] "
. "[-p pubid] [-u uri] [-i init_header]\n"
. " [-b stack_increment] [-r roottags] [-a actions] [-P prefix] name[.dtd]";
sub show_version {
exit 0;
}
Getopt::Long::Configure ("bundling");
GetOptions(
# Debugging and verbosity
"debug|d" => \$debug,
"verbose|v" => \$verbose,
"quiet|q" => \$quiet_parser,
# Version!
"version|V" => sub { print "FleXML version $Id.\n"; exit 0; },
# dry-run ?
"dry-run|n" => \$dryrun,
# Line numbers?
"lineno|L" => \$lineno,
# Exit without fail message?
"nofail|X" => \$nofail,
# Specific root tags?
"root-tags|r=s" => sub {
for (split ',',$_[1]) { $roottags{$_} = 'true'; }
},
# Specific stack size?
"stack-increment|b=s" => \$stacksize,
# Specific tagprefix?
"tag-prefix|P=s" => sub { $tagprefix = $_[1]."_" },
# Specific actbin? (internal use)
"act-bin|T=s" => \$actbin,
# Set skeleton scanner file name and check it is readable (if needed).
"skel|s=s" => sub {
$SKELETON = $_[1];
die "$0: No skeleton file $SKELETON.\n" if not -r $SKELETON and $_[1];
},
# Set document type URI and PUBID.
"uri|u=s" => \$uri,
"pubid|p=s" => \$pubid,
"sysid=s" => \$sysid,
# name of header file to be included in initial section of generated .l file
"init_header|i=s" => \$init_header,
# What to generate
"header|H:s" => sub { $header = $_[1] || 'true' },
"dummy|D:s" => sub { $dummy = $_[1] || 'true' },
"stand-alone|A" => \$standalone,
"scanner|S:s" => sub { $scanner = $_[1] || 'true' },
"actions|a=s" => \$actions
);
print "FleXML version $Id.\n" if $verbose;
# Set DTD file name...and extract prefix for later
my $prefix = $ARGV[0];
if (defined $prefix and $#ARGV == 0) {
$prefix =~ s/\.dtd$//;
$dtd = "$prefix.dtd"; # Require .dtd extension on DTD
geturl($dtd); # Read the DTD
$prefix =~ s|^([^:/]*[:/])*||;
$cdtd = variablify($prefix);
}
else {
die "$Use\n";
}
# Selection options: If none of -SHDA specified then default to -SH.
# Furthermore -a implies -D.
$scanner = $header = 'true' unless ($scanner or $header or $dummy or $standalone);
$dummy ||= $actions unless $standalone;
# Set default (DTD-based) output file names.
$SCANNER = (!defined($scanner)) || $scanner eq 'true' ? "$prefix.l" : $scanner;
$HEADER = (!defined($header)) || $header eq 'true' ? "$prefix.h" : $header;
$APPLICATION = (!defined($dummy)) || $dummy eq 'true' ? "$prefix-dummy.c" : $dummy;
# Set actions=based output file names, if any.
if ($ACTIONS = $actions) {
$actions =~ s/\.[a-z]+$//;
$APPLICATION = "$actions.c";
}
# Stand-alone applications...
if ($standalone) {
die "$0: -A conflicts with -SHD.\n" if ($scanner or $header or $dummy);
$SCANNER = $APPLICATION;
$SCANNER =~ s/\.c$/.l/;
}
# Dry-run?
if ($dryrun) {
$standalone = $scanner = $header = $dummy = undef;
}
# PARSE DTD.
print STDOUT "Processing DTD in $dtd.\n" if $verbose;
$_ = ''; # Current entry
while (@inputs) { # While there are lines...
my $orig = "$_"; # current source line(s)
# Skip spaces and complete comments (but save as source).
do {
# Skip blank lines.
$_ = nextline() while @inputs and m/^\s*$/;
# If we're looking at a parameter or external entity then expand it.
if ( m/^\s*%($Name);/ ) {
my $ent = $1;
if ($parameter{$ent}) {
expandparametersat('^');
}
elsif ($external{$ent}) {
$_ = $'; #'
geturl($external{$ent});
}
else {
die "Unknown entity `%$ent;'\n";
}
}
# Skip (but save) comments.
while ( m/^\s*<!--/ ) {
until (m/-->/ or not @inputs) { $_ .= "\n" . nextline(); }
# Extract first DTD version number...
if ( not $dtdrevision and /\$(Id|Header|Revision): [^\$]*\$/ ) {
$dtdrevision = "$&";
$dtdrevision =~ s/\s*\$\s*//go;
}
# Remove the comment to read on to next nonblank (but save as
# source).
$orig .= ($orig?"\n":"").$1 if s/^\s*(<!--([^-]|-[^-]|--[^>])*-->)\s*//;
}
s/^\s*//;
} until $_ or not @inputs;
# If we're looking at a parameter or external entity then expand and retry.
if ( m/^\s*%($Name);/ ) {
my $ent = $1;
if ($parameter{$ent}) {
expandparametersat('^');
}
elsif ($external{$ent}) {
$_ = $'; #'
geturl($external{$ent});
next;
}
else {
die "Unknown entity `\%$ent;'\n";
}
}
die place()."Nonsense `$_'.\n" if /^[^<]/ or /^<[^!]/;
# Read on until a full DTD <!...> or <?...?> entry is available.
until (m/^\s*<![^>]*>/o or m/^\s*<[?]([^?]|[?][^>])*[?]>/o or not @inputs) {
my $line = nextline();
$orig .= ($orig?"\n":"") . $line;
$_ .= "\n" . $line;
}
unless ( m/^\s*<![^>]*>/o or m/^\s*<[?]([^?]|[?][^>])*[?]>/o ) {
last if not @inputs;
die place()."Could not find end of declaration.\n";
}
# Clean out in $orig.
$orig =~ s/\n+/\n/g;
$orig =~ s/^\n*//g;
$orig =~ s/\n*$//g;
print STDOUT " [$_]\n" if $debug;
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Processing instruction.
if ( m/^\s*<[?]([^?]|[?][^>])*[?]>\s*/o ) {
print STDERR place()."Warning: ignoring processing instruction $&.\n";
$_ = $'; #'
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Parse element declarations.
elsif ( m/^<!ELEMENT\s+($Name)\s+([^>]*)>\s*/xo ) {
my ( $tag, $token_source ) = ( $1, $2 );
# strip off the matched code from the beginning of $_
$_ = $'; #'
# place the newly found tag into the list of tags @tags
die place()."Repeated element $tag.\n" if exists $source{$tag};
# ????? - most of the time $orig is undef
$source{$tag} = "$orig";
push @tags, $tag;
# Create C-friendly tag names.
$ctag{$tag} = variablify($tag) unless $ctag{$tag};
my $c = $ctag{$tag};
# start looking at the token_source ($2)
local $_ = $token_source;
expandparametersat(''); s/^\s+//;
# All elements should be followed by nothing when at the root.
# IF there is a list of roottags ($0 -r ..,..), then only add
# the exittrans if it is in the list
$exittrans{$tag} .= ($exittrans{$tag}?',':'') . "ROOT_${tagprefix}$c=>EPILOG"
if not %roottags or $roottags{$tag};
# Handle element declaration.
if ( m/^EMPTY\s*$/o ) {
$empty{$tag} = 'true';
$properempty{$tag} = 'true';
$states{$tag} = "E_$c";
$startstate{$tag} = "E_$c";
$endstates{$tag} = "E_$c";
}
elsif ( m/^ANY\s*$/o ) {
$any{$tag} = 'true';
$mixed{$tag} = 'true';
$empty{$tag} = 'true';
$states{$tag} = "IN_$c";
$startstate{$tag} = "IN_$c";
$endstates{$tag} = "IN_$c";
}
elsif ( m/^\(\s*\#PCDATA\s*\)\s*$/o
or m/^\(\s*\#PCDATA\s*((\|\s*$Name\s*)*)\)\*\s*$/xo ) {
$mixed{$tag} = 'true';
$empty{$tag} = 'true';
if ($1) {
my $desc = $1;
$desc =~ s/^\s*\|\s*//o;
for (split /\s*\|\s*/,$desc) {
$instates{$_} .= ($instates{$_}?',':'') . "IN_$c";
$inmixed{$_} = 'true';
}
}
$states{$tag} = "IN_$c";
$startstate{$tag} = "IN_$c";
$endstates{$tag} = "IN_$c";
}
else {
$children{$tag} = 'true';
$statecounter = 0;
$states{$tag} = "S_$c";
$startstate{$tag} = "S_$c";
$empty{$tag} = 'true' if analysechildren($tag,$_,"S_$c","E_$c");
$states{$tag} .= ",E_$c";
$endstates{$tag} = "E_$c";
}
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Parse attribute declarations.
elsif ( m/^<!ATTLIST\s+($Name)\s+([^>]*)>\s*/o ) {
$_ = $'; #'
{
my $tag = $1;
local $_ = $2;
expandparametersat(''); s/^\s+//;
# Repeat while there are attribute declarations.
while ( s/^($Name)\s+([A-Z]+|\(\s*$Nmtoken\s*(?:\|\s*$Nmtoken\s*)*\))
(?:\s+(\#IMPLIED|\#REQUIRED|(?:\#FIXED\s+)?$Literal))?\s*//xo ) {
my ($attribute,$type,$default) = ($1,$2,$3);
if ($atttype{"$tag/$attribute"}) {
print place()."Warning: Redeclaration of element $tag attribute $attribute ignored.\n";
}
else {
if ($orig) { # to only print the source once once
$source{"$tag/$attribute"} = "$orig";
$orig = '';
}
$ctag{$tag} = variablify($tag) unless $ctag{$tag};
$catt{$attribute} = variablify($attribute) unless $catt{$attribute};
# Add atribute to the appropriate lists.
$attlist{$tag} .= ($attlist{$tag}?',':'') . "$attribute";
if ($withattr{$attribute}) {
$withattr{$attribute} .= ",$tag";
}
else {
push @attributes, $attribute;
$withattr{$attribute} = "$tag";
}
# Analyse default value.
if (defined $default) {
if ($default eq '#REQUIRED') {
$required{"$tag/$attribute"} = 'true';
$default = undef;
}
elsif ($default eq '#IMPLIED') {
$default = undef;
}
else {
$fixed{"$tag/$attribute"} = 'true' if $default =~ s/\#FIXED\s+//o;
$default =~ s/^'([^'']*)'$/$1/o unless $default =~ s/^"([^""]*)"$/$1/o;
}
}
# Store attribute default string and type.
$attdef{"$tag/$attribute"} = $default if $default;
$atttype{"$tag/$attribute"} = $type;
# Handle enumeration types...
if ( $type =~ m/^\(((.|\n)*)\)$/x ) {
local $_ = $1;
s/\s+//go;
s/\|/,/go;
$enumtype{"$tag/$attribute"} = "$_";
s/$Nmtoken/ "A_${tagprefix}$ctag{$tag}_$catt{$attribute}_" . variablify($&) /xge;
my $undefined = "AU_${tagprefix}$ctag{$tag}_$catt{$attribute}";
s/^/enum \{ $undefined, /o;
s/$/ \}/o;
$typeof{"$tag/$attribute"} = "$_";
if ($default) {
$initof{"$tag/$attribute"} = "A_${tagprefix}$ctag{$tag}_$catt{$attribute}_"
. variablify($default);
}
else {
$initof{"$tag/$attribute"} = "$undefined";
}
}
# ...and string/token types.
else {
$typeof{"$tag/$attribute"} = 'int';
if ($default) {
$initof{"$tag/$attribute"} = add_def_att($default);
}
else {
$initof{"$tag/$attribute"} = '0';
}
# Special treatment of token types.
if ( $type eq 'ID' or $type eq 'IDREF' ) {
$literaltype{"$tag/$attribute"} = '{Name}';
print STDERR place()."Warning: attribute type `$type' not validated.\n";
}
elsif ( $type eq 'IDREFS' ) {
$literaltype{"$tag/$attribute"} = '{Names}';
print STDERR place()."Warning: attribute type `$type' not validated.\n";
}
elsif ( $type eq 'NMTOKEN' ) {
$literaltype{"$tag/$attribute"} = '{Nmtoken}';
}
elsif ( $type eq 'NMTOKENS' ) {
$literaltype{"$tag/$attribute"} = '{Nmtokens}';
}
elsif ( $type eq 'ENTITY' ) {
#die place()."ENTITY attribute type unimplemented.\n";
$literaltype{"$tag/$attribute"} = '{Name}';
print STDERR place()."Warning: attribute type `$type' not validated.\n";
}
elsif ( $type eq 'ENTITIES' ) {
#die place()."ENTITIES attribute type unimplemented.\n";
$literaltype{"$tag/$attribute"} = '{Names}';
print STDERR place()."Warning: attribute type `$type' not validated.\n";
}
elsif ( $type ne 'CDATA' ) {
die place()."Unknown AttType `$type'.\n";
}
}
}
expandparametersat('^'); s/^\s+//; # to expand next set of declarations...
}
die place()."Nonsense ($_) in attribute list.\n" if $_;
}
$orig = ''; # in case there were no attributes...
}
# Parse internal parameter entity declaration.
elsif ( m/^\s*<!ENTITY\s+%\s+($Name)\s+'([^'']*)'\s*>\s*/xo
or m/^\s*<!ENTITY\s+%\s+($Name)\s+"([^""]*)"\s*>\s*/xo ) {
$_ = $'; #'
$source{"%$1;"} = "$orig"; $orig = ''; # cycle
my $name = $1;
local $_ = $2;
die "Entity `%$name;' doubly defined.\n" if $parameter{$name} or $external{$name};
expandparametersat(''); s/^\s+//; s/\s+$//;
s/\&\#([0-9]+|x[0-9a-fA-F]+);/
(substr($1,0,1) eq 'x' ? chr(hex(substr($1,1))) : chr($1)) /ge;
$parameter{$name} = $_;
}
# Parse external parameter entity declaration.
elsif ( m/^<!ENTITY\s+%\s+($Name)\s+SYSTEM\s+'([^'']*)'\s*>\s*/xo
or m/^<!ENTITY\s+%\s+($Name)\s+SYSTEM\s+"([^""]*)"\s*>\s*/xo
or m/^<!ENTITY\s+%\s+($Name)\s+PUBLIC\s+$Literal\s+'([^'']*)'\s*>\s*/xo
or m/^<!ENTITY\s+%\s+($Name)\s+PUBLIC\s+$Literal\s+"([^""]*)"\s*>\s*/xo ) {
$_ = $'; #'
$source{"%$1;"} = "$orig"; $orig = ''; # cycle
my $name = $1;
die "Entity `%$name;' doubly defined.\n" if $parameter{$name} or $external{$name};
$external{$name} = $2;
}
# Parse internal general entity declarations.
elsif ( /^<!ENTITY\s+($Name)\s+['"]([^''""]*)["']\s*>\s*/xo ) {
$_ = $'; #'
$source{"&$1;"} = "$orig"; $orig = ''; # cycle
my $name = $1;
local $_ = $2;
die "Entity `&$name;' doubly defined.\n" if $entity{$name};
s/\&\#([0-9]+|x[0-9a-fA-F]+);/
(substr($1,0,1) eq 'x' ? chr(hex(substr($1,1))) : chr($1)) /ge;
$entity{$name} = cquote($_);
}
# Unrecognised declaration.
else {
die place()."Unrecognized declaration.\n";
}
}
# Post-process DTD.
print STDOUT "Post-processing DTD.\n" if $verbose;
# Add transitive empty transitions until none can be found.
{ my $changed = 'true';
while ($changed) {
$changed = undef;
for my $from (keys %emptytrans) {
my %tos = (); for (split /,/,$emptytrans{$from}) { $tos{$_} = 'true'; }
for my $to (keys %tos) {
if (exists $emptytrans{$to}) {
for my $next (split /,/,$emptytrans{$to}) {
if (not $tos{$next}) {
$changed = $tos{$next} = 'true';
}
}
}
}
$emptytrans{$from} = join ',',keys %tos;
}
}
}
# Complete all states with their `empty' equivalents.
for my $tag (@tags) {
# Complete and prune instates and endstates...
my %ins = ();
if (exists $instates{$tag}) {
for (split ',',$instates{$tag}) { $ins{$_} = 'true'; }
}
my %ens = ();
if (exists $endstates{$tag}) {
for (split ',',$endstates{$tag}) { $ens{$_} = 'true'; }
}
# ...and exit transitions...
my %exits = ();
if (exists $exittrans{$tag}) {
for (split ',',$exittrans{$tag}) { m/^($Name)=>($Name)$/o; $exits{$1} = $2; }
}
# Encode ANY as Mixed contents with all tags permitted.
for (keys %any) { $ins{"IN_$_"} = 'true'; }
# For each empty transition A->B add A where B occurs.
for my $from (keys %emptytrans) {
for my $to (split /,/,$emptytrans{$from}) {
$ins{$from} = 'true' if $ins{$to};
$ens{$from} = 'true' if $ens{$to};
$exits{$from} = $exits{$to} if $exits{$to};
}
}
# Completion done...now store'em right back.
$instates{$tag} = join ',', keys %ins if %ins;
$endstates{$tag} = join ',', keys %ens if %ens;
$exittrans{$tag} = join ',', map "$_=>$exits{$_}", keys %exits if %exits;
}
if (not %roottags) {
for (@tags) { $roottags{$_} = 'true'; }
}
# Handling prefix
if(length($tagprefix)) {
my($h,$k);
my(@hashlist) = (\%states,\%emptytrans,\%instates,\%startstate,
\%endstates,\%exittrans);
foreach $h (@hashlist) {
foreach $k (keys (%$h)) {
$$h{$k} =~ s/^E_/E_${tagprefix}/g;
$$h{$k} =~ s/,E_/,E_${tagprefix}/g;
$$h{$k} =~ s/>E_/>E_${tagprefix}/g;
$$h{$k} =~ s/^S_/S_${tagprefix}/g;
$$h{$k} =~ s/,S_/,S_${tagprefix}/g;
$$h{$k} =~ s/>S_/>S_${tagprefix}/g;
}
}
my %tmp = ();
foreach $k (keys %allstates) {
$k =~ s/^E_/E_${tagprefix}/;
$k =~ s/^S_/S_${tagprefix}/;
$tmp{$k} = 1;
}
%allstates = %tmp;
}
# Debugging: show DTD representation.
if ($debug) {
print STDOUT "DTD debug output:\n" if $verbose;
sub printhash {
my ($name) = @_;
my ($k,$v);
my $out = '';
while ( ($k, $v) = each(%$name) ) {
$out .= "\n $k => '" . ($v || "undef")."'";
}
return $out;
}
# display the options we got
print "debug=".($debug||'undef')."\n";
print "verbose=".($verbose||'undef')."\n";
print "quiet=".($quiet_parser||'undef')."\n";
print "dry-run=".($dryrun||'undef')."\n";
print "lineno=".($lineno||'undef')."\n";
print "nofail=".($nofail||'undef')."\n";
print "stack-increment=".($stacksize||'undef')."\n";
print "tag-prefix=".($tagprefix||'undef')."\n";
print "act-bin=".($actbin||'undef')."\n";
print "skel=".($SKELETON||'undef')."\n";
print "uri=".($uri||'undef')."\n";
print "pubid=".($pubid||'undef')."\n\n";
print "sysid=".($sysid||'undef')."\n\n";
print "header=".($header||'undef')."\n";
print "dummy=".($dummy||'undef')."\n";
print "stand-alone=".($standalone||'undef')."\n";
print "scanner=".($scanner||'undef')."\n";
print "actions=".($actions||'undef')."\n\n";
print '%source = (' . printhash(\%source) . ")\n";
print "\n";
print '@tags = (' . join(',',@tags) . ")\n";
print '%ctag = (' . printhash(\%ctag) . ")\n";
print '%states = (' . printhash(\%states) . ")\n";
print '%instates = (' . printhash(\%instates) . ")\n";
print '%endstates = (' . printhash(\%endstates) . ")\n";
print '%emptytrans = (' . printhash(\%emptytrans) . ")\n";
print '%exittrans = (' . printhash(\%exittrans) . ")\n";
print '%roottags = (' . printhash(\%roottags) . ")\n";
print '%empty = (' . printhash(\%empty) . ")\n";
print '%properempty = (' . printhash(\%properempty) . ")\n";
print '%any = (' . printhash(\%any) . ")\n";
print '%mixed = (' . printhash(\%mixed) . ")\n";
print '%children = (' . printhash(\%children) . ")\n";
print '%inmixed = (' . printhash(\%inmixed) . ")\n";
print "\n";
print '@attributes = (' . join(',',@attributes) . ")\n";
print '%catt = (' . printhash(\%catt) . ")\n";
print '%atttype = (' . printhash(\%atttype) . ")\n";
print '%enumtype = (' . printhash(\%enumtype) . ")\n";
print '%literaltype = (' . printhash(\%literaltype) . ")\n";
print '%typeof = (' . printhash(\%typeof) . ")\n";
print '%attdef = (' . printhash(\%attdef) . ")\n";
print '%required = (' . printhash(\%required) . ")\n";
print '%fixed = (' . printhash(\%fixed) . ")\n";
print '%initof = (' . printhash(\%initof) . ")\n";
print '%attlist = (' . printhash(\%attlist) . ")\n";
print '%withattr = (' . printhash(\%withattr) . ")\n";
print "\n";
print '%entity = (' . printhash(\%entity) . ")\n";
print '%parameter = (' . printhash(\%parameter) . ")\n";
print '%external = (' . printhash(\%external) . ")\n";
}
# WRITE API HEADER (if requested).
if ($header) {
print STDOUT "Generating XML processor header in `$HEADER'.\n" if $verbose;
open HEADER, "+>$HEADER" || die "$0: cannot write $HEADER: $!\n";
select HEADER;
# Identification and license.
print "/* XML processor/application API for $dtd"
. ($dtdrevision ? " ($dtdrevision)" : "") . ".\n";
print " * Generated " . `date +'%Y/%m/%d %T.'`;
print " *\n";
redistribute(" *");
print " */\n";
print "\n";
# Output the declarations safeguarded againts repeated loading.
print "#ifndef _FLEXML_${cdtd}_H\n";
print "#define _FLEXML_${cdtd}_H\n";
print "\n";
api_functions('extern ',';');
print "\n";
api_types();
print "\n";
api_data('extern ');
print "\n";
print "/* XML application utilities. */\n";
print "extern int ${tagprefix}element_context(int);\n";
print "\n";
print "/* XML processor entry point. */\n";
print "extern int yylex(void);\n";
print "\n";
print "/* Flexml error handling function (useful only when -q flag passed to flexml) */\n";
print "const char * ${tagprefix}parse_err_msg(void);\n";
print "#endif\n";
close HEADER || die "$0: cannot read $HEADER: $!\n";
}
# WRITE XML PROCESSOR (if requested).
if ($scanner or $standalone) {
print STDOUT "Writing XML processor"
. ($actions || $standalone ? " and application" : "")
. " onto `$SCANNER'.\n" if $verbose;
open SCANNER, "+>$SCANNER"|| die "$0: cannot write $SCANNER: $!\n";
select SCANNER;
open (SKELETON) || die "$0: cannot read $SKELETON: $!\n";
# Identification and license.
print "/* Validating XML processor for $dtd"
. ($dtdrevision ? " ($dtdrevision)" : "") . ".\n";
print " * Generated " . `date +'%Y/%m/%d %T.'`;
print " *\n";
redistribute(" *");
print " */\n";
print "\n";
# Skip initial comment.
while (<SKELETON>) { last if m/^\%\{/; }
print;
# Copy body of skeleton scanner with substitutions...
while (<SKELETON>) {
if ( /^FLEXML_VERSION$/ ) {
print "const char rcs_${tagprefix}flexml[] =\n"
. " \"\$\" \"$Id \$\";\n";
print "const char rcs_${cdtd}_dtd[] =\n"
. " \"\$\" \"$dtdrevision \$\";\n" if $dtdrevision;
}
elsif ( /^FLEXML_DEFINITIONS$/ ) {
print "#define DEBUG\n" if $debug;
print "#define FLEXML_yylineno\n" if $lineno;
print "#define FLEXML_NOFAIL\n" if $nofail;
print "#define FLEXML_quiet_parser\n" if $quiet_parser;
print "#ifndef FLEXML_BUFFERSTACKSIZE\n";
print "#define FLEXML_BUFFERSTACKSIZE $stacksize\n";
print "#endif\n";
print "#define FLEXML_NEED_BUFFERLIT\n"
if (scalar(%literaltype) or ($#default_attributes >= 0));
print "\n";
if ($standalone) {
api_functions('static ',';');
print "\n";
api_types();
print "\n";
api_data('static ');
}
else {
print "/* XML processor api. */\n";
print "#include \"$HEADER\"\n\n"
if ($header);
api_data('');
}
}
elsif ( /^FLEXML_INCLUDE_INIT_HEADER$/ ) {
if ($init_header) {
print "/* User-supplied header */\n";
print "#include \"$init_header\"\n";
}
}
elsif ( /^FLEXML_FLEX_OPTIONS$/ ) {
print "%option yylineno\n" if $lineno;
print "%option debug\n" if $debug;
print "%option nounput\n" if not %entity;
}
elsif ( /^FLEXML_START_CONDITIONS$/ ) {
for (@tags) {
my $c = $ctag{$_};
print "%x"
. ($roottags{$_} ? " ROOT_${tagprefix}$c" : "")
. " AL_${tagprefix}$c " . join(' ',split(',',$states{$_})) . "\n";
}
}
elsif ( /^FLEXML_EXTRA_DEFINITIONS$/ ) {
print "%{\n";
print "/* State names. */\n";
print "const char* *${tagprefix}statenames=NULL;\n";
print "%}\n";
}
elsif ( /^FLEXML_EXTRA_DEFINITIONS_INIT$/ ) {
my ($state, $tag);
print " /* FleXML_init */\n";
print " bnext = inext = 1;\n";
for my $att (@default_attributes) {
print " ${tagprefix}bufferliteral('\\0', &bnext, \"$att\");\n";
}
print " if(!${tagprefix}statenames) {${tagprefix}statenames= (const char **)calloc(IMPOSSIBLE,sizeof(char*));\n";
for ('PROLOG','DOCTYPE','EPILOG','INCOMMENT','INPI','VALUE1','VALUE2','CDATA') {
print " ${tagprefix}statenames[$_] = NULL;\n";
}
for my $tag (@tags) {
my $c = $ctag{$tag};
print " ${tagprefix}statenames[ROOT_${tagprefix}$c] = NULL;\n" if $roottags{$tag};
print " ${tagprefix}statenames[AL_${tagprefix}$c] = NULL;\n";
for (split ',',$states{$tag}) {
print " ${tagprefix}statenames[$_] = \"$tag\";\n";
}
}
print " }\n";
}
elsif ( /^FLEXML_DOCTYPES$/ ) {
$sysid = $sysid ? "(\"'$sysid'\"|\"\\\"$sysid\\\"\")"
: ( $uri ? "(\"'$uri'\"|\"\\\"$uri\\\"\")"
: "(\"'$dtd'\"|\"\\\"$dtd\\\"\")" );
for (keys %roottags) {
my $c = $ctag{$_};
print " \"<!DOCTYPE\"{S}\"$_\"{S}"
. "SYSTEM{S}" . $sysid . "{s}\">\" SET(ROOT_${tagprefix}$c);\n";
if ($pubid) {
print " \"<!DOCTYPE\"{S}\"$_\"{S}"
. "PUBLIC{S}(\"'$pubid'\"|\"\\\"$pubid\\\"\"){S}"
. $sysid . "{s}\">\" SET(ROOT_${tagprefix}$c);\n";
}
}
}
elsif ( /^FLEXML_RULES$/ ) {
# Dump all parameter entity declarations.
for (keys %parameter) { printsource($_); }
# Dump all start and empty tag recognition rules.
for my $tag (@tags) {
my $myctag = $ctag{$tag};
my @myattributes = (exists $attlist{$tag} ? split /,/,"$attlist{$tag}" : ());
my ($intag, $attribute);
# Tag's source element and attribute declarations.
printsource($tag);
for my $attribute (@myattributes) {
printsource("$tag/$attribute");
}
# Build element exit transition command.
my $exitswitch = "";
if (exists $exittrans{$tag}) {
$exitswitch .= " switch (YY_START) {\n";
my %casesto = ();
for (split /,/,$exittrans{$tag}) {
if (m/^($Name)=>($Name)$/o) {
$casesto{$2} .= "case $1: ";
}
}
for (keys %casesto) {
$exitswitch .= " $casesto{$_}SET($_); break;\n"
}
$exitswitch .= " }\n";
}
# Misplaced start or empty tag
unless ($nofail) {
print "\n";
my %ins = ();
foreach (keys %allstates) {
$ins{$_} = 'false';
}
if (exists $instates{$tag}) {
for (split /,/,$instates{$tag}) { $ins{$_} = 'true'; }
}
$ins{"ROOT_${tagprefix}$myctag"} = $roottags{$tag} ? 'true' : 'false';
my $str = '<' . join(',', grep {$ins{$_} eq 'false'} keys %ins);
if ($str ne '<') {
print "$str>\"<$tag\"{s} FAIL(\"Starting tag <$tag> is not allowed here.\");\n";
}
}
# Start or empty tag: initialise attribute list.
print "\n";
if ($roottags{$tag}) {
print "<ROOT_${tagprefix}$myctag" . ($instates{$tag} ? ",$instates{$tag}" : "");
}
else {
print "<$instates{$tag}";
}
# SHACK
# print ">{ \n" .
# "\"<$tag\"{s} {\n";
print ">\"<$tag\"{s} {\n";
for my $attribute (@myattributes) {
print " AX_${tagprefix}${myctag}_$catt{$attribute} = " . $initof{"$tag/$attribute"} . ";\n";
}
print " ENTER(AL_${tagprefix}$myctag); pushbuffer(0);\n";
print " }\n";
# print " . FAIL(\"Unexpected character `%c': `<$tag' expected.\",yytext[0]);\n";
# print " <<EOF>> FAIL(\"Premature EOF: `<$tag' expected.\");\n";
# #unless $mixed{$tag} or $nofail;
# print "}\n";
# Attribute list (of start or empty tag):
print "\n";
print "<AL_${tagprefix}$myctag>{\n";
for my $attribute (@myattributes) {
my $type; # set by conditions
if ($type = $enumtype{"$tag/$attribute"}) {
# - fixed enumeration attribute: generate one rule,
if ($fixed{"$tag/$attribute"}) {
print " \"$attribute\"{Eq}\"'" . $attdef{"$tag/$attribute"} . "'\""
. " |\n"
. " \"$attribute\"{Eq}\"\\\"" . $attdef{"$tag/$attribute"} . "\\\"\""
. " A_${tagprefix}${myctag}_$catt{$attribute}"
. " = " . $initof{"$tag/$attribute"} . ";\n";
}
else {
# - (non-fixed) enumeration attribute: generate a rule per value,
for my $alternative (split /,/,$type) {
print " \"$attribute\"{Eq}\"'$alternative'\""
. " |\n"
. " \"$attribute\"{Eq}\"\\\"$alternative\\\"\""
. " A_${tagprefix}${myctag}_$catt{$attribute}"
. " = A_${tagprefix}${myctag}_$catt{$attribute}_" . variablify($alternative) . ";\n";
}
}
}
elsif ($fixed{"$tag/$attribute"}) {
# - fixed (non-enumeration) attribute: generate one rule per literal form,
print " \"$attribute\"{Eq}\"'" . $attdef{"$tag/$attribute"} . "'\""
. " |\n"
. " \"$attribute\"{Eq}\"\\\"" . $attdef{"$tag/$attribute"} . "\\\"\""
. " AX_${tagprefix}${myctag}_$catt{$attribute}"
. " = " . $initof{"$tag/$attribute"} . ";\n";
}
elsif ($type = $literaltype{"$tag/$attribute"}) {
# - (non-fixed) literal-type attribute: scan literal string directly, or
print " \"$attribute\"{Eq}\'$type\' BUFFERLITERAL('\\\'',AX_${tagprefix}${myctag}_$catt{$attribute});\n";
print " \"$attribute\"{Eq}\\\"$type\\\" BUFFERLITERAL('\"',AX_${tagprefix}${myctag}_$catt{$attribute});\n";
}
else {
# - (non-fixed non-literal) attribute: scan string with entity expansion.
print " \"$attribute\"{Eq}\\' ENTER(VALUE1); BUFFERSET(AX_${tagprefix}${myctag}_$catt{$attribute});\n";
print " \"$attribute\"{Eq}\\\" ENTER(VALUE2); BUFFERSET(AX_${tagprefix}${myctag}_$catt{$attribute});\n";
}
print "\n";
}
#
# - the end of a start tag means to enter the contents after
# checking that all required attributes were set.
print " \">\" {\n";
for my $attribute (@myattributes) {
if ($required{"$tag/$attribute"}) {
print " if (!AX_${tagprefix}$ctag{$tag}_" . variablify($attribute) . ")"
. " FAIL(\"Required attribute `$attribute' not set for `$tag' element.\");\n";
}
}
print " LEAVE; STag_${tagprefix}$myctag();"
. (%inmixed ? ' pushbuffer('."${tagprefix}".'pcdata_ix);' : '')
. ($mixed{$tag} ? 'pushbuffer('."${tagprefix}".'pcdata_ix); BUFFERSET('."${tagprefix}".'pcdata_ix);' : "${tagprefix}".'pcdata_ix = 0'). ";"
. " ENTER($startstate{$tag});\n";
print " }\n";
#
# - accept and handle empty tags straight away,
if ($empty{$tag}) {
print " \"/>\" {\n";
for my $attribute (@myattributes) {
if ($required{"$tag/$attribute"}) {
print " if (!AX_${tagprefix}$ctag{$tag}_" . variablify($attribute) . ")"
. " FAIL(\"Required attribute `$attribute' not set for `$tag' element.\");\n";
}
}
print " LEAVE; STag_${tagprefix}$myctag();"
. (%inmixed ? ' pushbuffer('."${tagprefix}".'pcdata_ix);' : '')
. " ${tagprefix}".'pcdata_ix = 0;'
. " ETag_${tagprefix}$myctag();"
. (%inmixed ? " ${tagprefix}".'pcdata_ix = popbuffer();' : '')
. " popbuffer(); /* attribute */\n";
#
print $exitswitch;
print " }\n";
}
elsif (not $nofail) {
print " \"/>\" FAIL(\"`$tag' element cannot be empty.\");\n";
}
#
# - spaces are skipped, and
print " . FAIL(\"Unexpected character \`%c\' in attribute list of $tag element.\", yytext[0]);\n" unless $nofail;
#
# - other stuff is an error.
print " {Name} FAIL(\"Bad attribute `%s' in `$tag' element start tag.\",yytext);\n" unless $nofail;
print " <<EOF>> FAIL(\"EOF in attribute list of `$tag' element.\");\n" unless $nofail;
print "}\n";
# End tag.
print "\n";
print "<$endstates{$tag}>{\n";
print " \"</$tag\"{s}\">\" {\n";
print " LEAVE;\n";
print " BUFFERDONE;\n" if $mixed{$tag};
print " ETag_${tagprefix}$myctag();\n";
print " ${tagprefix}pcdata_ix = popbuffer();\n" if $mixed{$tag};
print " ${tagprefix}pcdata_ix = popbuffer();\n" if %inmixed;
print " popbuffer(); /* attribute */\n";
print $exitswitch;
print " }\n";
# Errors when expecting end tag.
print " \"</\"{Name}{s}\">\" FAIL(\"Unexpected end-tag `%s': `</$tag>' expected.\",yytext);\n"
unless $nofail;
print " . FAIL(\"Unexpected character `%c': `</$tag>' expected.\",yytext[0]);\n"
unless $mixed{$tag} or $nofail;
print " <<EOF>> FAIL(\"Premature EOF: `</$tag>' expected.\");\n" unless $nofail;
print "}\n";
# Errors when expecting root tag.
if ($roottags{$tag} and $nofail) {
print "\n";
print "<ROOT_${tagprefix}$myctag>{\n";
print " . FAIL(\"Unexpected character `%c': `$tag' element expected.\",yytext[0]);\n";
print " <<EOF>> FAIL(\"EOF in prolog.\");\n";
print "}\n";
}
}
}
elsif ( /FLEXML_MIXED([,>])/ ) {
if (%mixed) {
print "$`" . join(',', map("IN_$ctag{$_}", keys %mixed)) . "$1$'";
}
else {
print "$`IMPOSSIBLE$1$'";
}
}
elsif ( /FLEXML_NON_MIXED([,>])/ ) {
my $sep = $`;
for (@tags) {
print $sep . ($roottags{$_} ? "ROOT_${tagprefix}$ctag{$_}," : "")
. "AL_${tagprefix}$ctag{$_}";
print ",$states{$_}" if $properempty{$_} or $children{$_};
$sep = ',';
}
print "$1$'";
}
elsif ( /FLEXML_COMMENTS([,>])/ ) {
print "$`"
. join(',', map(($roottags{$_} ? "ROOT_${tagprefix}$ctag{$_}," : "")
. "AL_${tagprefix}$ctag{$_},$states{$_}", @tags))
. "$1$'";
}
elsif ( /^FLEXML_ENTITIES$/ ) {
# Process general entities.
for my $ent (keys %entity) {
printsource("%$ent;");
print " \"&$ent;\" ENTITYTEXT(\"" . $entity{$ent} . "\");\n";
}
print " /* Non-defined standard entities... */\n";
print "\"&\" BUFFERPUTC('&');\n" unless $entity{"amp"};
print "\"<\" BUFFERPUTC('<');\n" unless $entity{"lt"};
print "\">\" BUFFERPUTC('>');\n" unless $entity{"gt"};
print "\"'\" BUFFERPUTC('\\\'');\n" unless $entity{"apos"};
print "\""\" BUFFERPUTC('\"');\n" unless $entity{"quot"};
}
elsif ( /^FLEXML_FINAL$/ and not $nofail ) {
# Catch-all error cases.
for my $tag (@tags) {
for (split ',',$states{$tag}) {
print "<$_>{\n";
print " . FAIL(\"Unrecognized `%c' in $_.\",yytext[0]);\n";
print " [\\n] FAIL(\"Unrecognized newline in $_.\");\n";
print "}\n";
}
}
for ('PROLOG','DOCTYPE','EPILOG','INCOMMENT','INPI','VALUE1','VALUE2','CDATA','INITIAL','IMPOSSIBLE') {
print "<$_>{\n";
print " . FAIL(\"Unrecognized `%c' in $_.\",yytext[0]);\n";
print " [\\n] FAIL(\"Unrecognized space in $_.\");\n";
print "}\n";
}
}
elsif ( $nofail and /FAIL\(/ ) {
#ignore
}
else {
s/"\$Id/"\$" "Id/;
s/statenames/${tagprefix}statenames/g;
s/element_context/${tagprefix}element_context/g;
s/parse_err_msg/${tagprefix}parse_err_msg/g;
s/rcs_flexml_skeleton/rcs_${tagprefix}flexml_skeleton/g;
s/bufferliteral/${tagprefix}bufferliteral/g;
s/bufferstack/${tagprefix}bufferstack/g;
print;
}
}
close SKELETON || die "$0: Cannot close $SKELETON: $!\n";
unless ($standalone) {
close SCANNER || die "$0: Cannot close $SCANNER: $!\n";
}
}
# WRITE APPLICATION.
if ($dummy) {
print STDOUT "Writing XML"
. ($actions ? "" : " dummy")
. " application onto `$APPLICATION'.\n" if $verbose;
open APPLICATION, "+>$APPLICATION" || die "$0: Cannot write $APPLICATION: $!\n";
select APPLICATION;
# Identification and license.
print "/* XML application for $dtd"
. ($dtdrevision ? " ($dtdrevision)" : "") . ".\n";
print " * Includes actions from $ACTIONS.\n" if $ACTIONS;
print " * Generated " . `date +'%Y/%m/%d %T.'`;
print " *\n";
redistribute(" *");
print " */\n";
print "\n";
# Declarations.
print "#include \"$HEADER\"\n";
print "\n";
}
if ($dummy or $standalone) {
# Get requested actions.
if ($ACTIONS) {
open ACTIONS, "$actbin $ACTIONS|" || die "$0: Cannot exec $actbin $ACTIONS: $!\n";
my ($tag,$attribute);
my @myattributes;
my $lineno = 0;
my $isstart = undef;
while (<ACTIONS>) {
++$lineno;
if ( m/^\#line ([0-9]+)/ ) {
$lineno = $1;
}
elsif ( m/^void\s+STag_${tagprefix}($Name)\(void\)$/xo ) {
$tag = $1;
die "\"$ACTIONS\", line $lineno: Unknown element `$tag'.\n" unless $ctag{$tag};
$startok{$tag} = 'true';
@myattributes = (exists $withattr{$tag} ? split /,/,"$withattr{$tag}" : ());
$isstart = 'true';
}
elsif ( m|^\}\s+\/\*\s+STag_${tagprefix}($Name)\s+\*\/$|xo ) {
$tag = undef;
@myattributes = ();
$isstart = 'true';
}
elsif ( m/^void\s+ETag_${tagprefix}($Name)\(void\)$/xo ) {
$tag = $1;
$endok{$1} = 'true';
$isstart = undef;
}
# Make function names C-friendly (idempotently!)
s/(\s+[SE])Tag_($Name)\(/$1Tag_$ctag{$2}\(/xg;
# Replace special annotations with C equivalents.
if ($tag) {
while ( s/\{($Name)\}/A_${tagprefix}$ctag{$tag}_$catt{$1}/x ) {
die "\"$ACTIONS\", line $lineno: Unknown attribute `$1' for <$tag>.\n"
if not $atttype{"$tag/$1"};
}
while ( s/\{[!]($Name)\}/AU_${tagprefix}$ctag{$tag}_$catt{$1}/x ) {
die "\"$ACTIONS\", line $lineno: Unknown attribute `$1' for <$tag>.\n"
if not $atttype{"$tag/$1"};
}
while ( s|\{($Name)=($Name)\}|
"A_${tagprefix}$ctag{$tag}_$catt{$1}_" . variablify($2); |xe ) {
my ($att,$elt) = ($1,$2);
die "\"$ACTIONS\", line $lineno: Unknown attribute $1 for <$tag>.\n"
if not $atttype{"$tag/$1"};
die "\"$ACTIONS\", line $lineno: Attribute $att does not have value $elt for <$tag>.\n"
if not $enumtype{"$tag/$att"} =~ m/\b$elt\b/ ;
}
while ( s|\{\#(PCDATA)\}|${tagprefix}pcdata| ) {
die "\"$ACTIONS\", line $lineno: {#PCDATA} only allowed in end tag.\n"
if $isstart;
die "\"$ACTIONS\", line $lineno: {#PCDATA} only permitted in end tag with Mixed contents.\n"
if not $mixed{$tag};
}
die "\"$ACTIONS\", line $lineno: Malformed annotation `$&' in <$tag> action.\n"
if m|\{[^;\s]+\}|o;
}
print STDERR "Action: $_" if $debug;
print $_;
}
close ACTIONS || die "$0: Cannot close pipe to $actbin: $!\n";
print "\n";
}
# Fill up with dummy declarations for the remaining functions.
api_functions('',' {}');
}
if ($dummy) {
close APPLICATION || die "$0: Cannot close $APPLICATION: $!\n";
}
elsif ($standalone) {
close SCANNER || die "$0: Cannot close $SCANNER: $!\n";
}
=pod
=head1 NAME
flexml - generate validating XML processor and applications from DTD
=head1 SYNOPSIS
B<flexml>
[B<-ASHDvdnLXV>]
[B<-s>I<skel>]
[B<-p>I<pubid>]
[B<-i>I<init_header>]
[B<-u>I<uri>]
[B<-r>I<rootags>]
[B<-a>I<actions>]
I<name>[F<.dtd>]
=head1 DESCRIPTION
I<Flexml> reads I<name>F<.dtd> which must be a DTD (Document Type
Definition) describing the format of XML (Extensible Markup Language)
documents, and produces a "validating" XML I<processor> with an
interface to support XML I<application>s. Proper applications can be
generated optionally from special "action files", either for linking
or textual combination with the processor.
The generated processor will only validate documents that conform
strictly to the DTD, I<without extending it>, more precisely we in
practice restrict XML rule [28] to
[28r] doctypedecl ::= '<!DOCTYPE' S Name S ExternalID S? '>'
where the C<ExternalId> denotes the used DTD. (One might say, in
fact, that I<flexml> implements "non-extensible" markup. :)
The generated processor is a I<flex>(1) scanner, by default named
I<name>F<.l> with a corresponding C header file I<name>F<.h> for
separate compilation of generated applications. Optionally I<flexml>
takes an I<actions> file with per-element actions and produces a C
file with element functions for an XML application with entry points
called from the XML processor (it can also fold the XML application
into the XML processor to make stand-alone XML applications but this
prevents sharing of the processor between applications).
In L</OPTIONS>Z<> we list the possible options, in L</ACTION FILE
FORMAT>Z<> we explain how to write applications, in L</COMPILATION> we
explain how to compile produced processors and applications into
executables, and in L</BUGS> we list the current limitations of the
system before giving standard references.
=head1 OPTIONS
I<Flexml> takes the following options.
=over 4
=item B<--stand-alone>, B<-A>
Generate a I<stand-alone> scanner application. If combined with
B<-a>I<actions> then the application will be named as I<actions> with
the extension replaced by F<.l>, otherwise it will be in I<name>F<.l>.
Conflicts with B<-S>, B<-H>, and B<-D>.
=item B<--actions> I<actions>, B<-a> I<actions>
Uses the I<actions> file to produce an XML application in the file
with the same name as I<actions> after replacing the extension with
F<.c>. If combined with B<-A> then instead the stand-alone
application will include the action functions.
=item B<--dummy> B<[>I<app_name>B<]>, B<-D> B<[>I<app_name>B<]>
Generate a dummy application with just empty functions to be called by the
XML processor. If I<app_name> is not specified on the command line, it
defaults to I<name>F<-dummy.c>. If combined with B<-a> I<actions> then the
application will insert the specified actions and be named as I<actions>
with the extension replaced by F<.c>. Conflicts with B<-A>; implied by
B<-a> unless either of B<-SHD> is specified.
=item B<--debug>, B<-d>
Turns on debug mode in the flex scanner and also prints out the
details of the DTD analysis performed by I<flexml>.
=item B<--header> B<[>I<header_name>B<]>, B<-H> B<[>I<header_name>B<]>
Generate the header file. If the I<header_name> is not specified on the
command line, defaults to I<name>F<.h>. Conflicts with B<-A>; on by
default if none of B<-SHD> specified.
=item B<--lineno>, B<-L>
Makes the XML processor (as produced by I<flex>(1)) count the lines in
the input and keep it available to XML application actions in the
integer C<yylineno>. (This is off by default as the performance
overhead is significant.)
=item B<--quiet>, B<-q>
Prevents the XML processor (as produced by I<flex>(1)) from reporting
the error it runs into on stderr. Instead, users will have to pool for
error messages with the parse_err_msg() function.
By default, error messages are written on stderr.
=item B<--dry-run>, B<-n>
"Dry-run": do not produce any of the output files.
=item B<--pubid> I<pubid>, B<-p> I<pubid>
Sets the document type to be C<PUBLIC> with the identifier I<pubid>
instead of C<SYSTEM>, the default.
=item B<--init_header> I<init_header>, B<-i> I<init_header>
Puts a line containing C<#include "init_header"> in the C<%{...%}> section
at the top of the generated .l file. This may be useful for making various
flex C<#define>s, for example C<YY_INPUT> or C<YY_DECL>.
=item B<--sysid>=I<sysid>
Overrides the C<SYSTEM> id of the accepted DTD. Sometimes useful when your
dtd is placed in a subdirectory.
=item B<--root-tags> I<roottags>, B<-r> I<roottags>
Restricts the XML processor to validate only documents with one of the
root elements listed in the comma-separated I<roottags>.
=item B<--scanner> B<[>I<scanner_name>B<]>, B<-S> B<[>I<scanner_name>B<]>
Generate the scanner. If I<scanner_name> is not given on command line, it
defaults to I<name>F<.l>. Conflicts with B<-A>; on by default if none of
B<-SHD> specified.
=item B<--skel> I<skel>, B<-s> I<skel>
Use the skeleton scanner I<skel> instead of the default.
=item B<--act-bin> I<flexml-act>, B<-T> I<flexml-act>
This is an internal option mainly used to test versions of flexml not
installed yet.
=item B<--stack-increment> I<stack_increment>, B<-b> I<stack_increment>
Sets the FLEXML_BUFFERSTACKSIZE to stack_increment (100000 by default). This
controls how much the data stack grows in each realloc().
=item B<--tag-prefix> I<STRING>, B<-O> I<STRING>
Use STRING to differentiate multiple versions of flexml in the same C
code, just like the -P flex argument.
=item B<--uri> I<uri>, B<-u> I<uri>
Sets the URI of the DTD, used in the C<DOCTYPE> header, to the
specified I<uri> (the default is the DTD name).
=item B<--verbose>, B<-v>
Be verbose: echo each DTD declaration (after parameter expansion).
=item B<--version>, B<-V>
Print the version of I<flexml> and exit.
=back
=head1 ACTION FILE FORMAT
Action files, passed to the B<-a> option, are XML documents conforming
to the DTD F<flexml-act.dtd> which is the following:
<!ELEMENT actions ((top|start|end)*,main?)>
<!ENTITY % C-code "(#PCDATA)">
<!ELEMENT top %C-code;>
<!ELEMENT start %C-code;> <!ATTLIST start tag NMTOKEN #REQUIRED>
<!ELEMENT end %C-code;> <!ATTLIST end tag NMTOKEN #REQUIRED>
<!ELEMENT main %C-code;>
The elements should be used as follows:
=over 4
=item C<top>
Use for top-level C code such as global declarations, utility
functions, etc.
=item C<start>
Attaches the code as an action to the element with the name of the
required "C<tag>" attribute. The "C<%C-code;>" component should be C
code suitable for inclusion in a C block (i.e., within C<{>...C<}> so
it may contain local variables); furthermore the following extensions
are available:
C<{>I<attribute>C<}>: Can be used to access the value of the
I<attribute> as set with I<attribute>C<=>I<value> in the start tag.
In C, C<{>I<attribute>C<}> will be interpreted depending on the
declaration of the attribute. If the attribute is declared as an
enumerated type like
<!ATTLIST attrib (alt1 | alt2 |...) ...>
then the C attribute value is of an enumerated type with the elements
written C<{>I<attribute>C<=>I<alt1>C<}>,
C<{>I<attribute>C<=>I<alt2>C<}>, etc.; furthermore an I<unset>
attribute has the "value" C<{!>I<attribute>C<}>. If the attribute is
not an enumeration then C<{>I<attribute>C<}> is a null-terminated C
string (of type C<char*>) and C<{!>I<attribute>C<}> is C<NULL>.
=item C<end>
Similarly attaches the code as an action to the end tag with the name
of the required "C<tag>" attribute; also here the "C<%C-code;>"
component should be C code suitable for inclusion in a C block. In
case the element has "Mixed" contents, i.e, was declared to permit
C<#PCDATA>, then the following variable is available:
C<{#PCDATA}>: Contains the text (C<#PCDATA>) of the element as a
null-terminated C string (of type C<char*>). In case the Mixed
contents element actually mixed text and child elements then C<pcdata>
contains the plain concatenation of the text fragments as one string.
=item C<main>
Finally, an optional "C<main>" element can contain the C C<main>
function of the XML application. Normally the C<main> function should
include (at least) one call of the XML processor:
C<yylex()>:
Invokes the XML processor produced by I<flex>(1) on the XML document
found on the standard input (actually the C<yyin> file handle: see the
manual for I<flex>(1) for information on how to change this as well as
the name C<yylex>).
If no C<main> action is provided then the following is used:
int main() { exit(yylex()); }
=back
It is advisable to use XML E<lt>C<![CDATA[> ... C<]]>E<gt> sections
for the C code to make sure that all characters are properly passed to
the output file.
Finally note that I<Flexml> handles empty elements
E<lt>I<tag>C</>E<gt> as equivalent to
E<lt>I<tag>E<gt>E<lt>C</>I<tag>E<gt>.
=head1 COMPILATION
The following I<make>(1) file fragment shows how one can compile
I<flexml>-generated programs:
# Programs.
FLEXML = flexml -v
# Generate linkable XML processor with header for application.
%.l %.h: %.dtd
$(FLEXML) $<
# Generate C source from flex scanner.
%.c: %.l
$(FLEX) -Bs -o"$@" "$<"
# Generate XML application C source to link with processor.
# Note: The dependency must be of the form "appl.c: appl.act proc.dtd".
%.c: %.act
$(FLEXML) -D -a $^
# Direct generation of stand-alone XML processor+application.
# Note: The dependency must be of the form "appl.l: appl.act proc.dtd".
%.l: %.act
$(FLEXML) -A -a $^
=head1 BUGS
The present version of I<flexml> is to be considered in "early beta"
state thus bugs should be expected (and the author would like to hear
about them). Here are some known restrictions that we hope to
overcome in the future:
=over 4
=item *
The character set is merely ASCII (actually I<flex>(1) handles 8 bit
characters but only the ASCII character set is common with the XML
default UTF-8 encoding).
=item *
C<ID> type attributes are not validated for uniqueness; C<IDREF> and
C<IDREFS> attributes are not validated for existence.
=item *
The C<ENTITY> and C<ENTITIES> attribute types are not supported.
=item *
C<NOTATION> declarations are not supported.
=item *
The various C<xml:>-attributes are treated like any other attributes;
in particular C<xml:spaces> should be supported.
=item *
The DTD parser is presently a perl hack so it may parse some DTDs
badly; in particular the expansion of parameter entities may not
conform fully to the XML specification.
=item *
A child should be able to "return" a value for the parent (also called
a I<synthesised attribute>). Similarly an element in Mixed contents
should be able to inject text into the C<pcdata> of the parent.
=back
=head1 FILES
=over 4
=item F<./skel>
The skeleton scanner with the generic parts of XML scanning.
=item F</usr/share/doc/flexml/>
License, further documentation, and examples.
=back
=head1 SEE ALSO
I<flex>(1), Extensible Markup Language (XML) 1.0 (W3C Recommendation
REC-xml-1998-0210).
=head1 AUTHOR
I<Flexml> was written by Kristoffer Rose,
E<lt>C<krisrose@debian.org>E<gt>.
=head1 COPYRIGHT
The program is Copyright (c) 1999 Kristoffer Rose (all rights
reserved) and distributed under the GNU General Public License (GPL,
also known as "copyleft", which clarifies that the author provides
absolutely no warranty for I<flexml> and ensures that I<flexml> is and
will remain available for all uses, even comercial).
=head1 ACKNOWLEDGEMENT
I am grateful to NTSys (France) for supporting the development of
I<flexml>. Finally extend my severe thanks to Jef Poskanzer, Vern
Paxson, and the rest of the I<flex> maintainers and GNU developers for
a great tool.
=cut
|