1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367
|
{
**********************************************************************
This file is part of LazUtils.
It is copied from FCL unit xmlread svn revision 15251 and adapted to use
UTF8 instead of widestrings by Mattias Gaertner.
See the file COPYING.FPC, included in this distribution,
for details about the license.
**********************************************************************
XML reading routines.
Copyright (c) 1999-2000 by Sebastian Guenther, sg@freepascal.org
Modified in 2006 by Sergei Gorelkin, sergei_gorelkin@mail.ru
}
unit laz2_XMLRead;
{$ifdef fpc}
{$MODE objfpc}{$H+}
{$endif}
{$DEFINE UseUTF8}
{off $DEFINE UseWideString}
interface
uses
SysUtils, Classes, laz2_DOM, lazutf8classes;
type
TErrorSeverity = (esWarning, esError, esFatal);
TXMLReaderFlag = (
xrfAllowLowerThanInAttributeValue,
xrfAllowSpecialCharsInAttributeValue,
xrfAllowSpecialCharsInComments,
xrfPreserveWhiteSpace
);
TXMLReaderFlags = set of TXMLReaderFlag;
{ EXMLReadError }
EXMLReadError = class(Exception)
private
FSeverity: TErrorSeverity;
FErrorMessage: string;
FLine: Integer;
FLinePos: Integer;
public
property Severity: TErrorSeverity read FSeverity;
property ErrorMessage: string read FErrorMessage;
property Line: Integer read FLine;
property LinePos: Integer read FLinePos;
function LineCol: TPoint;
end;
procedure ReadXMLFile(out ADoc: TXMLDocument; const AFilename: String; Flags: TXMLReaderFlags = []); overload;
procedure ReadXMLFile(out ADoc: TXMLDocument; var f: Text; Flags: TXMLReaderFlags = []); overload;
procedure ReadXMLFile(out ADoc: TXMLDocument; var f: File; Flags: TXMLReaderFlags = []); overload;
procedure ReadXMLFile(out ADoc: TXMLDocument; f: TStream; Flags: TXMLReaderFlags = []); overload;
procedure ReadXMLFile(out ADoc: TXMLDocument; f: TStream; const ABaseURI: String; Flags: TXMLReaderFlags = []); overload;
procedure ReadXMLFragment(AParentNode: TDOMNode; const AFilename: String; Flags: TXMLReaderFlags = []); overload;
procedure ReadXMLFragment(AParentNode: TDOMNode; var f: Text; Flags: TXMLReaderFlags = []); overload;
procedure ReadXMLFragment(AParentNode: TDOMNode; var f: File; Flags: TXMLReaderFlags = []); overload;
procedure ReadXMLFragment(AParentNode: TDOMNode; f: TStream; Flags: TXMLReaderFlags = []); overload;
procedure ReadXMLFragment(AParentNode: TDOMNode; f: TStream; const ABaseURI: String; Flags: TXMLReaderFlags = []); overload;
procedure ReadDTDFile(out ADoc: TXMLDocument; const AFilename: String); overload;
procedure ReadDTDFile(out ADoc: TXMLDocument; var f: Text); overload;
procedure ReadDTDFile(out ADoc: TXMLDocument; var f: File); overload;
procedure ReadDTDFile(out ADoc: TXMLDocument; f: TStream); overload;
procedure ReadDTDFile(out ADoc: TXMLDocument; f: TStream; const ABaseURI: String); overload;
type
TDOMParseOptions = class(TObject)
private
FValidate: Boolean;
FPreserveWhitespace: Boolean;
FExpandEntities: Boolean;
FIgnoreComments: Boolean;
FCDSectionsAsText: Boolean;
FResolveExternals: Boolean;
FNamespaces: Boolean;
FDisallowDoctype: Boolean;
FCanonical: Boolean;
FMaxChars: Cardinal;
function GetCanonical: Boolean;
procedure SetCanonical(aValue: Boolean);
public
property Validate: Boolean read FValidate write FValidate;
property PreserveWhitespace: Boolean read FPreserveWhitespace write FPreserveWhitespace;
property ExpandEntities: Boolean read FExpandEntities write FExpandEntities;
property IgnoreComments: Boolean read FIgnoreComments write FIgnoreComments;
property CDSectionsAsText: Boolean read FCDSectionsAsText write FCDSectionsAsText;
property ResolveExternals: Boolean read FResolveExternals write FResolveExternals;
property Namespaces: Boolean read FNamespaces write FNamespaces;
property DisallowDoctype: Boolean read FDisallowDoctype write FDisallowDoctype;
property MaxChars: Cardinal read FMaxChars write FMaxChars;
property CanonicalForm: Boolean read GetCanonical write SetCanonical;
end;
// NOTE: DOM 3 LS ACTION_TYPE enumeration starts at 1
TXMLContextAction = (
xaAppendAsChildren = 1,
xaReplaceChildren,
xaInsertBefore,
xaInsertAfter,
xaReplace);
TXMLErrorEvent = procedure(Error: EXMLReadError) of object;
TXMLInputSource = class(TObject)
private
FStream: TStream;
FStringData: string;
FBaseURI: DOMString;
FSystemID: DOMString;
FPublicID: DOMString;
// FEncoding: string;
public
constructor Create(AStream: TStream); overload;
constructor Create(const AStringData: string); overload;
property Stream: TStream read FStream;
property StringData: string read FStringData;
property BaseURI: DOMString read FBaseURI write FBaseURI;
property SystemID: DOMString read FSystemID write FSystemID;
property PublicID: DOMString read FPublicID write FPublicID;
// property Encoding: string read FEncoding write FEncoding;
end;
TDOMParser = class(TObject)
private
FOptions: TDOMParseOptions;
FOnError: TXMLErrorEvent;
public
constructor Create;
destructor Destroy; override;
procedure Parse(Src: TXMLInputSource; out ADoc: TXMLDocument);
procedure ParseUri(const URI: DOMString; out ADoc: TXMLDocument);
function ParseWithContext(Src: TXMLInputSource; Context: TDOMNode;
Action: TXMLContextAction): TDOMNode;
property Options: TDOMParseOptions read FOptions;
property OnError: TXMLErrorEvent read FOnError write FOnError;
end;
TDecoder = record
Context: Pointer;
Decode: function(Context: Pointer; InBuf: PChar; var InCnt: Cardinal; OutBuf: DOMPChar; var OutCnt: Cardinal): Integer; stdcall;
Cleanup: procedure(Context: Pointer); stdcall;
end;
TGetDecoderProc = function(const AEncoding: string; out Decoder: TDecoder): Boolean; stdcall;
procedure RegisterDecoder(Proc: TGetDecoderProc);
// =======================================================
implementation
uses
UriParser, laz2_xmlutils, LazUTF8;
const
PubidChars: TSetOfChar = [' ', #13, #10, 'a'..'z', 'A'..'Z', '0'..'9',
'-', '''', '(', ')', '+', ',', '.', '/', ':', '=', '?', ';', '!', '*',
'#', '@', '$', '_', '%'];
var
{$IFDEF UseUTF8}
IsNameStartChar, IsNameChar: array[char] of boolean;
{$ENDIF}
type
TDOMNotationEx = class(TDOMNotation);
TDOMDocumentTypeEx = class(TDOMDocumentType);
TDOMElementDef = class;
TDTDSubsetType = (dsNone, dsInternal, dsExternal);
// This may be augmented with ByteOffset, UTF8Offset, etc.
TLocation = record
Line: Integer;
LinePos: Integer;
end;
TDOMEntityEx = class(TDOMEntity)
protected
FExternallyDeclared: Boolean;
FPrefetched: Boolean;
FResolved: Boolean;
FOnStack: Boolean;
FBetweenDecls: Boolean;
FIsPE: Boolean;
FReplacementText: DOMString;
FURI: DOMString;
FStartLocation: TLocation;
FCharCount: Cardinal;
end;
DOMPCharBuf = {%H-}^TDOMCharBuf;
TDOMCharBuf = record
Buffer: DOMPChar;
Length: Integer;
MaxLength: Integer;
end;
TXMLReader = class;
TXMLCharSource = class(TObject)
private
FBuf: DOMPChar;
FBufEnd: DOMPChar;
FReader: TXMLReader;
FParent: TXMLCharSource;
FEntity: TObject; // weak reference
FLineNo: Integer;
LFPos: DOMPChar;
FXML11Rules: Boolean;
FSystemID: DOMString;
FCharCount: Cardinal;
FStartNesting: Integer;
function GetSystemID: DOMString;
protected
function Reload: Boolean; virtual;
public
DTDSubsetType: TDTDSubsetType;
constructor Create(const AData: DOMString);
procedure NextChar;
procedure NewLine; virtual;
function SkipUntil(var ToFill: TDOMCharBuf; const Delim: TSetOfChar;
wsflag: PBoolean = nil; {%H-}AllowSpecialChars: boolean = false): DOMChar; virtual;
procedure Initialize; virtual;
function SetEncoding(const {%H-}AEncoding: string): Boolean; virtual;
function Matches(const arg: DOMString): Boolean;
property SystemID: DOMString read GetSystemID write FSystemID;
end;
TXMLDecodingSource = class(TXMLCharSource)
private
FCharBuf: PChar;
FCharBufEnd: PChar;
FBufStart: DOMPChar;
FDecoder: TDecoder;
FHasBOM: Boolean;
{$IFDEF UseWideString}
FFixedUCS2: string;
{$ENDIF}
FBufSize: Integer;
procedure DecodingError(const Msg: string);
protected
function Reload: Boolean; override;
procedure FetchData; virtual;
public
procedure AfterConstruction; override;
destructor Destroy; override;
function SetEncoding(const AEncoding: string): Boolean; override;
procedure NewLine; override;
function SkipUntil(var ToFill: TDOMCharBuf; const Delim: TSetOfChar;
wsflag: PBoolean = nil; AllowSpecialChars: boolean = false): DOMChar; override;
procedure Initialize; override;
end;
TXMLStreamInputSource = class(TXMLDecodingSource)
private
FAllocated: PChar;
FStream: TStream;
FCapacity: Integer;
FOwnStream: Boolean;
FEof: Boolean;
public
constructor Create(AStream: TStream; AOwnStream: Boolean);
destructor Destroy; override;
procedure FetchData; override;
end;
TXMLFileInputSource = class(TXMLDecodingSource)
private
FFile: ^Text;
FString: string;
FTmp: string;
public
constructor Create(var AFile: Text);
procedure FetchData; override;
end;
PForwardRef = ^TForwardRef;
TForwardRef = record
Value: DOMString;
Loc: TLocation;
end;
TCPType = (ctName, ctChoice, ctSeq);
TCPQuant = (cqOnce, cqZeroOrOnce, cqZeroOrMore, cqOnceOrMore);
TContentParticle = class(TObject)
private
FParent: TContentParticle;
FChildren: TFPList;
FIndex: Integer;
function GetChildCount: Integer;
function GetChild(Index: Integer): TContentParticle;
public
CPType: TCPType;
CPQuant: TCPQuant;
Def: TDOMElementDef;
destructor Destroy; override;
function Add: TContentParticle;
function IsRequired: Boolean;
function FindFirst(aDef: TDOMElementDef): TContentParticle;
function FindNext(aDef: TDOMElementDef; ChildIdx: Integer): TContentParticle;
function MoreRequired(ChildIdx: Integer): Boolean;
property ChildCount: Integer read GetChildCount;
property Children[Index: Integer]: TContentParticle read GetChild;
end;
TElementValidator = object
FElement: TDOMElement;
FElementDef: TDOMElementDef;
FCurCP: TContentParticle;
FFailed: Boolean;
function IsElementAllowed(Def: TDOMElementDef): Boolean;
function Incomplete: Boolean;
end;
TXMLReadState = (rsProlog, rsDTD, rsRoot, rsEpilog);
TElementContentType = (
ctUndeclared,
ctAny,
ctEmpty,
ctMixed,
ctChildren
);
TCheckNameFlags = set of (cnOptional, cnToken);
TPrefixedAttr = record
Attr: TDOMAttr;
PrefixLen: Integer; // to avoid recalculation
end;
TLiteralType = (ltPlain, ltAttr, ltTokAttr, ltPubid, ltEntity);
{ TXMLReader }
TXMLReader = class
private
FFlags: TXMLReaderFlags;
FSource: TXMLCharSource;
FCtrl: TDOMParser;
FXML11: Boolean;
FState: TXMLReadState;
FRecognizePE: Boolean;
FHavePERefs: Boolean;
FInsideDecl: Boolean;
FDocNotValid: Boolean;
FValue: TDOMCharBuf;
FEntityValue: TDOMCharBuf;
FName: TDOMCharBuf;
FTokenStart: TLocation;
FStandalone: Boolean; // property of Doc ?
FNamePages: PByteArray;
FDocType: TDOMDocumentTypeEx; // a shortcut
FPEMap: TDOMNamedNodeMap;
FIDRefs: TFPList;
FNotationRefs: TFPList;
FCurrContentType: TElementContentType;
FSaViolation: Boolean;
FDTDStartPos: DOMPChar;
FIntSubset: TDOMCharBuf;
FAttrTag: Cardinal;
FOwnsDoctype: Boolean;
FDTDProcessed: Boolean;
FNSHelper: TNSSupport;
FWorkAtts: array of TPrefixedAttr;
FNsAttHash: TDblHashArray;
FStdPrefix_xml: PHashItem;
FStdPrefix_xmlns: PHashItem;
FColonPos: Integer;
FValidate: Boolean; // parsing options, copy of FCtrl.Options
FPreserveWhitespace: Boolean;
FExpandEntities: Boolean;
FIgnoreComments: Boolean;
FCDSectionsAsText: Boolean;
FResolveExternals: Boolean;
FNamespaces: Boolean;
FDisallowDoctype: Boolean;
FCanonical: Boolean;
FMaxChars: Cardinal;
procedure SetFlags(AValue: TXMLReaderFlags);
procedure SkipQuote(out Delim: DOMChar; required: Boolean = True);
procedure Initialize(ASource: TXMLCharSource);
function ContextPush(AEntity: TDOMEntityEx): Boolean;
function ContextPop(Forced: Boolean = False): Boolean;
procedure XML11_BuildTables;
procedure ParseQuantity(CP: TContentParticle);
procedure StoreLocation(out Loc: TLocation);
function ValidateAttrSyntax(AttrDef: TDOMAttrDef; const aValue: DOMString): Boolean;
procedure ValidateAttrValue(Attr: TDOMAttr; const aValue: DOMString);
procedure AddForwardRef(aList: TFPList; Buf: DOMPChar; Length: Integer);
procedure ClearRefs(aList: TFPList);
procedure ValidateIdRefs;
procedure StandaloneError(LineOffs: Integer = 0);
procedure CallErrorHandler(E: EXMLReadError);
function FindOrCreateElDef: TDOMElementDef;
function SkipUntilSeq(const Delim: TSetOfChar; c1: DOMChar; c2: DOMChar = #0;
AllowSpecialChars: boolean = false): Boolean;
procedure CheckMaxChars;
protected
FCursor: TDOMNode_WithChildren;
FNesting: Integer;
FValidator: array of TElementValidator;
procedure DoError(Severity: TErrorSeverity; const descr: string; LineOffs: Integer=0);
procedure DoErrorPos(Severity: TErrorSeverity; const descr: string;
const ErrPos: TLocation);
procedure FatalError(const descr: String; LineOffs: Integer=0); overload;
procedure FatalError(const descr: string; const args: array of const; LineOffs: Integer=0); overload;
procedure FatalError(Expected: DOMChar); overload;
function SkipWhitespace(PercentAloneIsOk: Boolean = False): Boolean;
function SkipS(required: Boolean = False): Boolean;
procedure ExpectWhitespace;
procedure ExpectString(const s: String);
procedure ExpectChar(wc: DOMChar);
function CheckForChar(c: DOMChar): Boolean;
procedure RaiseNameNotFound;
function CheckName(aFlags: TCheckNameFlags = []): Boolean;
procedure CheckNCName;
function ExpectName: DOMString; // [5]
function ParseLiteral(var ToFill: TDOMCharBuf; aType: TLiteralType;
Required: Boolean; Normalized: PBoolean = nil): Boolean;
procedure ExpectAttValue; // [10]
procedure ParseComment; // [15]
procedure ParsePI; // [16]
procedure ParseXmlOrTextDecl(TextDecl: Boolean);
procedure ExpectEq;
procedure ParseDoctypeDecl; // [28]
procedure ParseMarkupDecl; // [29]
procedure ParseElement; // [39]
procedure ParseEndTag; // [42]
procedure DoEndElement(ErrOffset: Integer);
procedure ParseAttribute(Elem: TDOMElement; ElDef: TDOMElementDef);
procedure ParseContent; // [43]
function ResolvePredefined: Boolean;
function EntityCheck(NoExternals: Boolean = False): TDOMEntityEx;
procedure AppendReference(AEntity: TDOMEntityEx);
function PrefetchEntity(AEntity: TDOMEntityEx): Boolean;
procedure StartPE;
function ParseRef(var ToFill: TDOMCharBuf): Boolean; // [67]
function ParseExternalID(out SysID, PubID: DOMString; // [75]
SysIdOptional: Boolean): Boolean;
procedure BadPENesting(S: TErrorSeverity = esError);
procedure ParseEntityDecl;
procedure ParseAttlistDecl;
procedure ExpectChoiceOrSeq(CP: TContentParticle);
procedure ParseElementDecl;
procedure ParseNotationDecl;
function ResolveEntity(const SystemID, {%H-}PublicID, BaseURI: DOMString; out Source: TXMLCharSource): Boolean;
procedure ProcessDefaultAttributes(Element: TDOMElement; Map: TDOMNamedNodeMap);
procedure ProcessNamespaceAtts(Element: TDOMElement);
procedure AddBinding(Attr: TDOMAttr; PrefixPtr: DOMPChar; PrefixLen: Integer);
procedure PushVC(aElement: TDOMElement; aElDef: TDOMElementDef);
procedure PopVC;
procedure UpdateConstraints;
procedure ValidateDTD;
procedure ValidateRoot;
procedure ValidationError(const Msg: string; const args: array of const; LineOffs: Integer = -1);
procedure DoAttrText(ch: DOMPChar; Count: Integer);
procedure DTDReloadHook;
procedure ConvertSource(SrcIn: TXMLInputSource; out SrcOut: TXMLCharSource);
// Some SAX-alike stuff (at a very early stage)
procedure DoText(ch: DOMPChar; Count: Integer; Whitespace: Boolean=False);
procedure DoComment(ch: DOMPChar; Count: Integer);
procedure DoCDSect(ch: DOMPChar; Count: Integer);
procedure DoNotationDecl(const aName, aPubID, aSysID: DOMString);
public
doc: TDOMDocument;
constructor Create; overload;
constructor Create(AParser: TDOMParser); overload;
destructor Destroy; override;
procedure ProcessXML(ASource: TXMLCharSource); // [1]
procedure ProcessFragment(ASource: TXMLCharSource; AOwner: TDOMNode);
procedure ProcessDTD(ASource: TXMLCharSource); // ([29])
property Flags: TXMLReaderFlags read FFlags write SetFlags;
end;
// Attribute/Element declarations
TDOMElementDef = class(TDOMElement)
public
FExternallyDeclared: Boolean;
ContentType: TElementContentType;
IDAttr: TDOMAttrDef;
NotationAttr: TDOMAttrDef;
RootCP: TContentParticle;
destructor Destroy; override;
end;
const
NullLocation: TLocation = (Line: 0; LinePos: 0);
{ Decoders }
var
Decoders: array of TGetDecoderProc;
procedure RegisterDecoder(Proc: TGetDecoderProc);
var
L: Integer;
begin
L := Length(Decoders);
SetLength(Decoders, L+1);
Decoders[L] := Proc;
end;
function FindDecoder(const AEncoding: string; out Decoder: TDecoder): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to High(Decoders) do
if Decoders[I](AEncoding, Decoder) then
begin
Result := True;
Exit;
end;
end;
{$IFDEF UseUTF8}
function WriteUTF8(u: cardinal; var OutBuf: DOMPChar; var OutCnt: Cardinal): boolean; inline;
begin
case u of
0..$7f:
begin
if OutCnt<1 then exit(false);
dec(OutCnt);
OutBuf[0]:=char(byte(u));
inc(OutBuf);
end;
$80..$7ff:
begin
if OutCnt<2 then exit(false);
dec(OutCnt,2);
OutBuf[0]:=char(byte($c0 or (u shr 6)));
OutBuf[1]:=char(byte($80 or (u and $3f)));
inc(OutBuf,2);
end;
$800..$ffff:
begin
if OutCnt<3 then exit(false);
dec(OutCnt,3);
OutBuf[0]:=char(byte($e0 or (u shr 12)));
OutBuf[1]:=char(byte((u shr 6) and $3f) or $80);
OutBuf[2]:=char(byte(u and $3f) or $80);
inc(OutBuf,3);
end;
$10000..$10ffff:
begin
if OutCnt<4 then exit(false);
dec(OutCnt,4);
OutBuf[0]:=char(byte($f0 or (u shr 18)));
OutBuf[1]:=char(byte((u shr 12) and $3f) or $80);
OutBuf[2]:=char(byte((u shr 6) and $3f) or $80);
OutBuf[3]:=char(byte(u and $3f) or $80);
inc(OutBuf,3);
end;
else
exit(false);
end;
Result:=true;
end;
{$ENDIF}
function Decode_UCS2({%H-}Context: Pointer; InBuf: PChar; var InCnt: Cardinal; OutBuf: DOMPChar; var OutCnt: Cardinal): Integer; stdcall;
{$IFDEF UseUTF8}
var
u: cardinal;
OldOutCnt: cardinal;
begin
Result:=0;
OldOutCnt:=OutCnt;
while InCnt>1 do begin
u:=PWord(InBuf)^;
inc(InBuf,2);
if not WriteUTF8(u,OutBuf,OutCnt) then break;
dec(InCnt,2);
end;
Result:=OldOutCnt-OutCnt;
end;
{$ENDIF UseUTF8}
{$IFDEF UseWideString}
var
cnt: Cardinal;
begin
cnt := OutCnt; // num of DOMchars
if cnt > InCnt div sizeof(DOMChar) then
cnt := InCnt div sizeof(DOMChar);
Move(InBuf^, OutBuf^, cnt * sizeof(DOMChar));
Dec(InCnt, cnt*sizeof(DOMChar));
Dec(OutCnt, cnt);
Result := cnt;
end;
{$ENDIF UseWideString}
function Decode_UCS2_Swapped({%H-}Context: Pointer; InBuf: PChar; var InCnt: Cardinal; OutBuf: DOMPChar; var OutCnt: Cardinal): Integer; stdcall;
{$IFDEF UseUTF8}
var
u: cardinal;
OldOutCnt: cardinal;
begin
Result:=0;
OldOutCnt:=OutCnt;
while InCnt>1 do begin
u:=(ord(InBuf^) shl 8) or ord(InBuf[1]);
inc(InBuf,2);
if not WriteUTF8(u,OutBuf,OutCnt) then break;
dec(InCnt,2);
end;
Result:=OldOutCnt-OutCnt;
end;
{$ENDIF UseUTF8}
{$IFDEF UseWideString}
var
I: Integer;
cnt: Cardinal;
InPtr: PChar;
begin
cnt := OutCnt; // num of DOMchars
if cnt > InCnt div sizeof(DOMChar) then
cnt := InCnt div sizeof(DOMChar);
InPtr := InBuf;
for I := 0 to cnt-1 do
begin
OutBuf[I] := DOMChar((ord(InPtr^) shl 8) or ord(InPtr[1]));
Inc(InPtr, 2);
end;
Dec(InCnt, cnt*sizeof(DOMChar));
Dec(OutCnt, cnt);
Result := cnt;
end;
{$ENDIF UseWideString}
function Decode_88591({%H-}Context: Pointer; InBuf: PChar; var InCnt: Cardinal; OutBuf: DOMPChar; var OutCnt: Cardinal): Integer; stdcall;
{$IFDEF UseUTF8}
// convert ISO-8859-1 to UTF-8
var
u: cardinal;
OldOutCnt: cardinal;
begin
Result:=0;
OldOutCnt:=OutCnt;
while InCnt>0 do begin
u:=ord(InBuf^);
inc(InBuf);
if u<128 then begin
if OutCnt<1 then break;
dec(OutCnt);
OutBuf[0]:=char(byte(u));
inc(OutBuf);
end else if u<192 then begin
if OutCnt<2 then break;
dec(OutCnt,2);
OutBuf[0]:=#194;
OutBuf[1]:=char(byte(u));
inc(OutBuf,2);
end else begin
if OutCnt<2 then break;
dec(OutCnt,2);
OutBuf[0]:=#195;
OutBuf[1]:=char(byte(u-64));
inc(OutBuf,2);
end;
dec(InCnt);
end;
Result:=OldOutCnt-OutCnt;
end;
{$ENDIF UseUTF8}
{$IFDEF UseWideString}
var
I: Integer;
cnt: Cardinal;
begin
cnt := OutCnt; // num of DOMchars
if cnt > InCnt then
cnt := InCnt;
for I := 0 to cnt-1 do // ToDo: check for >#127
OutBuf[I] := DOMChar(ord(InBuf[I]));
Dec(InCnt, cnt);
Dec(OutCnt, cnt);
Result := cnt;
end;
{$ENDIF}
function Decode_UTF8({%H-}Context: Pointer; InBuf: PChar; var InCnt: Cardinal; OutBuf: DOMPChar; var OutCnt: Cardinal): Integer; stdcall;
{$IFDEF UseUTF8}
var
cnt: Cardinal;
begin
cnt := OutCnt; // num of DOMchars
if cnt > InCnt then
cnt := InCnt;
if cnt>0 then begin
System.Move(InBuf^,OutBuf^,cnt);
Dec(InCnt, cnt);
Dec(OutCnt, cnt);
end;
Result := cnt;
end;
{$ENDIF UseUTF8}
{$IFDEF UseWideString}
const
MaxCode: array[1..4] of Cardinal = ($7F, $7FF, $FFFF, $1FFFFF);
var
i, j, bc: Cardinal;
Value: Cardinal;
begin
result := 0;
i := OutCnt;
while (i > 0) and (InCnt > 0) do
begin
bc := 1;
Value := ord(InBuf^);
if Value < $80 then
OutBuf^ := DOMChar(Value)
else
begin
if Value < $C2 then
begin
Result := -1;
Break;
end;
Inc(bc);
if Value > $DF then
begin
Inc(bc);
if Value > $EF then
begin
Inc(bc);
if Value > $F7 then // never encountered in the tests.
begin
Result := -1;
Break;
end;
end;
end;
if InCnt < bc then
Break;
j := 1;
while j < bc do
begin
if InBuf[j] in [#$80..#$BF] then
Value := (Value shl 6) or (Cardinal(InBuf[j]) and $3F)
else
begin
Result := -1;
Break;
end;
Inc(j);
end;
Value := Value and MaxCode[bc];
// RFC2279 check
if Value <= MaxCode[bc-1] then
begin
Result := -1;
Break;
end;
case Value of
0..$D7FF, $E000..$FFFF: OutBuf^ := DOMChar(Value);
$10000..$10FFFF:
begin
if i < 2 then Break;
OutBuf^ := DOMChar($D7C0 + (Value shr 10));
OutBuf[1] := DOMChar($DC00 xor (Value and $3FF));
Inc(OutBuf); // once here
Dec(i);
end
else
begin
Result := -1;
Break;
end;
end;
end;
Inc(OutBuf);
Inc(InBuf, bc);
Dec(InCnt, bc);
Dec(i);
end;
if Result >= 0 then
Result := OutCnt-i;
OutCnt := i;
end;
{$ENDIF UseWideString}
function Is_8859_1(const AEncoding: string): Boolean;
begin
Result := SameText(AEncoding, 'ISO-8859-1') or
SameText(AEncoding, 'ISO_8859-1') or
SameText(AEncoding, 'latin1') or
SameText(AEncoding, 'iso-ir-100') or
SameText(AEncoding, 'l1') or
SameText(AEncoding, 'IBM819') or
SameText(AEncoding, 'CP819') or
SameText(AEncoding, 'csISOLatin1') or
// This one is not in character-sets.txt, but was used in FPC documentation,
// and still being used in fcl-registry package
SameText(AEncoding, 'ISO8859-1');
end;
function Is_UTF8(const AEncoding: String): Boolean;
begin
Result := SameText(AEncoding, 'UTF-8') or
SameText(AEncoding, 'UTF8');
end;
procedure BufAllocate(var ABuffer: TDOMCharBuf; ALength: Integer);
begin
ABuffer.MaxLength := ALength;
ABuffer.Length := 0;
ABuffer.Buffer := AllocMem(ABuffer.MaxLength*SizeOf(DOMChar));
end;
procedure BufAppend(var ABuffer: TDOMCharBuf; wc: DOMChar);
begin
if ABuffer.Length >= ABuffer.MaxLength then
begin
ReallocMem(ABuffer.Buffer, ABuffer.MaxLength * 2 * SizeOf(DOMChar));
FillChar(ABuffer.Buffer[ABuffer.MaxLength], ABuffer.MaxLength * SizeOf(DOMChar),0);
ABuffer.MaxLength := ABuffer.MaxLength * 2;
end;
ABuffer.Buffer[ABuffer.Length] := wc;
Inc(ABuffer.Length);
end;
procedure BufAppendChunk(var ABuf: TDOMCharBuf; pstart, pend: DOMPChar);
var
Len: Integer;
begin
Len := PEnd - PStart;
if Len <= 0 then
Exit;
if Len >= ABuf.MaxLength - ABuf.Length then
begin
ABuf.MaxLength := (Len + ABuf.Length)*2;
// note: memory clean isn't necessary here.
// To avoid garbage, control Length field.
ReallocMem(ABuf.Buffer, ABuf.MaxLength * sizeof(DOMChar));
end;
Move(pstart^, ABuf.Buffer[ABuf.Length], Len * sizeof(DOMChar));
Inc(ABuf.Length, Len);
end;
function BufEquals(const ABuf: TDOMCharBuf; const Arg: DOMString): Boolean;
begin
Result := (ABuf.Length = Length(Arg)) and
CompareMem(ABuf.Buffer, Pointer(Arg), ABuf.Length*sizeof(DOMChar));
end;
{ TDOMParseOptions }
function TDOMParseOptions.GetCanonical: Boolean;
begin
Result := FCanonical and FExpandEntities and FCDSectionsAsText and
{ (not normalizeCharacters) and } FNamespaces and
{ namespaceDeclarations and } FPreserveWhitespace;
end;
procedure TDOMParseOptions.SetCanonical(aValue: Boolean);
begin
FCanonical := aValue;
if aValue then
begin
FExpandEntities := True;
FCDSectionsAsText := True;
FNamespaces := True;
FPreserveWhitespace := True;
{ normalizeCharacters := False; }
{ namespaceDeclarations := True; }
{ wellFormed := True; }
end;
end;
{ TXMLInputSource }
constructor TXMLInputSource.Create(AStream: TStream);
begin
inherited Create;
FStream := AStream;
end;
constructor TXMLInputSource.Create(const AStringData: string);
begin
inherited Create;
FStringData := AStringData;
end;
{ TDOMParser }
constructor TDOMParser.Create;
begin
FOptions := TDOMParseOptions.Create;
end;
destructor TDOMParser.Destroy;
begin
FOptions.Free;
inherited Destroy;
end;
procedure TDOMParser.Parse(Src: TXMLInputSource; out ADoc: TXMLDocument);
var
InputSrc: TXMLCharSource;
begin
with TXMLReader.Create(Self) do
try
ConvertSource(Src, InputSrc); // handles 'no-input-specified' case
ProcessXML(InputSrc)
finally
ADoc := TXMLDocument(doc);
Free;
end;
end;
procedure TDOMParser.ParseUri(const URI: DOMString; out ADoc: TXMLDocument);
var
Src: TXMLCharSource;
begin
ADoc := nil;
with TXMLReader.Create(Self) do
try
if ResolveEntity(URI, '', '', Src) then
ProcessXML(Src)
else
DoErrorPos(esFatal, 'The specified URI could not be resolved', NullLocation);
finally
ADoc := TXMLDocument(doc);
Free;
end;
end;
function TDOMParser.ParseWithContext(Src: TXMLInputSource;
Context: TDOMNode; Action: TXMLContextAction): TDOMNode;
var
InputSrc: TXMLCharSource;
Frag: TDOMDocumentFragment;
node: TDOMNode;
begin
if Action in [xaInsertBefore, xaInsertAfter, xaReplace] then
node := Context.ParentNode
else
node := Context;
// TODO: replacing document isn't yet supported
if (Action = xaReplaceChildren) and (node.NodeType = DOCUMENT_NODE) then
raise EDOMNotSupported.Create('DOMParser.ParseWithContext');
if not (node.NodeType in [ELEMENT_NODE, DOCUMENT_FRAGMENT_NODE]) then
raise EDOMHierarchyRequest.Create('DOMParser.ParseWithContext');
with TXMLReader.Create(Self) do
try
ConvertSource(Src, InputSrc); // handles 'no-input-specified' case
Frag := Context.OwnerDocument.CreateDocumentFragment;
try
ProcessFragment(InputSrc, Frag);
Result := Frag.FirstChild;
case Action of
xaAppendAsChildren: Context.AppendChild(Frag);
xaReplaceChildren: begin
Context.TextContent := ''; // removes children
Context.ReplaceChild(Frag, Context.FirstChild);
end;
xaInsertBefore: node.InsertBefore(Frag, Context);
xaInsertAfter: node.InsertBefore(Frag, Context.NextSibling);
xaReplace: node.ReplaceChild(Frag, Context);
end;
finally
Frag.Free;
end;
finally
Free;
end;
end;
{ TXMLCharSource }
constructor TXMLCharSource.Create(const AData: DOMString);
begin
inherited Create;
FLineNo := 1;
FBuf := DOMPChar(AData);
FBufEnd := FBuf + Length(AData);
LFPos := FBuf-1;
FCharCount := Length(AData);
end;
procedure TXMLCharSource.Initialize;
begin
end;
function TXMLCharSource.SetEncoding(const AEncoding: string): Boolean;
begin
Result := True; // always succeed
end;
function TXMLCharSource.GetSystemID: DOMString;
begin
if FSystemID <> '' then
Result := FSystemID
else if Assigned(FParent) then
Result := FParent.SystemID
else
Result := '';
end;
function TXMLCharSource.Reload: Boolean;
begin
Result := False;
end;
procedure TXMLCharSource.NewLine;
begin
Inc(FLineNo);
LFPos := FBuf;
end;
function TXMLCharSource.SkipUntil(var ToFill: TDOMCharBuf; const Delim: TSetOfChar;
wsflag: PBoolean; AllowSpecialChars: boolean): DOMChar;
var
old: DOMPChar;
nonws: Boolean;
begin
old := FBuf;
nonws := False;
repeat
if FBuf^ = #10 then
NewLine;
if (FBuf^ < #255) and (Char(ord(FBuf^)) in Delim) then
Break;
if (FBuf^ > #32) or not (Char(ord(FBuf^)) in [#32, #9, #10, #13]) then
nonws := True;
Inc(FBuf);
until False;
Result := FBuf^;
BufAppendChunk(ToFill, old, FBuf);
if Assigned(wsflag) then
wsflag^ := wsflag^ or nonws;
end;
function TXMLCharSource.Matches(const arg: DOMString): Boolean;
begin
Result := False;
if (FBufEnd >= FBuf + Length(arg)) or Reload then
Result := CompareMem(Pointer(arg), FBuf, Length(arg)*sizeof(DOMChar));
if Result then
begin
Inc(FBuf, Length(arg));
if FBuf >= FBufEnd then
Reload;
end;
end;
{ TXMLDecodingSource }
procedure TXMLDecodingSource.AfterConstruction;
begin
inherited AfterConstruction;
FBufStart := AllocMem(4096);
FBuf := FBufStart;
FBufEnd := FBuf;
LFPos := FBuf-1;
end;
destructor TXMLDecodingSource.Destroy;
begin
FreeMem(FBufStart);
if Assigned(FDecoder.Cleanup) then
FDecoder.Cleanup(FDecoder.Context);
inherited Destroy;
end;
procedure TXMLDecodingSource.FetchData;
begin
end;
procedure TXMLDecodingSource.DecodingError(const Msg: string);
begin
// count line endings to obtain correct error location
while FBuf < FBufEnd do
begin
if (FBuf^ = #10) or (FBuf^ = #13)
or (FXML11Rules and ((FBuf^ = #$85) or (FBuf^ = #$2028))) // ToDo #$2028
then begin
if (FBuf^ = #13) and (FBuf < FBufEnd-1) and
((FBuf[1] = #10) or (FXML11Rules and (FBuf[1] = #$85))) then
Inc(FBuf);
LFPos := FBuf;
Inc(FLineNo);
end;
Inc(FBuf);
end;
FReader.FatalError(Msg);
end;
function TXMLDecodingSource.Reload: Boolean;
var
Remainder: PtrInt;
r, inLeft: Cardinal;
rslt: Integer;
begin
if DTDSubsetType = dsInternal then
FReader.DTDReloadHook;
Remainder := FBufEnd - FBuf;
if Remainder > 0 then
Move(FBuf^, FBufStart^, Remainder * sizeof(DOMChar));
Dec(LFPos, FBuf-FBufStart);
FBuf := FBufStart;
FBufEnd := FBufStart + Remainder;
repeat
inLeft := FCharBufEnd - FCharBuf;
if inLeft < 4 then // may contain an incomplete char
begin
FetchData;
inLeft := FCharBufEnd - FCharBuf;
if inLeft <= 0 then
Break;
end;
r := FBufStart + FBufSize - FBufEnd;
if r = 0 then
Break;
rslt := FDecoder.Decode(FDecoder.Context, FCharBuf, inLeft, FBufEnd, r);
{ Sanity checks: r and inLeft must not increase. }
if inLeft + FCharBuf <= FCharBufEnd then
FCharBuf := FCharBufEnd - inLeft
else
DecodingError('Decoder error: input byte count out of bounds');
if r + FBufEnd <= FBufStart + FBufSize then
FBufEnd := FBufStart + FBufSize - r
else
DecodingError('Decoder error: output char count out of bounds');
if rslt = 0 then
Break
else if rslt < 0 then
DecodingError('Invalid character in input stream')
else
begin
Inc(FCharCount, Cardinal(rslt));
FReader.CheckMaxChars;
end;
until False;
FBufEnd^ := #0;
Result := FBuf < FBufEnd;
end;
const
XmlSign: array [0..4] of DOMChar = ('<', '?', 'x', 'm', 'l');
procedure TXMLDecodingSource.Initialize;
begin
inherited;
FLineNo := 1;
FXml11Rules := FReader.FXML11;
FDecoder.Decode := @Decode_UTF8;
{$IFDEF UseWideString}
FFixedUCS2 := '';
if FCharBufEnd-FCharBuf > 1 then
begin
if (FCharBuf[0] = #$FE) and (FCharBuf[1] = #$FF) then
begin
FFixedUCS2 := 'UTF-16BE';
FDecoder.Decode := {$IFNDEF ENDIAN_BIG} @Decode_UCS2_Swapped {$ELSE} @Decode_UCS2 {$ENDIF};
end
else if (FCharBuf[0] = #$FF) and (FCharBuf[1] = #$FE) then
begin
FFixedUCS2 := 'UTF-16LE';
FDecoder.Decode := {$IFDEF ENDIAN_BIG} @Decode_UCS2_Swapped {$ELSE} @Decode_UCS2 {$ENDIF};
end;
end;
{$ENDIF}
FBufSize := 8; // possible BOM and '<?xml'
Reload;
{$IFDEF UseWideString}
if FBuf^ = #$FEFF then
begin
FHasBOM := True;
Inc(FBuf);
end;
{$ELSE}
if (FBuf[0]=#$EF) and (FBuf[1]=#$BB) and (FBuf[2]=#$BF) then begin
FHasBOM := true;
inc(FBuf,3);
end;
{$ENDIF}
LFPos := FBuf-1;
if CompareMem(FBuf, @XmlSign[0], sizeof(XmlSign)) then
begin
FBufSize := 3; // don't decode past XML declaration
Inc(FBuf, Length(XmlSign));
FReader.ParseXmlOrTextDecl(FParent <> nil);
end;
FBufSize := 2047;
end;
function TXMLDecodingSource.SetEncoding(const AEncoding: string): Boolean;
var
NewDecoder: TDecoder;
begin
Result := True;
{$IFDEF UseWideString}
if (FFixedUCS2 = '') and Is_UTF8(AEncoding) then
Exit;
if FFixedUCS2 <> '' then
begin
Result := SameText(AEncoding, FFixedUCS2) or
SameText(AEncoding, 'UTF-16') or
SameText(AEncoding, 'unicode');
Exit;
end;
// TODO: must fail when a byte-based stream is labeled as word-based.
// see rmt-e2e-61, it now fails but for a completely different reason.
{$ELSE}
if IS_UTF8(AEncoding) then
Exit;
{$ENDIF}
FillChar(NewDecoder{%H-}, sizeof(TDecoder), 0);
if Is_8859_1(AEncoding) then
FDecoder.Decode := @Decode_88591
else if FindDecoder(AEncoding, NewDecoder) then
FDecoder := NewDecoder
else
Result := False;
end;
procedure TXMLDecodingSource.NewLine;
begin
case FBuf^ of
#10: begin
Inc(FLineNo);
LFPos := FBuf;
end;
#13: begin
Inc(FLineNo);
LFPos := FBuf;
// Reload trashes the buffer, it should be consumed beforehand
if (FBufEnd >= FBuf+2) or Reload then
begin
if (FBuf[1] = #10) or (FXML11Rules and (FBuf[1] = #$85)) then
begin
Inc(FBuf);
Inc(LFPos);
end;
FBuf^ := #10;
end;
end;
#$85:
if FXML11Rules then
begin
FBuf^ := #10;
Inc(FLineNo);
LFPos := FBuf;
end;
end;
end;
{ TXMLStreamInputSource }
const
Slack = 16;
constructor TXMLStreamInputSource.Create(AStream: TStream; AOwnStream: Boolean);
begin
FStream := AStream;
FCapacity := 4096;
GetMem(FAllocated, FCapacity+Slack);
FCharBuf := FAllocated+(Slack-4);
FCharBufEnd := FCharBuf;
FOwnStream := AOwnStream;
FetchData;
end;
destructor TXMLStreamInputSource.Destroy;
begin
FreeMem(FAllocated);
if FOwnStream then
FStream.Free;
inherited Destroy;
end;
procedure TXMLStreamInputSource.FetchData;
var
Remainder, BytesRead: Integer;
OldBuf: PChar;
begin
Assert(FCharBufEnd - FCharBuf < Slack-4);
if FEof then
Exit;
OldBuf := FCharBuf;
Remainder := FCharBufEnd - FCharBuf;
if Remainder < 0 then
Remainder := 0;
FCharBuf := FAllocated+Slack-4-Remainder;
if Remainder > 0 then
Move(OldBuf^, FCharBuf^, Remainder);
BytesRead := FStream.Read(FAllocated[Slack-4], FCapacity);
if BytesRead < FCapacity then
FEof := True;
FCharBufEnd := FAllocated + (Slack-4) + BytesRead;
{ Null-termination has been removed:
1) Built-in decoders don't need it because they respect the buffer length.
2) It was causing unaligned access errors on ARM CPUs.
}
//DOMPChar(FCharBufEnd)^ := #0;
end;
{ TXMLFileInputSource }
constructor TXMLFileInputSource.Create(var AFile: Text);
begin
FFile := @AFile;
SystemID := FilenameToURI(TTextRec(AFile).Name);
FetchData;
end;
procedure TXMLFileInputSource.FetchData;
var
Remainder: Integer;
begin
if not Eof(FFile^) then
begin
Remainder := FCharBufEnd - FCharBuf;
if Remainder > 0 then
SetString(FTmp, FCharBuf, Remainder);
ReadLn(FFile^, FString);
FString := FString + #10; // bad solution...
if Remainder > 0 then
Insert(FTmp, FString, 1);
FCharBuf := PChar(FString);
FCharBufEnd := FCharBuf + Length(FString);
end;
end;
{ helper that closes handle upon destruction }
type
THandleOwnerStream = class(THandleStream)
public
destructor Destroy; override;
end;
destructor THandleOwnerStream.Destroy;
begin
FileClose(Handle);
inherited Destroy;
end;
{ TXMLReader }
procedure TXMLReader.ConvertSource(SrcIn: TXMLInputSource; out SrcOut: TXMLCharSource);
begin
SrcOut := nil;
if Assigned(SrcIn) then
begin
if Assigned(SrcIn.FStream) then
SrcOut := TXMLStreamInputSource.Create(SrcIn.FStream, False)
else if SrcIn.FStringData <> '' then
SrcOut := TXMLStreamInputSource.Create(TStringStream.Create(SrcIn.FStringData), True)
else if (SrcIn.SystemID <> '') then
ResolveEntity(SrcIn.SystemID, SrcIn.PublicID, SrcIn.BaseURI, SrcOut);
end;
if (SrcOut = nil) and (FSource = nil) then
DoErrorPos(esFatal, 'No input source specified', NullLocation);
end;
procedure TXMLReader.StoreLocation(out Loc: TLocation);
begin
Loc.Line := FSource.FLineNo;
Loc.LinePos := FSource.FBuf-FSource.LFPos;
end;
function TXMLReader.ResolveEntity(const SystemID, PublicID, BaseURI: DOMString; out Source: TXMLCharSource): Boolean;
var
AbsSysID: DOMString;
Filename: string;
Stream: TStream;
fd: THandle;
begin
Source := nil;
Result := False;
if not ResolveRelativeURI(BaseURI, SystemID, AbsSysID) then
Exit;
{ TODO: alternative resolvers
These may be 'internal' resolvers or a handler set by application.
Internal resolvers should probably produce a TStream
( so that internal classes need not be exported ).
External resolver will produce TXMLInputSource that should be converted.
External resolver must NOT be called for root entity.
External resolver can return nil, in which case we do the default }
if URIToFilename(AbsSysID, Filename) then
begin
fd := FileOpen(Filename, fmOpenRead + fmShareDenyWrite);
if fd <> THandle(-1) then
begin
Stream := THandleOwnerStream.Create(fd);
Source := TXMLStreamInputSource.Create(Stream, True);
Source.SystemID := AbsSysID; // <- Revisit: Really need absolute sysID?
end;
end;
Result := Assigned(Source);
end;
procedure TXMLReader.Initialize(ASource: TXMLCharSource);
begin
ASource.FParent := FSource;
FSource := ASource;
FSource.FReader := Self;
FSource.FStartNesting := FNesting;
FSource.Initialize;
end;
procedure TXMLReader.FatalError(Expected: DOMChar);
begin
// FIX: don't output what is found - anything may be found, including exploits...
FatalError('Expected "%1s"', [string(Expected)]);
end;
procedure TXMLReader.FatalError(const descr: String; LineOffs: Integer);
begin
DoError(esFatal, descr, LineOffs);
end;
procedure TXMLReader.FatalError(const descr: string; const args: array of const; LineOffs: Integer);
begin
DoError(esFatal, Format(descr, args), LineOffs);
end;
procedure TXMLReader.ValidationError(const Msg: string;
const args: array of const; LineOffs: Integer);
begin
FDocNotValid := True;
if FValidate then
DoError(esError, Format(Msg, Args), LineOffs);
end;
procedure TXMLReader.DoError(Severity: TErrorSeverity; const descr: string; LineOffs: Integer);
var
Loc: TLocation;
begin
StoreLocation(Loc);
if LineOffs >= 0 then
begin
Dec(Loc.LinePos, LineOffs);
DoErrorPos(Severity, descr, Loc);
end
else
DoErrorPos(Severity, descr, FTokenStart);
end;
procedure TXMLReader.DoErrorPos(Severity: TErrorSeverity; const descr: string; const ErrPos: TLocation);
var
E: EXMLReadError;
sysid: DOMString;
begin
if Assigned(FSource) then
begin
sysid := FSource.FSystemID;
if (sysid = '') and Assigned(FSource.FEntity) then
sysid := TDOMEntityEx(FSource.FEntity).FURI;
E := EXMLReadError.CreateFmt('In ''%s'' (line %d pos %d): %s', [sysid, ErrPos.Line, ErrPos.LinePos, descr]);
end
else
E := EXMLReadError.Create(descr);
E.FSeverity := Severity;
E.FErrorMessage := descr;
E.FLine := ErrPos.Line;
E.FLinePos := ErrPos.LinePos;
CallErrorHandler(E);
// No 'finally'! If user handler raises exception, control should not get here
// and the exception will be freed in CallErrorHandler (below)
E.Free;
end;
procedure TXMLReader.CheckMaxChars;
var
src: TXMLCharSource;
total: Cardinal;
begin
if FMaxChars = 0 then
Exit;
src := FSource;
total := 0;
repeat
Inc(total, src.FCharCount);
if total > FMaxChars then
FatalError('Exceeded character count limit');
src := src.FParent;
until src = nil;
end;
procedure TXMLReader.CallErrorHandler(E: EXMLReadError);
begin
try
if Assigned(FCtrl) and Assigned(FCtrl.FOnError) then
FCtrl.FOnError(E);
if E.Severity = esFatal then
raise E;
except
if ExceptObject <> E then
E.Free;
raise;
end;
end;
function TXMLReader.SkipWhitespace(PercentAloneIsOk: Boolean): Boolean;
begin
Result := False;
repeat
Result := SkipS or Result;
if FSource.FBuf^ = #0 then
begin
Result := True; // report whitespace upon exiting the PE
if not ContextPop then
Break;
end
else if FSource.FBuf^ = '%' then
begin
if not FRecognizePE then
Break;
// This is the only case where look-ahead is needed
if FSource.FBuf > FSource.FBufEnd-2 then
FSource.Reload;
if (not PercentAloneIsOk) or (Byte(FSource.FBuf[1]) in NamingBitmap[FNamePages^[$100+hi(Word(FSource.FBuf[1]))]]) or
(FXML11 and (FSource.FBuf[1] >= #$D800) and (FSource.FBuf[1] <= #$DB7F)) then
begin
Inc(FSource.FBuf); // skip '%'
CheckName;
ExpectChar(';');
StartPE;
Result := True; // report whitespace upon entering the PE
end
else Break;
end
else
Break;
until False;
end;
procedure TXMLReader.ExpectWhitespace;
begin
if not SkipWhitespace then
FatalError('Expected whitespace');
end;
function TXMLReader.SkipS(required: Boolean): Boolean;
var
p: DOMPChar;
begin
Result := False;
repeat
p := FSource.FBuf;
repeat
if (p^ = #10) or (p^ = #13)
or (FXML11 and ((p^ = #$85) or (p^ = #$2028))) // ToDo #$2028
then begin
FSource.FBuf := p;
FSource.NewLine;
p := FSource.FBuf;
end
else if (p^ <> #32) and (p^ <> #9) then
Break;
Inc(p);
Result := True;
until False;
FSource.FBuf := p;
until (p^ <> #0) or (not FSource.Reload);
if (not Result) and Required then
FatalError('Expected whitespace');
end;
procedure TXMLReader.ExpectString(const s: String);
var
I: Integer;
begin
for I := 1 to Length(s) do
begin
if FSource.FBuf^ <> DOMChar(ord(s[i])) then
FatalError('Expected "%s"', [s], i-1);
FSource.NextChar;
end;
end;
function TXMLReader.CheckForChar(c: DOMChar): Boolean;
begin
Result := (FSource.FBuf^ = c);
if Result then
begin
Inc(FSource.FBuf);
if FSource.FBuf >= FSource.FBufEnd then
FSource.Reload;
end;
end;
procedure TXMLReader.SkipQuote(out Delim: DOMChar; required: Boolean);
begin
Delim := #0;
if (FSource.FBuf^ = '''') or (FSource.FBuf^ = '"') then
begin
Delim := FSource.FBuf^;
FSource.NextChar; // skip quote
StoreLocation(FTokenStart);
end
else if required then
FatalError('Expected single or double quote');
end;
procedure TXMLReader.SetFlags(AValue: TXMLReaderFlags);
begin
if FFlags=AValue then Exit;
FFlags:=AValue;
FPreserveWhitespace:=xrfPreserveWhiteSpace in Flags;
end;
const
PrefixDefault: array[0..4] of DOMChar = ('x','m','l','n','s');
constructor TXMLReader.Create;
begin
inherited Create;
BufAllocate(FName, 128);
BufAllocate(FValue, 512);
FIDRefs := TFPList.Create;
FNotationRefs := TFPList.Create;
FNSHelper := TNSSupport.Create;
FNsAttHash := TDblHashArray.Create;
SetLength(FWorkAtts, 16);
FStdPrefix_xml := FNSHelper.GetPrefix(@PrefixDefault, 3);
FStdPrefix_xmlns := FNSHelper.GetPrefix(@PrefixDefault, 5);
// Set char rules to XML 1.0
FNamePages := @NamePages;
SetLength(FValidator, 16);
end;
constructor TXMLReader.Create(AParser: TDOMParser);
begin
Create;
FCtrl := AParser;
FValidate := FCtrl.Options.Validate;
FPreserveWhitespace := FCtrl.Options.PreserveWhitespace;
FExpandEntities := FCtrl.Options.ExpandEntities;
FCDSectionsAsText := FCtrl.Options.CDSectionsAsText;
FIgnoreComments := FCtrl.Options.IgnoreComments;
FResolveExternals := FCtrl.Options.ResolveExternals;
FNamespaces := FCtrl.Options.Namespaces;
FDisallowDoctype := FCtrl.Options.DisallowDoctype;
FCanonical := FCtrl.Options.CanonicalForm;
FMaxChars := FCtrl.Options.MaxChars;
end;
destructor TXMLReader.Destroy;
begin
if Assigned(FEntityValue.Buffer) then
FreeMem(FEntityValue.Buffer);
FreeMem(FName.Buffer);
FreeMem(FValue.Buffer);
if Assigned(FSource) then
while ContextPop(True) do; // clean input stack
FSource.Free;
FPEMap.Free;
ClearRefs(FNotationRefs);
ClearRefs(FIDRefs);
FNsAttHash.Free;
FNSHelper.Free;
if FOwnsDoctype then
FDocType.Free;
FNotationRefs.Free;
FIDRefs.Free;
inherited Destroy;
end;
procedure TXMLReader.XML11_BuildTables;
begin
FNamePages := Xml11NamePages;
FXML11 := True;
FSource.FXml11Rules := True;
end;
procedure TXMLReader.ProcessXML(ASource: TXMLCharSource);
begin
doc := TXMLDocument.Create;
doc.documentURI := ASource.SystemID; // TODO: to be changed to URI or BaseURI
FCursor := doc;
FState := rsProlog;
FNesting := 0;
Initialize(ASource);
ParseContent;
if FState < rsRoot then
FatalError('Root element is missing');
if FValidate and Assigned(FDocType) then
ValidateIdRefs;
end;
procedure TXMLReader.ProcessFragment(ASource: TXMLCharSource; AOwner: TDOMNode);
begin
doc := AOwner.OwnerDocument;
FCursor := AOwner as TDOMNode_WithChildren;
FState := rsRoot;
Initialize(ASource);
FXML11 := doc.InheritsFrom(TXMLDocument) and (TXMLDocument(doc).XMLVersion = '1.1');
ParseContent;
end;
function TXMLReader.CheckName(aFlags: TCheckNameFlags): Boolean;
var
p: DOMPChar;
NameStartFlag: Boolean;
begin
p := FSource.FBuf;
FName.Length := 0;
FColonPos := -1;
NameStartFlag := not (cnToken in aFlags);
//writeln('TXMLReader.CheckName ',PtrUInt(FSource.FBuf),' ',ord(p^));
repeat
if NameStartFlag then
begin
if {$IFDEF UseWideString}
(Byte(p^) in NamingBitmap[FNamePages^[hi(Word(p^))]])
{$ELSE}
IsNameStartChar[p^]
{$ENDIF}
or ((p^ = ':') and (not FNamespaces)) then
begin
Inc(p);
end
{$IFDEF UseWideString}
else if FXML11 and ((p^ >= #$D800) and (p^ <= #$DB7F) and
(p[1] >= #$DC00) and (p[1] <= #$DFFF)) then
begin
Inc(p, 2);
end
{$ENDIF}
else
begin
// here we come either when first char of name is bad (it may be a colon),
// or when a colon is not followed by a valid NameStartChar
Result := False;
Break;
end;
NameStartFlag := False;
end;
{$IFDEF UseWideString}
if FXML11 then begin
repeat
if Byte(p^) in NamingBitmap[FNamePages^[$100+hi(Word(p^))]] then
Inc(p)
else if ((p^ >= #$D800) and (p^ <= #$DB7F) and
(p[1] >= #$DC00) and (p[1] <= #$DFFF)) then
Inc(p,2)
else
Break;
until False;
end
else
while Byte(p^) in NamingBitmap[FNamePages^[$100+hi(Word(p^))]] do
Inc(p);
{$ELSE}
while IsNameChar[p^] do inc(p);
{$ENDIF}
if p^ = ':' then
begin
if (cnToken in aFlags) or not FNamespaces then // colon has no specific meaning
begin
Inc(p);
if p^ <> #0 then Continue;
end
else if FColonPos = -1 then // this is the first colon, remember it
begin
FColonPos := p-FSource.FBuf+FName.Length;
NameStartFlag := True;
Inc(p);
if p^ <> #0 then Continue;
end;
end;
BufAppendChunk(FName, FSource.FBuf, p);
Result := (FName.Length > 0);
FSource.FBuf := p;
if (p^ <> #0) or not FSource.Reload then
Break;
p := FSource.FBuf;
until False;
//writeln('TXMLReader.CheckName END ',PtrUInt(FSource.FBuf),' Result=',Result);
if not (Result or (cnOptional in aFlags)) then
RaiseNameNotFound;
end;
procedure TXMLReader.CheckNCName;
begin
if FNamespaces and (FColonPos <> -1) then
FatalError('Names of entities, notations and processing instructions may not contain colons', FName.Length);
end;
procedure TXMLReader.RaiseNameNotFound;
begin
if FColonPos <> -1 then
FatalError('Bad QName syntax, local part is missing')
else
// Coming at no cost, this allows more user-friendly error messages
with FSource do
if (FBuf^ = #32) or (FBuf^ = #10) or (FBuf^ = #9) or (FBuf^ = #13) then
FatalError('Whitespace is not allowed here')
else
FatalError('Name starts with invalid character '+IntToStr(ord(fbuf^)));
end;
function TXMLReader.ExpectName: DOMString;
begin
CheckName;
SetString(Result, FName.Buffer, FName.Length);
end;
function TXMLReader.ResolvePredefined: Boolean;
var
wc: DOMChar;
begin
Result := False;
with FName do
begin
if (Length = 2) and (Buffer[1] = 't') then
begin
if Buffer[0] = 'l' then
wc := '<'
else if Buffer[0] = 'g' then
wc := '>'
else Exit;
end
else if Buffer[0] = 'a' then
begin
if (Length = 3) and (Buffer[1] = 'm') and (Buffer[2] = 'p') then
wc := '&'
else if (Length = 4) and (Buffer[1] = 'p') and (Buffer[2] = 'o') and
(Buffer[3] = 's') then
wc := ''''
else Exit;
end
else if (Length = 4) and (Buffer[0] = 'q') and (Buffer[1] = 'u') and
(Buffer[2] = 'o') and (Buffer[3] ='t') then
wc := '"'
else
Exit;
end; // with
BufAppend(FValue, wc);
Result := True;
end;
function TXMLReader.ParseRef(var ToFill: TDOMCharBuf): Boolean; // [67]
var
Value: Integer;
begin
FSource.NextChar; // skip '&'
Result := CheckForChar('#');
if Result then
begin
Value := 0;
if CheckForChar('x') then
repeat
case FSource.FBuf^ of
'0'..'9': Value := Value * 16 + Ord(FSource.FBuf^) - Ord('0');
'a'..'f': Value := Value * 16 + Ord(FSource.FBuf^) - (Ord('a') - 10);
'A'..'F': Value := Value * 16 + Ord(FSource.FBuf^) - (Ord('A') - 10);
else
Break;
end;
FSource.NextChar;
until Value > $10FFFF
else
repeat
case FSource.FBuf^ of
'0'..'9': Value := Value * 10 + Ord(FSource.FBuf^) - Ord('0');
else
Break;
end;
FSource.NextChar;
until Value > $10FFFF;
case Value of
$01..$08, $0B..$0C, $0E..$1F:
if FXML11 or (xrfAllowSpecialCharsInAttributeValue in FFlags) then
BufAppend(ToFill, DOMChar(Value))
else
FatalError('Invalid character reference');
$09, $0A, $0D, $20..$7F:
BufAppend(ToFill, DOMChar(Value));
{$IFDEF UseUTF8}
$80..$7ff:
begin
BufAppend(ToFill, DOMChar(byte($c0 or (Value shr 6))));
BufAppend(ToFill, DOMChar(byte($80 or (Value and $3f))));
end;
$800..$ffff:
begin
BufAppend(ToFill, DOMChar(byte($e0 or (Value shr 12))));
BufAppend(ToFill, DOMChar(byte((Value shr 6) and $3f) or $80));
BufAppend(ToFill, DOMChar(byte(Value and $3f) or $80));
end;
$10000..$10ffff:
begin
BufAppend(ToFill, DOMChar(byte($f0 or (Value shr 18))));
BufAppend(ToFill, DOMChar(byte((Value shr 12) and $3f) or $80));
BufAppend(ToFill, DOMChar(byte((Value shr 6) and $3f) or $80));
BufAppend(ToFill, DOMChar(byte(Value and $3f) or $80));
end;
{$ENDIF}
{$IFDEF UseWideString}
$D7FF, $E000..$FFFD:
BufAppend(ToFill, DOMChar(Value));
$10000..$10FFFF:
begin
BufAppend(ToFill, DOMChar($D7C0 + (Value shr 10)));
BufAppend(ToFill, DOMChar($DC00 xor (Value and $3FF)));
end;
{$ENDIF}
else
FatalError('Invalid character reference');
end;
end
else CheckName;
ExpectChar(';');
end;
const
AttrDelims: array[boolean] of TSetOfChar = (
[#0, '<', '&', '''', '"', #9, #10, #13], // false: default
[#0, '<', '&', '''', '"'] // true: xrfAllowSpecialCharsInAttributeValue
);
GT_Delim: TSetOfChar = [#0, '>'];
procedure TXMLReader.ExpectAttValue;
var
wc: DOMChar;
Delim: DOMChar;
ent: TDOMEntityEx;
start: TObject;
AllowSpecialChars: boolean;
begin
SkipQuote(Delim);
FValue.Length := 0;
start := FSource.FEntity;
AllowSpecialChars:=xrfAllowSpecialCharsInAttributeValue in Flags;
repeat
wc := FSource.SkipUntil(FValue, AttrDelims[AllowSpecialChars], nil, AllowSpecialChars);
if (wc = '<') and (not (xrfAllowLowerThanInAttributeValue in Flags)) then
FatalError('Character ''<'' is not allowed in attribute value')
else if wc = '&' then
begin
if ParseRef(FValue) or ResolvePredefined then
Continue;
ent := EntityCheck(True);
if (ent = nil) or (not FExpandEntities) then
begin
if FValue.Length > 0 then
begin
DoAttrText(FValue.Buffer, FValue.Length);
FValue.Length := 0;
end;
AppendReference(ent);
end
else
ContextPush(ent);
end
else if wc <> #0 then
begin
FSource.NextChar;
if (wc = Delim) and (FSource.FEntity = start) then
Break;
if (not FPreserveWhitespace) and (ord(wc) in [9,10,13]) then
wc := #32;
BufAppend(FValue, wc);
end
else if (FSource.FEntity = start) or not ContextPop then // #0
FatalError('Literal has no closing quote', -1);
until False;
if FValue.Length > 0 then
DoAttrText(FValue.Buffer, FValue.Length);
FValue.Length := 0;
end;
const
PrefixChar: array[Boolean] of string = ('', '%');
function TXMLReader.ContextPush(AEntity: TDOMEntityEx): Boolean;
var
Src: TXMLCharSource;
begin
if AEntity.FOnStack then
FatalError('Entity ''%s%s'' recursively references itself', [PrefixChar[AEntity.FIsPE], AEntity.FName]);
if (AEntity.SystemID <> '') and not AEntity.FPrefetched then
begin
Result := ResolveEntity(AEntity.SystemID, AEntity.PublicID, AEntity.FURI, Src);
if not Result then
begin
// TODO: a detailed message like SysErrorMessage(GetLastError) would be great here
ValidationError('Unable to resolve external entity ''%s''', [AEntity.FName]);
Exit;
end;
end
else
begin
Src := TXMLCharSource.Create(AEntity.FReplacementText);
Src.FLineNo := AEntity.FStartLocation.Line;
Src.LFPos := Src.FBuf - AEntity.FStartLocation.LinePos;
// needed in case of prefetched external PE
if AEntity.SystemID <> '' then
Src.SystemID := AEntity.FURI;
end;
AEntity.FOnStack := True;
Src.FEntity := AEntity;
Initialize(Src);
Result := True;
end;
function TXMLReader.ContextPop(Forced: Boolean): Boolean;
var
Src: TXMLCharSource;
Error: Boolean;
begin
Result := Assigned(FSource.FParent) and (Forced or (FSource.DTDSubsetType = dsNone));
if Result then
begin
Src := FSource.FParent;
Error := False;
if Assigned(FSource.FEntity) then
begin
TDOMEntityEx(FSource.FEntity).FOnStack := False;
TDOMEntityEx(FSource.FEntity).FCharCount := FSource.FCharCount;
// [28a] PE that was started between MarkupDecls may not end inside MarkupDecl
Error := TDOMEntityEx(FSource.FEntity).FBetweenDecls and FInsideDecl;
end;
FSource.Free;
FSource := Src;
// correct position of this error is after PE reference
if Error then
BadPENesting(esFatal);
end;
end;
function TXMLReader.EntityCheck(NoExternals: Boolean): TDOMEntityEx;
var
RefName: DOMString;
cnt: Integer;
SaveCursor: TDOMNode_WithChildren;
SaveState: TXMLReadState;
SaveElDef: TDOMElementDef;
SaveValue: TDOMCharBuf;
begin
Result := nil;
SetString(RefName, FName.Buffer, FName.Length);
cnt := FName.Length+2;
if Assigned(FDocType) then
Result := FDocType.Entities.GetNamedItem(RefName) as TDOMEntityEx;
if Result = nil then
begin
if FStandalone or (FDocType = nil) or not (FHavePERefs or (FDocType.SystemID <> '')) then
FatalError('Reference to undefined entity ''%s''', [RefName], cnt)
else
ValidationError('Undefined entity ''%s'' referenced', [RefName], cnt);
Exit;
end;
if FStandalone and Result.FExternallyDeclared then
FatalError('Standalone constraint violation', cnt);
if Result.NotationName <> '' then
FatalError('Reference to unparsed entity ''%s''', [RefName], cnt);
if NoExternals and (Result.SystemID <> '') then
FatalError('External entity reference is not allowed in attribute value', cnt);
if not Result.FResolved then
begin
// To build children of the entity itself, we must parse it "out of context"
SaveCursor := FCursor;
SaveElDef := FValidator[FNesting].FElementDef;
SaveState := FState;
SaveValue := FValue;
if ContextPush(Result) then
try
FCursor := Result; // build child node tree for the entity
Result.SetReadOnly(False);
FState := rsRoot;
FValidator[FNesting].FElementDef := nil;
UpdateConstraints;
FSource.DTDSubsetType := dsExternal; // avoids ContextPop at the end
BufAllocate(FValue, 256);
ParseContent;
Result.FResolved := True;
finally
FreeMem(FValue.Buffer);
FValue := SaveValue;
Result.SetReadOnly(True);
ContextPop(True);
FCursor := SaveCursor;
FState := SaveState;
FValidator[FNesting].FElementDef := SaveElDef;
UpdateConstraints;
end;
end;
// at this point we know the charcount of the entity being included
Inc(FSource.FCharCount, Result.FCharCount - cnt);
CheckMaxChars;
end;
procedure TXMLReader.StartPE;
var
PEName: DOMString;
PEnt: TDOMEntityEx;
begin
SetString(PEName, FName.Buffer, FName.Length);
PEnt := nil;
if Assigned(FPEMap) then
PEnt := FPEMap.GetNamedItem(PEName) as TDOMEntityEx;
if PEnt = nil then
begin
ValidationError('Undefined parameter entity ''%s'' referenced', [PEName], FName.Length+2);
// cease processing declarations, unless document is standalone.
FDTDProcessed := FStandalone;
Exit;
end;
{ cache an external PE so it's only fetched once }
if (PEnt.SystemID <> '') and (not PEnt.FPrefetched) and (not PrefetchEntity(PEnt)) then
begin
FDTDProcessed := FStandalone;
Exit;
end;
Inc(FSource.FCharCount, PEnt.FCharCount);
CheckMaxChars;
PEnt.FBetweenDecls := not FInsideDecl;
ContextPush(PEnt);
FHavePERefs := True;
end;
function TXMLReader.PrefetchEntity(AEntity: TDOMEntityEx): Boolean;
begin
Result := ContextPush(AEntity);
if Result then
try
FValue.Length := 0;
FSource.SkipUntil(FValue, [#0]);
SetString(AEntity.FReplacementText, FValue.Buffer, FValue.Length);
AEntity.FCharCount := FValue.Length;
AEntity.FStartLocation.Line := 1;
AEntity.FStartLocation.LinePos := 1;
AEntity.FURI := FSource.SystemID; // replace base URI with absolute one
finally
ContextPop;
AEntity.FPrefetched := True;
FValue.Length := 0;
end;
end;
procedure Normalize(var Buf: TDOMCharBuf; Modified: PBoolean);
var
Dst, Src: Integer;
begin
Dst := 0;
Src := 0;
// skip leading space if any
while (Src < Buf.Length) and (Buf.Buffer[Src] = ' ') do
Inc(Src);
while Src < Buf.Length do
begin
if Buf.Buffer[Src] = ' ' then
begin
// Dst cannot be 0 here, because leading space is already skipped
if Buf.Buffer[Dst-1] <> ' ' then
begin
Buf.Buffer[Dst] := ' ';
Inc(Dst);
end;
end
else
begin
Buf.Buffer[Dst] := Buf.Buffer[Src];
Inc(Dst);
end;
Inc(Src);
end;
// trailing space (only one possible due to compression)
if (Dst > 0) and (Buf.Buffer[Dst-1] = ' ') then
Dec(Dst);
if Assigned(Modified) then
Modified^ := Dst <> Buf.Length;
Buf.Length := Dst;
end;
const
LiteralDelims: array[TLiteralType] of TSetOfChar = (
[#0, '''', '"'], // ltPlain
[#0, '<', '&', '''', '"', #9, #10, #13], // ltAttr
[#0, '<', '&', '''', '"', #9, #10, #13], // ltTokAttr
[#0, '''', '"', #13, #10], // ltPubid
[#0, '%', '&', '''', '"'] // ltEntity
);
function TXMLReader.ParseLiteral(var ToFill: TDOMCharBuf; aType: TLiteralType;
Required: Boolean; Normalized: PBoolean): Boolean;
var
start: TObject;
wc, Delim: DOMChar;
ent: TDOMEntityEx;
begin
SkipQuote(Delim, Required);
Result := (Delim <> #0);
if not Result then
Exit;
ToFill.Length := 0;
start := FSource.FEntity;
repeat
wc := FSource.SkipUntil(ToFill, LiteralDelims[aType]);
if wc = '%' then { ltEntity only }
begin
FSource.NextChar;
CheckName;
ExpectChar(';');
if FSource.DTDSubsetType = dsInternal then
FatalError('PE reference not allowed here in internal subset', FName.Length+2);
StartPE;
end
else if wc = '&' then { ltAttr, ltTokAttr, ltEntity }
begin
if ParseRef(ToFill) then // charRefs always expanded
Continue;
if aType = ltEntity then // bypass
begin
BufAppend(ToFill, '&');
BufAppendChunk(ToFill, FName.Buffer, FName.Buffer + FName.Length);
BufAppend(ToFill, ';');
end
else // include
begin
if ResolvePredefined then
Continue;
ent := EntityCheck(True);
if ent = nil then
Continue;
ContextPush(ent);
end;
end
else if wc = '<' then
FatalError('Character ''<'' is not allowed in attribute value')
else if wc <> #0 then
begin
FSource.NextChar;
if (wc = #10) or (wc = #13) or (wc = #9) then
wc := #32
// terminating delimiter must be in the same context as the starting one
else if (wc = Delim) and (start = FSource.FEntity) then
Break;
BufAppend(ToFill, wc);
end
else if (FSource.FEntity = start) or not ContextPop then // #0
FatalError('Literal has no closing quote', -1);
until False;
if aType in [ltTokAttr, ltPubid] then
Normalize(ToFill, Normalized);
end;
function TXMLReader.SkipUntilSeq(const Delim: TSetOfChar; c1: DOMChar;
c2: DOMChar; AllowSpecialChars: boolean): Boolean;
var
wc: DOMChar;
begin
Result := False;
FValue.Length := 0;
StoreLocation(FTokenStart);
repeat
wc := FSource.SkipUntil(FValue, Delim, nil, AllowSpecialChars);
if wc <> #0 then
begin
FSource.NextChar;
if (FValue.Length > ord(c2 <> #0)) then
begin
if (FValue.Buffer[FValue.Length-1] = c1) and
((c2 = #0) or ((c2 <> #0) and (FValue.Buffer[FValue.Length-2] = c2))) then
begin
Dec(FValue.Length, ord(c2 <> #0) + 1);
Result := True;
Exit;
end;
end;
BufAppend(FValue, wc);
end;
until wc = #0;
end;
procedure TXMLReader.ParseComment; // [15]
var
AllowSpecialChars: Boolean;
begin
ExpectString('--');
AllowSpecialChars := xrfAllowSpecialCharsInComments in FFlags;
if SkipUntilSeq([#0, '-'], '-', #0, AllowSpecialChars) then
begin
ExpectChar('>');
DoComment(FValue.Buffer, FValue.Length);
end
else
FatalError('Unterminated comment', -1);
end;
procedure TXMLReader.ParsePI; // [16]
var
Name, Value: DOMString;
PINode: TDOMProcessingInstruction;
begin
FSource.NextChar; // skip '?'
Name := ExpectName;
CheckNCName;
with FName do
if (Length = 3) and
((Buffer[0] = 'X') or (Buffer[0] = 'x')) and
((Buffer[1] = 'M') or (Buffer[1] = 'm')) and
((Buffer[2] = 'L') or (Buffer[2] = 'l')) then
begin
if Name <> 'xml' then
FatalError('''xml'' is a reserved word; it must be lowercase', FName.Length)
else
FatalError('XML declaration is not allowed here', FName.Length);
end;
if FSource.FBuf^ <> '?' then
SkipS(True);
if SkipUntilSeq(GT_Delim, '?') then
begin
SetString(Value, FValue.Buffer, FValue.Length);
// SAX: ContentHandler.ProcessingInstruction(Name, Value);
if FCurrContentType = ctEmpty then
ValidationError('Processing instructions are not allowed within EMPTY elements', []);
PINode := Doc.CreateProcessingInstruction(Name, Value);
if Assigned(FCursor) then
FCursor.AppendChild(PINode)
else // to comply with certain tests, insert PI from DTD before DTD
Doc.InsertBefore(PINode, FDocType);
end
else
FatalError('Unterminated processing instruction', -1);
end;
const
verStr: array[Boolean] of DOMString = ('1.0', '1.1');
procedure TXMLReader.ParseXmlOrTextDecl(TextDecl: Boolean);
var
TmpStr: DOMString;
IsXML11: Boolean;
Delim: DOMChar;
buf: array[0..31] of DOMChar;
I: Integer;
begin
SkipS(True);
// [24] VersionInfo: optional in TextDecl, required in XmlDecl
if (not TextDecl) or (FSource.FBuf^ = 'v') then
begin
ExpectString('version');
ExpectEq;
SkipQuote(Delim);
I := 0;
while (I < 3) and (FSource.FBuf^ <> Delim) do
begin
buf[I] := FSource.FBuf^;
Inc(I);
FSource.NextChar;
end;
if (I <> 3) or (buf[0] <> '1') or (buf[1] <> '.') or
((buf[2] <> '0') and (buf[2] <> '1')) then
FatalError('Illegal version number', -1);
ExpectChar(Delim);
IsXML11 := buf[2] = '1';
if not TextDecl then
begin
if doc.InheritsFrom(TXMLDocument) then
TXMLDocument(doc).XMLVersion := verStr[IsXML11]; // buf[0..2] works with FPC only
end
else // parsing external entity
if IsXML11 and not FXML11 then
FatalError('XML 1.0 document cannot invoke XML 1.1 entities', -1);
if TextDecl or (FSource.FBuf^ <> '?') then
SkipS(True);
end;
// [80] EncodingDecl: required in TextDecl, optional in XmlDecl
if TextDecl or (FSource.FBuf^ = 'e') then
begin
ExpectString('encoding');
ExpectEq;
SkipQuote(Delim);
I := 0;
while (I < 30) and (FSource.FBuf^ <> Delim) and (FSource.FBuf^ < #127) and
((Char(ord(FSource.FBuf^)) in ['A'..'Z', 'a'..'z']) or
((I > 0) and (Char(ord(FSource.FBuf^)) in ['0'..'9', '.', '-', '_']))) do
begin
buf[I] := FSource.FBuf^;
Inc(I);
FSource.NextChar;
end;
if not CheckForChar(Delim) then
FatalError('Illegal encoding name', i);
SetString(TmpStr, buf, i);
if not FSource.SetEncoding(TmpStr) then // <-- Wide2Ansi conversion here
FatalError('Encoding ''%s'' is not supported', [TmpStr], i+1);
// getting here means that specified encoding is supported
// TODO: maybe assign the 'preferred' encoding name?
if not TextDecl and doc.InheritsFrom(TXMLDocument) then
TXMLDocument(doc).Encoding := TmpStr;
if FSource.FBuf^ <> '?' then
SkipS(not TextDecl);
end;
// [32] SDDecl: forbidden in TextDecl, optional in XmlDecl
if (not TextDecl) and (FSource.FBuf^ = 's') then
begin
ExpectString('standalone');
ExpectEq;
SkipQuote(Delim);
if FSource.Matches('yes') then
FStandalone := True
else if not FSource.Matches('no') then
FatalError('Only "yes" or "no" are permitted as values of "standalone"', -1);
ExpectChar(Delim);
SkipS;
end;
ExpectString('?>');
{ Switch to 1.1 rules only after declaration is parsed completely. This is to
ensure that NEL and LSEP within declaration are rejected (rmt-056, rmt-057) }
if (not TextDecl) and IsXML11 then
XML11_BuildTables;
end;
procedure TXMLReader.DTDReloadHook;
var
p: DOMPChar;
begin
{ FSource converts CR, NEL and LSEP linebreaks to LF, and CR-NEL sequences to CR-LF.
We must further remove the CR chars and have only LF's left. }
p := FDTDStartPos;
while p < FSource.FBuf do
begin
while (p < FSource.FBuf) and (p^ <> #13) do
Inc(p);
BufAppendChunk(FIntSubset, FDTDStartPos, p);
if p^ = #13 then
Inc(p);
FDTDStartPos := p;
end;
FDTDStartPos := TXMLDecodingSource(FSource).FBufStart;
end;
procedure TXMLReader.ParseDoctypeDecl; // [28]
var
Src: TXMLCharSource;
begin
if FState >= rsDTD then
FatalError('Markup declaration is not allowed here');
if FDisallowDoctype then
FatalError('Document type is prohibited by parser settings');
ExpectString('DOCTYPE');
SkipS(True);
FDocType := TDOMDocumentTypeEx(TDOMDocumentType.Create(doc));
FDTDProcessed := True; // assume success
FState := rsDTD;
try
FDocType.FName := ExpectName;
if SkipS(false) then begin
ParseExternalID(FDocType.FSystemID, FDocType.FPublicID, False);
SkipS;
end;
finally
// DONE: append node after its name has been set; always append to avoid leak
if FCanonical then
FOwnsDoctype := True
else
Doc.AppendChild(FDocType);
FCursor := nil;
end;
if CheckForChar('[') then
begin
BufAllocate(FIntSubset, 256);
FSource.DTDSubsetType := dsInternal;
try
FDTDStartPos := FSource.FBuf;
ParseMarkupDecl;
DTDReloadHook; // fetch last chunk
SetString(FDocType.FInternalSubset, FIntSubset.Buffer, FIntSubset.Length);
finally
FreeMem(FIntSubset.Buffer);
FSource.DTDSubsetType := dsNone;
end;
ExpectChar(']');
SkipS;
end;
ExpectChar('>');
if (FDocType.SystemID <> '') then
begin
if ResolveEntity(FDocType.SystemID, FDocType.PublicID, FSource.SystemID, Src) then
begin
Initialize(Src);
try
Src.DTDSubsetType := dsExternal;
ParseMarkupDecl;
finally
ContextPop(True);
end;
end
else
begin
ValidationError('Unable to resolve external DTD subset', []);
FDTDProcessed := FStandalone;
end;
end;
FCursor := Doc;
ValidateDTD;
FDocType.SetReadOnly(True);
end;
procedure TXMLReader.ExpectEq; // [25]
begin
if FSource.FBuf^ <> '=' then
SkipS;
if FSource.FBuf^ <> '=' then
FatalError('Expected "="');
FSource.NextChar;
SkipS;
end;
{ DTD stuff }
procedure TXMLReader.BadPENesting(S: TErrorSeverity);
begin
if (S = esFatal) or FValidate then
DoError(S, 'Parameter entities must be properly nested');
end;
procedure TXMLReader.StandaloneError(LineOffs: Integer);
begin
ValidationError('Standalone constriant violation', [], LineOffs);
end;
procedure TXMLReader.ParseQuantity(CP: TContentParticle);
begin
case FSource.FBuf^ of
'?': CP.CPQuant := cqZeroOrOnce;
'*': CP.CPQuant := cqZeroOrMore;
'+': CP.CPQuant := cqOnceOrMore;
else
Exit;
end;
FSource.NextChar;
end;
function TXMLReader.FindOrCreateElDef: TDOMElementDef;
var
p: PHashItem;
begin
CheckName;
p := doc.Names.FindOrAdd(FName.Buffer, FName.Length);
Result := TDOMElementDef(p^.Data);
if Result = nil then
begin
Result := TDOMElementDef.Create(doc);
Result.FNSI.QName := p;
p^.Data := Result;
end;
end;
procedure TXMLReader.ExpectChoiceOrSeq(CP: TContentParticle); // [49], [50]
var
Delim: DOMChar;
CurrentEntity: TObject;
CurrentCP: TContentParticle;
begin
Delim := #0;
repeat
CurrentCP := CP.Add;
SkipWhitespace;
if CheckForChar('(') then
begin
CurrentEntity := FSource.FEntity;
ExpectChoiceOrSeq(CurrentCP);
if CurrentEntity <> FSource.FEntity then
BadPENesting;
FSource.NextChar;
end
else
CurrentCP.Def := FindOrCreateElDef;
ParseQuantity(CurrentCP);
SkipWhitespace;
if FSource.FBuf^ = ')' then
Break;
if Delim = #0 then
begin
if (FSource.FBuf^ = '|') or (FSource.FBuf^ = ',') then
Delim := FSource.FBuf^
else
FatalError('Expected pipe or comma delimiter');
end
else
if FSource.FBuf^ <> Delim then
FatalError(Delim);
FSource.NextChar; // skip delimiter
until False;
if Delim = '|' then
CP.CPType := ctChoice
else
CP.CPType := ctSeq; // '(foo)' is a sequence!
end;
procedure TXMLReader.ParseElementDecl; // [45]
var
ElDef: TDOMElementDef;
CurrentEntity: TObject;
I: Integer;
CP: TContentParticle;
Typ: TElementContentType;
ExtDecl: Boolean;
begin
CP := nil;
Typ := ctUndeclared; // satisfy compiler
ExpectWhitespace;
ElDef := FindOrCreateElDef;
if ElDef.ContentType <> ctUndeclared then
ValidationError('Duplicate declaration of element ''%s''', [ElDef.TagName], FName.Length);
ExtDecl := FSource.DTDSubsetType <> dsInternal;
ExpectWhitespace;
if FSource.Matches('EMPTY') then
Typ := ctEmpty
else if FSource.Matches('ANY') then
Typ := ctAny
else if CheckForChar('(') then
begin
CP := TContentParticle.Create;
try
CurrentEntity := FSource.FEntity;
SkipWhitespace;
if FSource.Matches('#PCDATA') then // Mixed section [51]
begin
SkipWhitespace;
Typ := ctMixed;
while FSource.FBuf^ <> ')' do
begin
ExpectChar('|');
SkipWhitespace;
with CP.Add do
begin
Def := FindOrCreateElDef;
for I := CP.ChildCount-2 downto 0 do
if Def = CP.Children[I].Def then
ValidationError('Duplicate token in mixed section', [], FName.Length);
end;
SkipWhitespace;
end;
if CurrentEntity <> FSource.FEntity then
BadPENesting;
FSource.NextChar;
if (not CheckForChar('*')) and (CP.ChildCount > 0) then
FatalError(DOMChar('*'));
end
else // Children section [47]
begin
Typ := ctChildren;
ExpectChoiceOrSeq(CP);
if CurrentEntity <> FSource.FEntity then
BadPENesting;
FSource.NextChar;
ParseQuantity(CP);
end;
except
CP.Free;
raise;
end;
end
else
FatalError('Invalid content specification');
// SAX: DeclHandler.ElementDecl(name, model);
if FDTDProcessed and (ElDef.ContentType = ctUndeclared) then
begin
ElDef.FExternallyDeclared := ExtDecl;
ElDef.ContentType := Typ;
ElDef.RootCP := CP;
end
else
CP.Free;
end;
procedure TXMLReader.ParseNotationDecl; // [82]
var
Name, SysID, PubID: DOMString;
begin
ExpectWhitespace;
Name := ExpectName;
CheckNCName;
ExpectWhitespace;
if not ParseExternalID(SysID, PubID, True) then
FatalError('Expected external or public ID');
if FDTDProcessed then
DoNotationDecl(Name, PubID, SysID);
end;
const
AttrDataTypeNames: array[TAttrDataType] of DOMString = (
'CDATA',
'ID',
'IDREF',
'IDREFS',
'ENTITY',
'ENTITIES',
'NMTOKEN',
'NMTOKENS',
'NOTATION'
);
procedure TXMLReader.ParseAttlistDecl; // [52]
var
ElDef: TDOMElementDef;
AttDef: TDOMAttrDef;
dt: TAttrDataType;
Found, DiscardIt: Boolean;
Offsets: array [Boolean] of Integer;
begin
ExpectWhitespace;
ElDef := FindOrCreateElDef;
SkipWhitespace;
while FSource.FBuf^ <> '>' do
begin
CheckName;
ExpectWhitespace;
AttDef := doc.CreateAttributeDef(FName.Buffer, FName.Length);
try
AttDef.ExternallyDeclared := FSource.DTDSubsetType <> dsInternal;
// In case of duplicate declaration of the same attribute, we must discard it,
// not modifying ElDef, and suppressing certain validation errors.
DiscardIt := (not FDTDProcessed) or Assigned(ElDef.GetAttributeNode(AttDef.Name));
if not DiscardIt then
ElDef.SetAttributeNode(AttDef);
if CheckForChar('(') then // [59]
begin
AttDef.DataType := dtNmToken;
repeat
SkipWhitespace;
CheckName([cnToken]);
if not AttDef.AddEnumToken(FName.Buffer, FName.Length) then
ValidationError('Duplicate token in enumerated attribute declaration', [], FName.Length);
SkipWhitespace;
until not CheckForChar('|');
ExpectChar(')');
ExpectWhitespace;
end
else
begin
StoreLocation(FTokenStart);
// search topside-up so that e.g. NMTOKENS is matched before NMTOKEN
for dt := dtNotation downto dtCData do
begin
Found := FSource.Matches(AttrDataTypeNames[dt]);
if Found then
Break;
end;
if Found and SkipWhitespace then
begin
AttDef.DataType := dt;
if (dt = dtId) and not DiscardIt then
begin
if Assigned(ElDef.IDAttr) then
ValidationError('Only one attribute of type ID is allowed per element',[])
else
ElDef.IDAttr := AttDef;
end
else if dt = dtNotation then // no test cases for these ?!
begin
if not DiscardIt then
begin
if Assigned(ElDef.NotationAttr) then
ValidationError('Only one attribute of type NOTATION is allowed per element',[])
else
ElDef.NotationAttr := AttDef;
if ElDef.ContentType = ctEmpty then
ValidationError('NOTATION attributes are not allowed on EMPTY elements',[]);
end;
ExpectChar('(');
repeat
SkipWhitespace;
StoreLocation(FTokenStart);
CheckName;
CheckNCName;
if not AttDef.AddEnumToken(FName.Buffer, FName.Length) then
ValidationError('Duplicate token in NOTATION attribute declaration',[], FName.Length);
if not DiscardIt then
AddForwardRef(FNotationRefs, FName.Buffer, FName.Length);
SkipWhitespace;
until not CheckForChar('|');
ExpectChar(')');
ExpectWhitespace;
end;
end
else
begin
// don't report 'expected whitespace' if token does not match completely
Offsets[False] := 0;
Offsets[True] := Length(AttrDataTypeNames[dt]);
if Found and (FSource.FBuf^ < 'A') then
ExpectWhitespace
else
FatalError('Illegal attribute type for ''%s''', [AttDef.Name], Offsets[Found]);
end;
end;
StoreLocation(FTokenStart);
if FSource.Matches('#REQUIRED') then
AttDef.Default := adRequired
else if FSource.Matches('#IMPLIED') then
AttDef.Default := adImplied
else if FSource.Matches('#FIXED') then
begin
AttDef.Default := adFixed;
ExpectWhitespace;
end
else
AttDef.Default := adDefault;
if AttDef.Default in [adDefault, adFixed] then
begin
if AttDef.DataType = dtId then
ValidationError('An attribute of type ID cannot have a default value',[]);
FCursor := AttDef;
// See comments to valid-sa-094: PE expansion should be disabled in AttDef.
// ExpectAttValue() does not recognize PEs anyway, so setting FRecognizePEs isn't needed
// Saving/restoring FCursor is also redundant because it is always nil here.
ExpectAttValue;
FCursor := nil;
if not ValidateAttrSyntax(AttDef, AttDef.NodeValue) then
ValidationError('Default value for attribute ''%s'' has wrong syntax', [AttDef.Name]);
end;
// SAX: DeclHandler.AttributeDecl(...)
if DiscardIt then
AttDef.Free;
except
AttDef.Free;
raise;
end;
SkipWhitespace;
end;
end;
procedure TXMLReader.ParseEntityDecl; // [70]
var
IsPE: Boolean;
Entity: TDOMEntityEx;
Map: TDOMNamedNodeMap;
begin
if not SkipWhitespace(True) then
FatalError('Expected whitespace');
IsPE := False;
Map := FDocType.Entities;
if CheckForChar('%') then // [72]
begin
ExpectWhitespace;
IsPE := True;
if FPEMap = nil then
FPEMap := TDOMNamedNodeMap.Create(FDocType, ENTITY_NODE);
Map := FPEMap;
end;
Entity := TDOMEntityEx.Create(Doc);
Entity.SetReadOnly(True);
try
Entity.FExternallyDeclared := FSource.DTDSubsetType <> dsInternal;
Entity.FIsPE := IsPE;
Entity.FName := ExpectName;
CheckNCName;
ExpectWhitespace;
// remember where the entity is declared
Entity.FURI := FSource.SystemID;
if FEntityValue.Buffer = nil then
BufAllocate(FEntityValue, 256);
if ParseLiteral(FEntityValue, ltEntity, False) then
begin
SetString(Entity.FReplacementText, FEntityValue.Buffer, FEntityValue.Length);
Entity.FCharCount := FEntityValue.Length;
Entity.FStartLocation := FTokenStart;
end
else
begin
if not ParseExternalID(Entity.FSystemID, Entity.FPublicID, False) then
FatalError('Expected entity value or external ID');
if not IsPE then // [76]
begin
if FSource.FBuf^ <> '>' then
ExpectWhitespace;
if FSource.Matches('NDATA') then
begin
ExpectWhitespace;
StoreLocation(FTokenStart);
Entity.FNotationName := ExpectName;
AddForwardRef(FNotationRefs, FName.Buffer, FName.Length);
// SAX: DTDHandler.UnparsedEntityDecl(...);
end;
end;
end;
except
Entity.Free;
raise;
end;
// Repeated declarations of same entity are legal but must be ignored
if FDTDProcessed and (Map.GetNamedItem(Entity.FName) = nil) then
Map.SetNamedItem(Entity)
else
Entity.Free;
end;
procedure TXMLReader.ParseMarkupDecl; // [29]
var
IncludeLevel: Integer;
IgnoreLevel: Integer;
CurrentEntity: TObject;
IncludeLoc: TLocation;
IgnoreLoc: TLocation;
wc: DOMChar;
CondType: (ctUnknown, ctInclude, ctIgnore);
begin
IncludeLevel := 0;
IgnoreLevel := 0;
repeat
FRecognizePE := True; // PERef between declarations should always be recognized
SkipWhitespace;
FRecognizePE := False;
if (FSource.FBuf^ = ']') and (IncludeLevel > 0) then
begin
ExpectString(']]>');
Dec(IncludeLevel);
Continue;
end;
if not CheckForChar('<') then
Break;
CurrentEntity := FSource.FEntity;
if FSource.FBuf^ = '?' then
ParsePI
else
begin
ExpectChar('!');
if FSource.FBuf^ = '-' then
ParseComment
else if CheckForChar('[') then
begin
if FSource.DTDSubsetType = dsInternal then
FatalError('Conditional sections are not allowed in internal subset', 1);
FRecognizePE := True;
SkipWhitespace;
CondType := ctUnknown; // satisfy compiler
if FSource.Matches('INCLUDE') then
CondType := ctInclude
else if FSource.Matches('IGNORE') then
CondType := ctIgnore
else
FatalError('Expected "INCLUDE" or "IGNORE"');
SkipWhitespace;
if CurrentEntity <> FSource.FEntity then
BadPENesting;
ExpectChar('[');
if CondType = ctInclude then
begin
if IncludeLevel = 0 then
StoreLocation(IncludeLoc);
Inc(IncludeLevel);
end
else if CondType = ctIgnore then
begin
StoreLocation(IgnoreLoc);
IgnoreLevel := 1;
repeat
FValue.Length := 0;
wc := FSource.SkipUntil(FValue, [#0, '<', ']']);
if FSource.Matches('<![') then
Inc(IgnoreLevel)
else if FSource.Matches(']]>') then
Dec(IgnoreLevel)
else if wc <> #0 then
FSource.NextChar
else // PE's aren't recognized in ignore section, cannot ContextPop()
DoErrorPos(esFatal, 'IGNORE section is not closed', IgnoreLoc);
until IgnoreLevel=0;
end;
end
else
begin
FRecognizePE := FSource.DTDSubsetType <> dsInternal;
FInsideDecl := True;
if FSource.Matches('ELEMENT') then
ParseElementDecl
else if FSource.Matches('ENTITY') then
ParseEntityDecl
else if FSource.Matches('ATTLIST') then
ParseAttlistDecl
else if FSource.Matches('NOTATION') then
ParseNotationDecl
else
FatalError('Illegal markup declaration');
SkipWhitespace;
FRecognizePE := False;
if CurrentEntity <> FSource.FEntity then
BadPENesting;
ExpectChar('>');
FInsideDecl := False;
end;
end;
until False;
FRecognizePE := False;
if IncludeLevel > 0 then
DoErrorPos(esFatal, 'INCLUDE section is not closed', IncludeLoc);
if (FSource.DTDSubsetType = dsInternal) and (FSource.FBuf^ = ']') then
Exit;
if FSource.FBuf^ <> #0 then
FatalError('Illegal character in DTD');
end;
procedure TXMLReader.ProcessDTD(ASource: TXMLCharSource);
begin
doc := TXMLDocument.Create;
FDocType := TDOMDocumentTypeEx.Create(doc);
// TODO: DTD labeled version 1.1 will be rejected - must set FXML11 flag
// DONE: It's ok to have FCursor=nil now
doc.AppendChild(FDocType);
Initialize(ASource);
ParseMarkupDecl;
end;
procedure TXMLReader.AppendReference(AEntity: TDOMEntityEx);
var
s: DOMString;
begin
if AEntity = nil then
SetString(s, FName.Buffer, FName.Length)
else
s := AEntity.nodeName;
FCursor.AppendChild(doc.CreateEntityReference(s));
end;
// The code below does the bulk of the parsing, and must be as fast as possible.
// To minimize CPU cache effects, methods from different classes are kept together
function TXMLDecodingSource.SkipUntil(var ToFill: TDOMCharBuf; const Delim: TSetOfChar;
wsflag: PBoolean; AllowSpecialChars: boolean): DOMChar;
var
old: DOMPChar;
nonws: Boolean;
wc: DOMChar;
begin
nonws := False;
repeat
old := FBuf;
repeat
{$IFDEF UseWideString}
// skip common white spaces
while FBuf^ in [' ',#9] do inc(FBuf);
wc := FBuf^;
//writeln('TXMLDecodingSource.SkipUntil ',ord(wc));
if ((wc = #10) or (wc = #13)
) and (not AllowSpecialChars)
then begin
BufAppendChunk(ToFill, old, FBuf);
NewLine;
old := FBuf;
inc(FBuf);
// skip common white spaces at line start
while FBuf^ in [' ',#9] do inc(FBuf);
wc := FBuf^;
end
else if (not AllowSpecialChars)
and ( ((wc < #32) and (not ((wc = #0) and (FBuf >= FBufEnd))) and (wc <> #9))
or (FXML11Rules and (wc >= #$7F) and (wc <= #$9F)) )
then
FReader.FatalError('Invalid character')
else if (wc=#0) and (FBuf < FBufEnd) then
FReader.FatalError('Invalid #0 character');
if (Char(ord(wc)) in Delim) then
Break;
// the checks above filter away everything below #32 that isn't a whitespace
if wc > #32 then
nonws := True;
Inc(FBuf);
{$ELSE}
wc:=FBuf^;
if (wc>#0) and (wc < #255) and (Char(ord(wc)) in Delim) then
Break;
if wc<' ' then begin
case wc of
#0:
if (FBuf < FBufEnd) then
FReader.FatalError('Invalid #0 character')
else
break;
#10:
if AllowSpecialChars then begin
inc(FBuf);
end else begin
if FBuf[1] in [#0,#13] then begin
BufAppendChunk(ToFill, old, FBuf);
old := FBuf;
end;
NewLine;
inc(FBuf);
// skip common white spaces at line start
while FBuf^ in [' ',#9] do inc(FBuf);
end;
#13:
if AllowSpecialChars then begin
inc(FBuf);
end else begin
BufAppendChunk(ToFill, old, FBuf);
NewLine;
old := FBuf;
inc(FBuf);
// skip common white spaces at line start
while FBuf^ in [' ',#9] do inc(FBuf);
end;
' ',#9:
inc(FBuf);
#1..#8,#11,#12,#14..#31:
if AllowSpecialChars then begin
inc(FBuf);
end else begin
FReader.FatalError('Invalid character');
end;
else
nonws:=true;
inc(FBuf);
end;
end else begin
if wc>' ' then
nonws:=true;
inc(FBuf);
end;
{$ENDIF}
until False;
Result := wc;
BufAppendChunk(ToFill, old, FBuf);
until (Result <> #0) or (not Reload);
if Assigned(wsflag) then
wsflag^ := wsflag^ or nonws;
end;
const
TextDelims: array[Boolean] of TSetOfChar = (
[#0, '<', '&', '>'],
[#0, '>']
);
procedure TXMLReader.ParseContent;
var
nonWs: Boolean;
wc: DOMChar;
ent: TDOMEntityEx;
InCDATA: Boolean;
begin
InCDATA := False;
StoreLocation(FTokenStart);
nonWs := False;
FValue.Length := 0;
repeat
wc := FSource.SkipUntil(FValue, TextDelims[InCDATA], @nonWs);
if wc = '<' then
begin
Inc(FSource.FBuf);
if FSource.FBufEnd < FSource.FBuf + 2 then
FSource.Reload;
if FSource.FBuf^ = '/' then
begin
DoText(FValue.Buffer, FValue.Length, not nonWs);
if FNesting <= FSource.FStartNesting then
FatalError('End-tag is not allowed here');
Inc(FSource.FBuf);
ParseEndTag;
end
else if CheckName([cnOptional]) then
begin
DoText(FValue.Buffer, FValue.Length, not nonWs);
ParseElement;
end
else if FSource.FBuf^ = '!' then
begin
Inc(FSource.FBuf);
if FSource.FBuf^ = '[' then
begin
ExpectString('[CDATA[');
if FState <> rsRoot then
FatalError('Illegal at document level');
StoreLocation(FTokenStart);
InCDATA := True;
if not FCDSectionsAsText then
DoText(FValue.Buffer, FValue.Length, not nonWs)
else
Continue;
end
else if FSource.FBuf^ = '-' then
begin
DoText(FValue.Buffer, FValue.Length, not nonWs);
ParseComment;
end
else
begin
DoText(FValue.Buffer, FValue.Length, not nonWs);
ParseDoctypeDecl;
end;
end
else if FSource.FBuf^ = '?' then
begin
DoText(FValue.Buffer, FValue.Length, not nonWs);
ParsePI;
end
else begin
//writeln('TXMLReader.ParseContent FAIL ',PtrUInt(FSource.FBuf),' Buf=',ord(FSource.FBuf^),' ',FSource.FBuf);
RaiseNameNotFound;
end;
end
else if wc = #0 then
begin
if InCDATA then
FatalError('Unterminated CDATA section', -1);
if FNesting > FSource.FStartNesting then
FatalError('End-tag is missing for ''%s''', [FValidator[FNesting].FElement.NSI.QName^.Key]);
if ContextPop then Continue;
Break;
end
else if wc = '>' then
begin
BufAppend(FValue, wc);
FSource.NextChar;
if (FValue.Length <= 2) or (FValue.Buffer[FValue.Length-2] <> ']') or
(FValue.Buffer[FValue.Length-3] <> ']') then Continue;
if InCData then // got a ']]>' separator
begin
Dec(FValue.Length, 3);
InCDATA := False;
if FCDSectionsAsText then
Continue;
DoCDSect(FValue.Buffer, FValue.Length);
end
else
FatalError('Literal '']]>'' is not allowed in text', 3);
end
else if wc = '&' then
begin
if FState <> rsRoot then
FatalError('Illegal at document level');
if FCurrContentType = ctEmpty then
ValidationError('References are illegal in EMPTY elements', []);
if ParseRef(FValue) or ResolvePredefined then
begin
nonWs := True; // CharRef to whitespace is not considered whitespace
Continue;
end
else
begin
ent := EntityCheck;
if (ent = nil) or (not FExpandEntities) then
begin
DoText(FValue.Buffer, FValue.Length, not nonWs);
AppendReference(ent);
end
else
begin
ContextPush(ent);
Continue;
end;
end;
end;
StoreLocation(FTokenStart);
FValue.Length := 0;
nonWs := False;
until False;
DoText(FValue.Buffer, FValue.Length, not nonWs);
end;
procedure TXMLCharSource.NextChar;
begin
Inc(FBuf);
if FBuf >= FBufEnd then
Reload;
end;
procedure TXMLReader.ExpectChar(wc: DOMChar);
begin
if FSource.FBuf^ = wc then
FSource.NextChar
else
FatalError(wc);
end;
// Element name already in FNameBuffer
procedure TXMLReader.ParseElement; // [39] [40] [44]
var
NewElem: TDOMElement;
ElDef: TDOMElementDef;
IsEmpty: Boolean;
ElName: PHashItem;
begin
if FState > rsRoot then
FatalError('Only one top-level element allowed', FName.Length)
else if FState < rsRoot then
begin
if FValidate then
ValidateRoot;
FState := rsRoot;
end;
NewElem := doc.CreateElementBuf(FName.Buffer, FName.Length);
FCursor.AppendChild(NewElem);
// we're about to process a new set of attributes
Inc(FAttrTag);
// Remember the hash entry, we'll need it often
ElName := NewElem.NSI.QName;
// Find declaration for this element
ElDef := TDOMElementDef(ElName^.Data);
if (ElDef = nil) or (ElDef.ContentType = ctUndeclared) then
ValidationError('Using undeclared element ''%s''',[ElName^.Key], FName.Length);
// Check if new element is allowed in current context
if FValidate and not FValidator[FNesting].IsElementAllowed(ElDef) then
ValidationError('Element ''%s'' is not allowed in this context',[ElName^.Key], FName.Length);
IsEmpty := False;
while (FSource.FBuf^ <> '>') and (FSource.FBuf^ <> '/') do
begin
SkipS(True);
if (FSource.FBuf^ = '>') or (FSource.FBuf^ = '/') then
Break;
ParseAttribute(NewElem, ElDef);
end;
if FSource.FBuf^ = '/' then
begin
IsEmpty := True;
FSource.NextChar;
end;
ExpectChar('>');
if Assigned(ElDef) and Assigned(ElDef.FAttributes) then
ProcessDefaultAttributes(NewElem, ElDef.FAttributes);
PushVC(NewElem, ElDef); // this increases FNesting
if FNamespaces then
ProcessNamespaceAtts(NewElem);
if not IsEmpty then
begin
FCursor := NewElem;
if not FPreserveWhitespace then // critical for testsuite compliance
SkipS;
end
else
DoEndElement(0);
end;
procedure TXMLReader.DoEndElement(ErrOffset: Integer);
var
NewElem: TDOMElement;
begin
NewElem := FValidator[FNesting].FElement;
TDOMNode(FCursor) := NewElem.ParentNode;
if FCursor = doc then
FState := rsEpilog;
if FValidate and FValidator[FNesting].Incomplete then
ValidationError('Element ''%s'' is missing required sub-elements', [NewElem.NSI.QName^.Key], ErrOffset);
if FNamespaces then
FNSHelper.EndElement;
PopVC;
end;
procedure TXMLReader.ParseEndTag; // [42]
var
ErrOffset: Integer;
ElName: PHashItem;
procedure UnmatchingEndTag;
begin
FatalError('Unmatching element end tag (expected "</%s>")', [ElName^.Key], FName.Length);
end;
begin
ElName := FValidator[FNesting].FElement.NSI.QName;
CheckName;
if not BufEquals(FName, ElName^.Key) then
UnmatchingEndTag;
if FSource.FBuf^ = '>' then // this handles majority of cases
begin
ErrOffset := FName.Length+1;
FSource.NextChar;
end
else // but if closing '>' is preceded by whitespace,
begin // skipping it is likely to lose position info.
StoreLocation(FTokenStart);
Dec(FTokenStart.LinePos, FName.Length);
ErrOffset := -1;
SkipS;
ExpectChar('>');
end;
DoEndElement(ErrOffset);
end;
procedure TXMLReader.ParseAttribute(Elem: TDOMElement; ElDef: TDOMElementDef);
var
attr: TDOMAttr;
AttDef: TDOMAttrDef;
OldAttr: TDOMNode;
procedure CheckValue;
var
AttValue, OldValue: DOMString;
begin
if FStandalone and AttDef.ExternallyDeclared then
begin
OldValue := Attr.Value;
Attr.DataType := AttDef.DataType;
AttValue := Attr.Value;
if AttValue <> OldValue then
StandaloneError(-1);
end
else
begin
Attr.DataType := AttDef.DataType;
AttValue := Attr.Value;
end;
// TODO: what about normalization of AttDef.Value? (Currently it IS normalized)
if (AttDef.Default = adFixed) and (AttDef.Value <> AttValue) then
ValidationError('Value of attribute ''%s'' does not match its #FIXED default',[AttDef.Name], -1);
if not ValidateAttrSyntax(AttDef, AttValue) then
ValidationError('Attribute ''%s'' type mismatch', [AttDef.Name], -1);
ValidateAttrValue(Attr, AttValue);
end;
begin
CheckName;
attr := doc.CreateAttributeBuf(FName.Buffer, FName.Length);
if Assigned(ElDef) then
begin
AttDef := TDOMAttrDef(ElDef.GetAttributeNode(attr.NSI.QName^.Key));
if AttDef = nil then
ValidationError('Using undeclared attribute ''%s'' on element ''%s''',[attr.NSI.QName^.Key, Elem.NSI.QName^.Key], FName.Length)
else
AttDef.Tag := FAttrTag; // indicates that this one is specified
end
else
AttDef := nil;
// !!cannot use TDOMElement.SetAttributeNode because it will free old attribute
OldAttr := Elem.Attributes.SetNamedItem(Attr);
if Assigned(OldAttr) then
begin
OldAttr.Free;
FatalError('Duplicate attribute', FName.Length);
end;
ExpectEq;
FCursor := attr;
ExpectAttValue;
if Assigned(AttDef) and ((AttDef.DataType <> dtCdata) or (AttDef.Default = adFixed)) then
CheckValue;
end;
procedure TXMLReader.AddForwardRef(aList: TFPList; Buf: DOMPChar; Length: Integer);
var
w: PForwardRef;
begin
New(w);
SetString(w^.Value, Buf, Length);
w^.Loc := FTokenStart;
aList.Add(w);
end;
procedure TXMLReader.ClearRefs(aList: TFPList);
var
I: Integer;
begin
for I := 0 to aList.Count-1 do
Dispose(PForwardRef(aList.List^[I]));
aList.Clear;
end;
procedure TXMLReader.ValidateIdRefs;
var
I: Integer;
begin
for I := 0 to FIDRefs.Count-1 do
with PForwardRef(FIDRefs.List^[I])^ do
if Doc.GetElementById(Value) = nil then
DoErrorPos(esError, Format('The ID ''%s'' does not match any element', [Value]), Loc);
ClearRefs(FIDRefs);
end;
procedure TXMLReader.ProcessDefaultAttributes(Element: TDOMElement; Map: TDOMNamedNodeMap);
var
I: Integer;
AttDef: TDOMAttrDef;
Attr: TDOMAttr;
begin
for I := 0 to Map.Length-1 do
begin
AttDef := Map[I] as TDOMAttrDef;
if AttDef.Tag <> FAttrTag then // this one wasn't specified
begin
case AttDef.Default of
adDefault, adFixed: begin
if FStandalone and AttDef.ExternallyDeclared then
StandaloneError;
Attr := TDOMAttr(AttDef.CloneNode(True));
Element.SetAttributeNode(Attr);
ValidateAttrValue(Attr, Attr.Value);
end;
adRequired: ValidationError('Required attribute ''%s'' of element ''%s'' is missing',[AttDef.Name, Element.TagName], 0)
end;
end;
end;
end;
procedure TXMLReader.AddBinding(Attr: TDOMAttr; PrefixPtr: DOMPChar; PrefixLen: Integer);
var
nsUri: DOMString;
Prefix: PHashItem;
begin
nsUri := Attr.NodeValue;
Prefix := FNSHelper.GetPrefix(PrefixPtr, PrefixLen);
{ 'xml' is allowed to be bound to the correct namespace }
if ((nsUri = stduri_xml) <> (Prefix = FStdPrefix_xml)) or
(Prefix = FStdPrefix_xmlns) or
(nsUri = stduri_xmlns) then
begin
if (Prefix = FStdPrefix_xml) or (Prefix = FStdPrefix_xmlns) then
FatalError('Illegal usage of reserved prefix ''%s''', [Prefix^.Key])
else
FatalError('Illegal usage of reserved namespace URI ''%s''', [nsUri]);
end;
if (nsUri = '') and not (FXML11 or (Prefix^.Key = '')) then
FatalError('Illegal undefining of namespace'); { position - ? }
FNSHelper.BindPrefix(nsURI, Prefix);
end;
procedure TXMLReader.ProcessNamespaceAtts(Element: TDOMElement);
var
I, J: Integer;
Map: TDOMNamedNodeMap;
Prefix, AttrName: PHashItem;
Attr: TDOMAttr;
PrefixCount: Integer;
b: TBinding;
begin
FNSHelper.StartElement;
PrefixCount := 0;
if Element.HasAttributes then
begin
Map := Element.Attributes;
if Map.Length > LongWord(Length(FWorkAtts)) then
SetLength(FWorkAtts, Map.Length+10);
{ Pass 1, identify prefixed attrs and assign prefixes }
for I := 0 to Map.Length-1 do
begin
Attr := TDOMAttr(Map[I]);
AttrName := Attr.NSI.QName;
if Pos(DOMString('xmlns'), AttrName^.Key) = 1 then
begin
{ this is a namespace declaration }
if Length(AttrName^.Key) = 5 then
begin
// TODO: check all consequences of having zero PrefixLength
Attr.SetNSI(stduri_xmlns, 0);
AddBinding(Attr, nil, 0);
end
else if AttrName^.Key[6] = ':' then
begin
Attr.SetNSI(stduri_xmlns, 6);
AddBinding(Attr, @AttrName^.Key[7], Length(AttrName^.Key)-6);
end;
end
else
begin
J := Pos(DOMChar(':'), AttrName^.Key);
if J > 1 then
begin
FWorkAtts[PrefixCount].Attr := Attr;
FWorkAtts[PrefixCount].PrefixLen := J;
Inc(PrefixCount);
end;
end;
end;
end;
{ Pass 2, now all bindings are known, handle remaining prefixed attributes }
if PrefixCount > 0 then
begin
FNsAttHash.Init(PrefixCount);
for I := 0 to PrefixCount-1 do
begin
AttrName := FWorkAtts[I].Attr.NSI.QName;
if not FNSHelper.IsPrefixBound(DOMPChar(AttrName^.Key), FWorkAtts[I].PrefixLen-1, Prefix) then
FatalError('Unbound prefix "%s"', [Prefix^.Key]);
b := TBinding(Prefix^.Data);
{ detect duplicates }
J := FWorkAtts[I].PrefixLen+1;
if FNsAttHash.Locate(@b.uri, @AttrName^.Key[J], Length(AttrName^.Key) - J+1) then
FatalError('Duplicate prefixed attribute');
// convert Attr into namespaced one (by hack for the time being)
FWorkAtts[I].Attr.SetNSI(b.uri, J-1);
end;
end;
{ Finally, expand the element name }
J := Pos(DOMChar(':'), Element.NSI.QName^.Key);
if J > 1 then
begin
if not FNSHelper.IsPrefixBound(DOMPChar(Element.NSI.QName^.Key), J-1, Prefix) then
FatalError('Unbound prefix "%s"', [Prefix^.Key]);
b := TBinding(Prefix^.Data);
Element.SetNSI(b.uri, J);
end
else
begin
b := FNSHelper.DefaultNSBinding;
if Assigned(b) then
Element.SetNSI(b.uri, 0);
end;
end;
function TXMLReader.ParseExternalID(out SysID, PubID: DOMString; // [75]
SysIdOptional: Boolean): Boolean;
var
I: Integer;
wc: DOMChar;
begin
Result := False;
if FSource.Matches('SYSTEM') then
SysIdOptional := False
else if FSource.Matches('PUBLIC') then
begin
ExpectWhitespace;
ParseLiteral(FValue, ltPubid, True);
SetString(PubID, FValue.Buffer, FValue.Length);
for I := 1 to Length(PubID) do
begin
wc := PubID[I];
if (wc > #255) or not (Char(ord(wc)) in PubidChars) then
FatalError('Illegal Public ID literal', -1);
end;
end
else
Exit;
if SysIdOptional then
SkipWhitespace
else
ExpectWhitespace;
if ParseLiteral(FValue, ltPlain, not SysIdOptional) then
SetString(SysID, FValue.Buffer, FValue.Length);
Result := True;
end;
function TXMLReader.ValidateAttrSyntax(AttrDef: TDOMAttrDef; const aValue: DOMString): Boolean;
begin
case AttrDef.DataType of
dtId, dtIdRef, dtEntity: Result := IsXmlName(aValue, FXML11) and
((not FNamespaces) or (Pos(DOMChar(':'), aValue) = 0));
dtIdRefs, dtEntities: Result := IsXmlNames(aValue, FXML11) and
((not FNamespaces) or (Pos(DOMChar(':'), aValue) = 0));
dtNmToken: Result := IsXmlNmToken(aValue, FXML11) and AttrDef.HasEnumToken(aValue);
dtNmTokens: Result := IsXmlNmTokens(aValue, FXML11);
// IsXmlName() not necessary - enum is never empty and contains valid names
dtNotation: Result := AttrDef.HasEnumToken(aValue);
else
Result := True;
end;
end;
procedure TXMLReader.ValidateAttrValue(Attr: TDOMAttr; const aValue: DOMString);
var
L, StartPos, EndPos: Integer;
Entity: TDOMEntity;
begin
L := Length(aValue);
case Attr.DataType of
dtId: if not Doc.AddID(Attr) then
ValidationError('The ID ''%s'' is not unique', [aValue], -1);
dtIdRef, dtIdRefs: begin
StartPos := 1;
while StartPos <= L do
begin
EndPos := StartPos;
while (EndPos <= L) and (aValue[EndPos] <> #32) do
Inc(EndPos);
AddForwardRef(FIDRefs, @aValue[StartPos], EndPos-StartPos);
StartPos := EndPos + 1;
end;
end;
dtEntity, dtEntities: begin
StartPos := 1;
while StartPos <= L do
begin
EndPos := StartPos;
while (EndPos <= L) and (aValue[EndPos] <> #32) do
Inc(EndPos);
Entity := TDOMEntity(FDocType.Entities.GetNamedItem(Copy(aValue, StartPos, EndPos-StartPos)));
if (Entity = nil) or (Entity.NotationName = '') then
ValidationError('Attribute ''%s'' type mismatch', [Attr.Name], -1);
StartPos := EndPos + 1;
end;
end;
end;
end;
procedure TXMLReader.ValidateRoot;
begin
if Assigned(FDocType) then
begin
if not BufEquals(FName, FDocType.Name) then
ValidationError('Root element name does not match DTD', [], FName.Length);
end
else
ValidationError('Missing DTD', [], FName.Length);
end;
procedure TXMLReader.ValidateDTD;
var
I: Integer;
begin
if FValidate then
for I := 0 to FNotationRefs.Count-1 do
with PForwardRef(FNotationRefs[I])^ do
if FDocType.Notations.GetNamedItem(Value) = nil then
DoErrorPos(esError, Format('Notation ''%s'' is not declared', [Value]), Loc);
ClearRefs(FNotationRefs);
end;
procedure TXMLReader.DoText(ch: DOMPChar; Count: Integer; Whitespace: Boolean);
var
TextNode: TDOMText;
begin
if FState <> rsRoot then
if not Whitespace then
FatalError('Illegal at document level', -1)
else
Exit;
if (Whitespace and (not FPreserveWhitespace)) or (Count = 0) then
Exit;
// Validating filter part
case FCurrContentType of
ctChildren:
if not Whitespace then
ValidationError('Character data is not allowed in element-only content',[])
else
if FSaViolation then
StandaloneError(-1);
ctEmpty:
ValidationError('Character data is not allowed in EMPTY elements', []);
end;
// Document builder part
TextNode := Doc.CreateTextNodeBuf(ch, Count, Whitespace and (FCurrContentType = ctChildren));
FCursor.AppendChild(TextNode);
end;
procedure TXMLReader.DoAttrText(ch: DOMPChar; Count: Integer);
begin
FCursor.AppendChild(Doc.CreateTextNodeBuf(ch, Count, False));
end;
procedure TXMLReader.DoComment(ch: DOMPChar; Count: Integer);
var
Node: TDOMComment;
begin
// validation filter part
if FCurrContentType = ctEmpty then
ValidationError('Comments are not allowed within EMPTY elements', []);
// DOM builder part
if (not FIgnoreComments) and Assigned(FCursor) then
begin
Node := Doc.CreateCommentBuf(ch, Count);
FCursor.AppendChild(Node);
end;
end;
procedure TXMLReader.DoCDSect(ch: DOMPChar; Count: Integer);
var
s: DOMString;
begin
if FCurrContentType = ctChildren then
ValidationError('CDATA sections are not allowed in element-only content',[]);
if not FCDSectionsAsText then
begin
SetString(s, ch, Count);
// SAX: LexicalHandler.StartCDATA;
// SAX: ContentHandler.Characters(...);
FCursor.AppendChild(doc.CreateCDATASection(s));
// SAX: LexicalHandler.EndCDATA;
end
else
FCursor.AppendChild(doc.CreateTextNodeBuf(ch, Count, False));
end;
procedure TXMLReader.DoNotationDecl(const aName, aPubID, aSysID: DOMString);
var
Notation: TDOMNotationEx;
begin
if FDocType.Notations.GetNamedItem(aName) = nil then
begin
Notation := TDOMNotationEx(TDOMNotation.Create(doc));
Notation.FName := aName;
Notation.FPublicID := aPubID;
Notation.FSystemID := aSysID;
FDocType.Notations.SetNamedItem(Notation);
end
else
ValidationError('Duplicate notation declaration: ''%s''', [aName]);
end;
procedure TXMLReader.PushVC(aElement: TDOMElement; aElDef: TDOMElementDef);
begin
Inc(FNesting);
if FNesting >= Length(FValidator) then
SetLength(FValidator, FNesting * 2);
FValidator[FNesting].FElement := aElement;
FValidator[FNesting].FElementDef := aElDef;
FValidator[FNesting].FCurCP := nil;
FValidator[FNesting].FFailed := False;
UpdateConstraints;
end;
procedure TXMLReader.PopVC;
begin
if FNesting > 0 then Dec(FNesting);
UpdateConstraints;
end;
procedure TXMLReader.UpdateConstraints;
begin
if FValidate and Assigned(FValidator[FNesting].FElementDef) then
begin
FCurrContentType := FValidator[FNesting].FElementDef.ContentType;
FSaViolation := FStandalone and (FValidator[FNesting].FElementDef.FExternallyDeclared);
end
else
begin
FCurrContentType := ctAny;
FSaViolation := False;
end;
end;
{ TElementValidator }
function TElementValidator.IsElementAllowed(Def: TDOMElementDef): Boolean;
var
I: Integer;
Next: TContentParticle;
begin
Result := True;
// if element is not declared, non-validity has been already reported, no need to report again...
if Assigned(Def) and Assigned(FElementDef) then
begin
case FElementDef.ContentType of
ctMixed: begin
for I := 0 to FElementDef.RootCP.ChildCount-1 do
begin
if Def = FElementDef.RootCP.Children[I].Def then
Exit;
end;
Result := False;
end;
ctEmpty: Result := False;
ctChildren: begin
if FCurCP = nil then
Next := FElementDef.RootCP.FindFirst(Def)
else
Next := FCurCP.FindNext(Def, 0); { second arg ignored here }
Result := Assigned(Next);
if Result then
FCurCP := Next
else
FFailed := True; // used to prevent extra error at the end of element
end;
// ctAny, ctUndeclared: returns True by default
end;
end;
end;
function TElementValidator.Incomplete: Boolean;
begin
if Assigned(FElementDef) and (FElementDef.ContentType = ctChildren) and (not FFailed) then
begin
if FCurCP <> nil then
Result := FCurCP.MoreRequired(0) { arg ignored here }
else
Result := FElementDef.RootCP.IsRequired;
end
else
Result := False;
end;
{ TContentParticle }
function TContentParticle.Add: TContentParticle;
begin
if FChildren = nil then
FChildren := TFPList.Create;
Result := TContentParticle.Create;
Result.FParent := Self;
Result.FIndex := FChildren.Add(Result);
end;
destructor TContentParticle.Destroy;
var
I: Integer;
begin
if Assigned(FChildren) then
for I := FChildren.Count-1 downto 0 do
TObject(FChildren[I]).Free;
FChildren.Free;
inherited Destroy;
end;
function TContentParticle.GetChild(Index: Integer): TContentParticle;
begin
Result := TContentParticle(FChildren[Index]);
end;
function TContentParticle.GetChildCount: Integer;
begin
if Assigned(FChildren) then
Result := FChildren.Count
else
Result := 0;
end;
function TContentParticle.IsRequired: Boolean;
var
I: Integer;
begin
Result := (CPQuant = cqOnce) or (CPQuant = cqOnceOrMore);
// do not return True if all children are optional
if (CPType <> ctName) and Result then
begin
for I := 0 to ChildCount-1 do
begin
Result := Children[I].IsRequired;
if Result then Exit;
end;
end;
end;
function TContentParticle.MoreRequired(ChildIdx: Integer): Boolean;
var
I: Integer;
begin
Result := False;
if CPType = ctSeq then
begin
for I := ChildIdx + 1 to ChildCount-1 do
begin
Result := Children[I].IsRequired;
if Result then Exit;
end;
end;
if Assigned(FParent) then
Result := FParent.MoreRequired(FIndex);
end;
function TContentParticle.FindFirst(aDef: TDOMElementDef): TContentParticle;
var
I: Integer;
begin
Result := nil;
case CPType of
ctSeq:
for I := 0 to ChildCount-1 do with Children[I] do
begin
Result := FindFirst(aDef);
if Assigned(Result) or IsRequired then
Exit;
end;
ctChoice:
for I := 0 to ChildCount-1 do with Children[I] do
begin
Result := FindFirst(aDef);
if Assigned(Result) then
Exit;
end;
else // ctName
if aDef = Self.Def then
Result := Self
end;
end;
function TContentParticle.FindNext(aDef: TDOMElementDef;
ChildIdx: Integer): TContentParticle;
var
I: Integer;
begin
Result := nil;
if CPType = ctSeq then // search sequence to its end
begin
for I := ChildIdx + 1 to ChildCount-1 do with Children[I] do
begin
Result := FindFirst(aDef);
if (Result <> nil) or IsRequired then
Exit;
end;
end;
if (CPQuant = cqZeroOrMore) or (CPQuant = cqOnceOrMore) then
Result := FindFirst(aDef);
if (Result = nil) and Assigned(FParent) then
Result := FParent.FindNext(aDef, FIndex);
end;
{ TDOMElementDef }
destructor TDOMElementDef.Destroy;
begin
RootCP.Free;
inherited Destroy;
end;
{ plain calls }
procedure ReadXMLFile(out ADoc: TXMLDocument; var f: Text; Flags: TXMLReaderFlags);
var
Reader: TXMLReader;
Src: TXMLCharSource;
begin
ADoc := nil;
Src := TXMLFileInputSource.Create(f);
Reader := TXMLReader.Create;
try
Reader.Flags:=Flags;
Reader.ProcessXML(Src);
finally
ADoc := TXMLDocument(Reader.Doc);
Reader.Free;
end;
end;
procedure ReadXMLFile(out ADoc: TXMLDocument; f: TStream; const ABaseURI: String;
Flags: TXMLReaderFlags);
var
Reader: TXMLReader;
Src: TXMLCharSource;
begin
ADoc := nil;
Reader := TXMLReader.Create;
try
Src := TXMLStreamInputSource.Create(f, False);
Src.SystemID := ABaseURI;
Reader.Flags:=Flags;
Reader.ProcessXML(Src);
finally
ADoc := TXMLDocument(Reader.doc);
Reader.Free;
end;
end;
procedure ReadXMLFile(out ADoc: TXMLDocument; var f: File;
Flags: TXMLReaderFlags);
var
BufSize: Int64;
ms: TMemoryStream;
begin
ADoc := nil;
BufSize := FileSize(f) + 1;
if BufSize <= 1 then
exit;
ms:=TMemoryStream.Create;
try
ms.Size:=BufSize;
BlockRead(f, ms.Memory^, BufSize - 1);
PChar(ms.Memory)[BufSize - 1] := #0;
ms.Position:=0;
ReadXMLFile(ADoc,ms,Flags);
finally
ms.Free;
end;
end;
procedure ReadXMLFile(out ADoc: TXMLDocument; f: TStream; Flags: TXMLReaderFlags);
begin
ReadXMLFile(ADoc, f, 'stream:', Flags);
end;
procedure ReadXMLFile(out ADoc: TXMLDocument; const AFilename: String;
Flags: TXMLReaderFlags);
var
FileStream: TStream;
begin
ADoc := nil;
FileStream := TFileStreamUTF8.Create(AFilename, fmOpenRead+fmShareDenyWrite);
try
ReadXMLFile(ADoc, FileStream, FilenameToURI(AFilename), Flags);
finally
FileStream.Free;
end;
end;
procedure ReadXMLFragment(AParentNode: TDOMNode; var f: Text;
Flags: TXMLReaderFlags);
var
Reader: TXMLReader;
Src: TXMLCharSource;
begin
Reader := TXMLReader.Create;
try
Reader.Flags:=Flags;
Src := TXMLFileInputSource.Create(f);
Reader.ProcessFragment(Src, AParentNode);
finally
Reader.Free;
end;
end;
procedure ReadXMLFragment(AParentNode: TDOMNode; f: TStream;
const ABaseURI: String; Flags: TXMLReaderFlags);
var
Reader: TXMLReader;
Src: TXMLCharSource;
begin
Reader := TXMLReader.Create;
try
Src := TXMLStreamInputSource.Create(f, False);
Src.SystemID := ABaseURI;
Reader.Flags:=Flags;
Reader.ProcessFragment(Src, AParentNode);
finally
Reader.Free;
end;
end;
procedure ReadXMLFragment(AParentNode: TDOMNode; var f: File;
Flags: TXMLReaderFlags);
var
BufSize: Int64;
ms: TMemoryStream;
begin
BufSize := FileSize(f) + 1;
if BufSize <= 1 then
exit;
ms:=TMemoryStream.Create;
try
ms.Size:=BufSize;
BlockRead(f, ms.Memory^, BufSize - 1);
PChar(ms.Memory)[BufSize - 1] := #0;
ms.Position:=0;
ReadXMLFragment(AParentNode,ms,'stream:',Flags);
finally
ms.Free;
end;
end;
procedure ReadXMLFragment(AParentNode: TDOMNode; f: TStream;
Flags: TXMLReaderFlags);
begin
ReadXMLFragment(AParentNode, f, 'stream:', Flags);
end;
procedure ReadXMLFragment(AParentNode: TDOMNode; const AFilename: String;
Flags: TXMLReaderFlags);
var
Stream: TStream;
begin
Stream := TFileStreamUTF8.Create(AFilename, fmOpenRead+fmShareDenyWrite);
try
ReadXMLFragment(AParentNode, Stream, FilenameToURI(AFilename), Flags);
finally
Stream.Free;
end;
end;
procedure ReadDTDFile(out ADoc: TXMLDocument; var f: Text);
var
Reader: TXMLReader;
Src: TXMLCharSource;
begin
ADoc := nil;
Reader := TXMLReader.Create;
try
Src := TXMLFileInputSource.Create(f);
Reader.ProcessDTD(Src);
finally
ADoc := TXMLDocument(Reader.doc);
Reader.Free;
end;
end;
procedure ReadDTDFile(out ADoc: TXMLDocument; f: TStream; const ABaseURI: String);
var
Reader: TXMLReader;
Src: TXMLCharSource;
begin
ADoc := nil;
Reader := TXMLReader.Create;
try
Src := TXMLStreamInputSource.Create(f, False);
Src.SystemID := ABaseURI;
Reader.ProcessDTD(Src);
finally
ADoc := TXMLDocument(Reader.doc);
Reader.Free;
end;
end;
procedure ReadDTDFile(out ADoc: TXMLDocument; var f: File);
var
BufSize: Int64;
ms: TMemoryStream;
begin
ADoc := nil;
BufSize := FileSize(f) + 1;
if BufSize <= 1 then
exit;
ms:=TMemoryStream.Create;
try
ms.Size:=BufSize;
BlockRead(f, ms.Memory^, BufSize - 1);
PChar(ms.Memory)[BufSize - 1] := #0;
ms.Position:=0;
ReadDTDFile(ADoc,ms,'stream:');
finally
ms.Free;
end;
end;
procedure ReadDTDFile(out ADoc: TXMLDocument; f: TStream);
begin
ReadDTDFile(ADoc, f, 'stream:');
end;
procedure ReadDTDFile(out ADoc: TXMLDocument; const AFilename: String);
var
Stream: TStream;
begin
ADoc := nil;
Stream := TFileStreamUTF8.Create(AFilename, fmOpenRead+fmShareDenyWrite);
try
ReadDTDFile(ADoc, Stream, FilenameToURI(AFilename));
finally
Stream.Free;
end;
end;
{ EXMLReadError }
function EXMLReadError.LineCol: TPoint;
begin
Result.Y:=Line;
Result.X:=LinePos;
end;
procedure InitXMLRead;
{$IFDEF UseUTF8}
var
c: Char;
{$ENDIF}
begin
{$IFDEF UseUTF8}
for c:=low(char) to high(char) do begin
IsNameStartChar[c]:=c in ['A'..'Z','a'..'z','_',#128..#255];
IsNameChar[c]:=c in ['A'..'Z','a'..'z','_','0'..'9','-','.',#128..#255];
end;
{$ENDIF}
end;
initialization
InitXMLRead;
end.
|