1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// INCLUDE ---------------------------------------------------------------
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <basic/sbmeth.hxx>
#include <basic/sbstar.hxx>
#include <svl/zforlist.hxx>
#include <sal/macros.h>
#include <tools/rcid.h>
#include <tools/rc.hxx>
#include <tools/solar.h>
#include <unotools/charclass.hxx>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/sheet/FormulaOpCodeMapEntry.hpp>
#include <com/sun/star/sheet/FormulaLanguage.hpp>
#include <com/sun/star/sheet/FormulaMapGroup.hpp>
#include <comphelper/processfactory.hxx>
#include <unotools/transliterationwrapper.hxx>
#include <comphelper/string.hxx>
#include <tools/urlobj.hxx>
#include <rtl/math.hxx>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "compiler.hxx"
#include "rangenam.hxx"
#include "dbdata.hxx"
#include "document.hxx"
#include "callform.hxx"
#include "addincol.hxx"
#include "refupdat.hxx"
#include "scresid.hxx"
#include "sc.hrc"
#include "globstr.hrc"
#include "cell.hxx"
#include "dociter.hxx"
#include "docoptio.hxx"
#include <formula/errorcodes.hxx>
#include "parclass.hxx"
#include "autonamecache.hxx"
#include "externalrefmgr.hxx"
#include "rangeutl.hxx"
#include "convuno.hxx"
#include "tokenuno.hxx"
#include "formulaparserpool.hxx"
using namespace formula;
using namespace ::com::sun::star;
using rtl::OUString;
using ::std::vector;
CharClass* ScCompiler::pCharClassEnglish = NULL;
const ScCompiler::Convention* ScCompiler::pConventions[ ] = { NULL, NULL, NULL, NULL, NULL, NULL };
enum ScanState
{
ssGetChar,
ssGetBool,
ssGetValue,
ssGetString,
ssSkipString,
ssGetIdent,
ssGetReference,
ssSkipReference,
ssGetErrorConstant,
ssStop
};
static const sal_Char* pInternal[ 1 ] = { "TTT" };
using namespace ::com::sun::star::i18n;
/////////////////////////////////////////////////////////////////////////
class ScCompilerRecursionGuard
{
private:
short& rRecursion;
public:
ScCompilerRecursionGuard( short& rRec )
: rRecursion( rRec ) { ++rRecursion; }
~ScCompilerRecursionGuard() { --rRecursion; }
};
void ScCompiler::fillFromAddInMap( NonConstOpCodeMapPtr xMap,FormulaGrammar::Grammar _eGrammar ) const
{
size_t nSymbolOffset;
switch( _eGrammar )
{
case FormulaGrammar::GRAM_PODF:
nSymbolOffset = offsetof( AddInMap, pUpper);
break;
default:
case FormulaGrammar::GRAM_ODFF:
nSymbolOffset = offsetof( AddInMap, pODFF);
break;
case FormulaGrammar::GRAM_ENGLISH:
nSymbolOffset = offsetof( AddInMap, pEnglish);
break;
}
const AddInMap* pMap = GetAddInMap();
const AddInMap* const pStop = pMap + GetAddInMapCount();
for ( ; pMap < pStop; ++pMap)
{
char const * const * ppSymbol =
reinterpret_cast< char const * const * >(
reinterpret_cast< char const * >(pMap) + nSymbolOffset);
xMap->putExternal( String::CreateFromAscii( *ppSymbol),
String::CreateFromAscii( pMap->pOriginal));
}
}
void ScCompiler::fillFromAddInCollectionUpperName( NonConstOpCodeMapPtr xMap ) const
{
ScUnoAddInCollection* pColl = ScGlobal::GetAddInCollection();
long nCount = pColl->GetFuncCount();
for (long i=0; i < nCount; ++i)
{
const ScUnoAddInFuncData* pFuncData = pColl->GetFuncData(i);
if (pFuncData)
xMap->putExternalSoftly( pFuncData->GetUpperName(),
pFuncData->GetOriginalName());
}
}
void ScCompiler::fillFromAddInCollectionEnglishName( NonConstOpCodeMapPtr xMap ) const
{
ScUnoAddInCollection* pColl = ScGlobal::GetAddInCollection();
long nCount = pColl->GetFuncCount();
for (long i=0; i < nCount; ++i)
{
const ScUnoAddInFuncData* pFuncData = pColl->GetFuncData(i);
if (pFuncData)
{
String aName;
if (pFuncData->GetExcelName( LANGUAGE_ENGLISH_US, aName))
xMap->putExternalSoftly( aName, pFuncData->GetOriginalName());
else
xMap->putExternalSoftly( pFuncData->GetUpperName(),
pFuncData->GetOriginalName());
}
}
}
void ScCompiler::DeInit()
{
if (pCharClassEnglish)
{
delete pCharClassEnglish;
pCharClassEnglish = NULL;
}
}
bool ScCompiler::IsEnglishSymbol( const String& rName )
{
// function names are always case-insensitive
String aUpper( ScGlobal::pCharClass->upper( rName ) );
// 1. built-in function name
OpCode eOp = ScCompiler::GetEnglishOpCode( aUpper );
if ( eOp != ocNone )
{
return true;
}
// 2. old add in functions
sal_uInt16 nIndex;
if ( ScGlobal::GetFuncCollection()->SearchFunc( aUpper, nIndex ) )
{
return true;
}
// 3. new (uno) add in functions
String aIntName(ScGlobal::GetAddInCollection()->FindFunction( aUpper, false ));
if (aIntName.Len())
{
return true;
}
return false; // no valid function name
}
void ScCompiler::InitCharClassEnglish()
{
::com::sun::star::lang::Locale aLocale(
OUString( RTL_CONSTASCII_USTRINGPARAM( "en")),
OUString( RTL_CONSTASCII_USTRINGPARAM( "US")),
OUString());
pCharClassEnglish = new CharClass(
::comphelper::getProcessServiceFactory(), aLocale);
}
void ScCompiler::SetGrammar( const FormulaGrammar::Grammar eGrammar )
{
OSL_ENSURE( eGrammar != FormulaGrammar::GRAM_UNSPECIFIED, "ScCompiler::SetGrammar: don't pass FormulaGrammar::GRAM_UNSPECIFIED");
if (eGrammar == GetGrammar())
return; // nothing to be done
if( eGrammar == FormulaGrammar::GRAM_EXTERNAL )
{
meGrammar = eGrammar;
mxSymbols = GetOpCodeMap( ::com::sun::star::sheet::FormulaLanguage::NATIVE);
}
else
{
FormulaGrammar::Grammar eMyGrammar = eGrammar;
const sal_Int32 nFormulaLanguage = FormulaGrammar::extractFormulaLanguage( eMyGrammar);
OpCodeMapPtr xMap = GetOpCodeMap( nFormulaLanguage);
OSL_ENSURE( xMap, "ScCompiler::SetGrammar: unknown formula language");
if (!xMap)
{
xMap = GetOpCodeMap( ::com::sun::star::sheet::FormulaLanguage::NATIVE);
eMyGrammar = xMap->getGrammar();
}
// Save old grammar for call to SetGrammarAndRefConvention().
FormulaGrammar::Grammar eOldGrammar = GetGrammar();
// This also sets the grammar associated with the map!
SetFormulaLanguage( xMap);
// Override if necessary.
if (eMyGrammar != GetGrammar())
SetGrammarAndRefConvention( eMyGrammar, eOldGrammar);
}
}
ScCompiler::EncodeUrlMode ScCompiler::GetEncodeUrlMode() const
{
return meEncodeUrlMode;
}
void ScCompiler::SetFormulaLanguage( const ScCompiler::OpCodeMapPtr & xMap )
{
if (xMap.get())
{
mxSymbols = xMap;
if (mxSymbols->isEnglish())
{
if (!pCharClassEnglish)
InitCharClassEnglish();
pCharClass = pCharClassEnglish;
}
else
pCharClass = ScGlobal::pCharClass;
SetGrammarAndRefConvention( mxSymbols->getGrammar(), GetGrammar());
}
}
void ScCompiler::SetGrammarAndRefConvention(
const FormulaGrammar::Grammar eNewGrammar, const FormulaGrammar::Grammar eOldGrammar )
{
meGrammar = eNewGrammar; //! SetRefConvention needs the new grammar set!
FormulaGrammar::AddressConvention eConv = FormulaGrammar::extractRefConvention( meGrammar);
if (eConv == FormulaGrammar::CONV_UNSPECIFIED && eOldGrammar == FormulaGrammar::GRAM_UNSPECIFIED)
{
if (pDoc)
SetRefConvention( pDoc->GetAddressConvention());
else
SetRefConvention( pConvOOO_A1);
}
else
SetRefConvention( eConv );
}
String ScCompiler::FindAddInFunction( const String& rUpperName, bool bLocalFirst ) const
{
return ScGlobal::GetAddInCollection()->FindFunction(rUpperName, bLocalFirst); // bLocalFirst=false for english
}
//-----------------------------------------------------------------------------
ScCompiler::Convention::~Convention()
{
delete [] mpCharTable;
mpCharTable = NULL;
}
ScCompiler::Convention::Convention( FormulaGrammar::AddressConvention eConv )
:
meConv( eConv )
{
int i;
sal_uLong *t= new sal_uLong [128];
ScCompiler::pConventions[ meConv ] = this;
mpCharTable = t;
for (i = 0; i < 128; i++)
t[i] = SC_COMPILER_C_ILLEGAL;
/* */ t[32] = SC_COMPILER_C_CHAR_DONTCARE | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* ! */ t[33] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
if (FormulaGrammar::CONV_ODF == meConv)
/* ! */ t[33] |= SC_COMPILER_C_ODF_LABEL_OP;
/* " */ t[34] = SC_COMPILER_C_CHAR_STRING | SC_COMPILER_C_STRING_SEP;
/* # */ t[35] = SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_CHAR_ERRCONST;
/* $ */ t[36] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_IDENT | SC_COMPILER_C_IDENT;
if (FormulaGrammar::CONV_ODF == meConv)
/* $ */ t[36] |= SC_COMPILER_C_ODF_NAME_MARKER;
/* % */ t[37] = SC_COMPILER_C_VALUE;
/* & */ t[38] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* ' */ t[39] = SC_COMPILER_C_NAME_SEP;
/* ( */ t[40] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* ) */ t[41] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* * */ t[42] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* + */ t[43] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_EXP | SC_COMPILER_C_VALUE_SIGN;
/* , */ t[44] = SC_COMPILER_C_CHAR_VALUE | SC_COMPILER_C_VALUE;
/* - */ t[45] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_EXP | SC_COMPILER_C_VALUE_SIGN;
/* . */ t[46] = SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_VALUE | SC_COMPILER_C_VALUE | SC_COMPILER_C_IDENT | SC_COMPILER_C_NAME;
/* / */ t[47] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
for (i = 48; i < 58; i++)
/* 0-9 */ t[i] = SC_COMPILER_C_CHAR_VALUE | SC_COMPILER_C_WORD | SC_COMPILER_C_VALUE | SC_COMPILER_C_VALUE_EXP | SC_COMPILER_C_VALUE_VALUE | SC_COMPILER_C_IDENT | SC_COMPILER_C_NAME;
/* : */ t[58] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD;
/* ; */ t[59] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* < */ t[60] = SC_COMPILER_C_CHAR_BOOL | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* = */ t[61] = SC_COMPILER_C_CHAR | SC_COMPILER_C_BOOL | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* > */ t[62] = SC_COMPILER_C_CHAR_BOOL | SC_COMPILER_C_BOOL | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* ? */ t[63] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_NAME;
/* @ */ // FREE
for (i = 65; i < 91; i++)
/* A-Z */ t[i] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_IDENT | SC_COMPILER_C_IDENT | SC_COMPILER_C_CHAR_NAME | SC_COMPILER_C_NAME;
if (FormulaGrammar::CONV_ODF == meConv)
{
/* [ */ t[91] = SC_COMPILER_C_ODF_LBRACKET;
/* \ */ // FREE
/* ] */ t[93] = SC_COMPILER_C_ODF_RBRACKET;
}
else
{
/* [ */ // FREE
/* \ */ // FREE
/* ] */ // FREE
}
/* ^ */ t[94] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
/* _ */ t[95] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_IDENT | SC_COMPILER_C_IDENT | SC_COMPILER_C_CHAR_NAME | SC_COMPILER_C_NAME;
/* ` */ // FREE
for (i = 97; i < 123; i++)
/* a-z */ t[i] = SC_COMPILER_C_CHAR_WORD | SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_IDENT | SC_COMPILER_C_IDENT | SC_COMPILER_C_CHAR_NAME | SC_COMPILER_C_NAME;
/* { */ t[123] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP; // array open
/* | */ t[124] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP; // array row sep (Should be OOo specific)
/* } */ t[125] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP; // array close
/* ~ */ t[126] = SC_COMPILER_C_CHAR; // OOo specific
/* 127 */ // FREE
if( FormulaGrammar::CONV_XL_A1 == meConv || FormulaGrammar::CONV_XL_R1C1 == meConv || FormulaGrammar::CONV_XL_OOX == meConv )
{
/* */ t[32] |= SC_COMPILER_C_WORD;
/* ! */ t[33] |= SC_COMPILER_C_IDENT | SC_COMPILER_C_WORD;
/* " */ t[34] |= SC_COMPILER_C_WORD;
/* # */ t[35] &= (~SC_COMPILER_C_WORD_SEP);
/* # */ t[35] |= SC_COMPILER_C_WORD;
/* % */ t[37] |= SC_COMPILER_C_WORD;
/* ' */ t[39] |= SC_COMPILER_C_WORD;
/* % */ t[37] |= SC_COMPILER_C_WORD;
/* & */ t[38] |= SC_COMPILER_C_WORD;
/* ' */ t[39] |= SC_COMPILER_C_WORD;
/* ( */ t[40] |= SC_COMPILER_C_WORD;
/* ) */ t[41] |= SC_COMPILER_C_WORD;
/* * */ t[42] |= SC_COMPILER_C_WORD;
/* + */ t[43] |= SC_COMPILER_C_WORD;
#if 0 /* this really needs to be locale specific. */
/* , */ t[44] = SC_COMPILER_C_CHAR | SC_COMPILER_C_WORD_SEP | SC_COMPILER_C_VALUE_SEP;
#else
/* , */ t[44] |= SC_COMPILER_C_WORD;
#endif
/* - */ t[45] |= SC_COMPILER_C_WORD;
/* ; */ t[59] |= SC_COMPILER_C_WORD;
/* < */ t[60] |= SC_COMPILER_C_WORD;
/* = */ t[61] |= SC_COMPILER_C_WORD;
/* > */ t[62] |= SC_COMPILER_C_WORD;
/* ? */ // question really is not permitted in sheet name
/* @ */ t[64] |= SC_COMPILER_C_WORD;
/* [ */ t[91] |= SC_COMPILER_C_WORD;
/* ] */ t[93] |= SC_COMPILER_C_WORD;
/* { */ t[123]|= SC_COMPILER_C_WORD;
/* | */ t[124]|= SC_COMPILER_C_WORD;
/* } */ t[125]|= SC_COMPILER_C_WORD;
/* ~ */ t[126]|= SC_COMPILER_C_WORD;
if( FormulaGrammar::CONV_XL_R1C1 == meConv )
{
/* [ */ t[91] |= SC_COMPILER_C_IDENT;
/* ] */ t[93] |= SC_COMPILER_C_IDENT;
}
if( FormulaGrammar::CONV_XL_OOX == meConv )
{
/* [ */ t[91] |= SC_COMPILER_C_CHAR_IDENT;
/* ] */ t[93] |= SC_COMPILER_C_IDENT;
}
}
}
//-----------------------------------------------------------------------------
static bool lcl_isValidQuotedText( const String& rFormula, xub_StrLen nSrcPos, ParseResult& rRes )
{
// Tokens that start at ' can have anything in them until a final '
// but '' marks an escaped '
// We've earlier guaranteed that a string containing '' will be
// surrounded by '
if (rFormula.GetChar(nSrcPos) == '\'')
{
xub_StrLen nPos = nSrcPos+1;
while (nPos < rFormula.Len())
{
if (rFormula.GetChar(nPos) == '\'')
{
if ( (nPos+1 == rFormula.Len()) || (rFormula.GetChar(nPos+1) != '\'') )
{
rRes.TokenType = KParseType::SINGLE_QUOTE_NAME;
rRes.EndPos = nPos+1;
return true;
}
++nPos;
}
++nPos;
}
}
return false;
}
static bool lcl_parseExternalName(
const String& rSymbol,
String& rFile,
String& rName,
const sal_Unicode cSep,
const ScDocument* pDoc = NULL,
const uno::Sequence< const sheet::ExternalLinkInfo > * pExternalLinks = NULL )
{
/* TODO: future versions will have to support sheet-local names too, thus
* return a possible sheet name as well. */
const sal_Unicode* const pStart = rSymbol.GetBuffer();
const sal_Unicode* p = pStart;
xub_StrLen nLen = rSymbol.Len();
sal_Unicode cPrev = 0;
String aTmpFile, aTmpName;
xub_StrLen i = 0;
bool bInName = false;
if (cSep == '!')
{
// For XL use existing parser that resolves bracketed and quoted and
// indexed external document names.
ScRange aRange;
String aStartTabName, aEndTabName;
sal_uInt16 nFlags = 0;
p = aRange.Parse_XL_Header( p, pDoc, aTmpFile, aStartTabName,
aEndTabName, nFlags, true, pExternalLinks );
if (!p || p == pStart)
return false;
i = xub_StrLen(p - pStart);
cPrev = *(p-1);
}
for ( ; i < nLen; ++i, ++p)
{
sal_Unicode c = *p;
if (i == 0)
{
if (c == '.' || c == cSep)
return false;
if (c == '\'')
{
// Move to the next char and loop until the second single
// quote.
cPrev = c;
++i; ++p;
for (xub_StrLen j = i; j < nLen; ++j, ++p)
{
c = *p;
if (c == '\'')
{
if (j == i)
{
// empty quote e.g. (=''!Name)
return false;
}
if (cPrev == '\'')
{
// two consecutive quotes equal a single quote in
// the file name.
aTmpFile.Append(c);
cPrev = 'a';
}
else
cPrev = c;
continue;
}
if (cPrev == '\'' && j != i)
{
// this is not a quote but the previous one is. This
// ends the parsing of the quoted segment. At this
// point, the current char must equal the separator
// char.
i = j;
bInName = true;
aTmpName.Append(c); // Keep the separator as part of the name.
break;
}
aTmpFile.Append(c);
cPrev = c;
}
if (!bInName)
{
// premature ending of the quoted segment.
return false;
}
if (c != cSep)
{
// only the separator is allowed after the closing quote.
return false;
}
cPrev = c;
continue;
}
}
if (bInName)
{
if (c == cSep)
{
// A second separator ? Not a valid external name.
return false;
}
aTmpName.Append(c);
}
else
{
if (c == cSep)
{
bInName = true;
aTmpName.Append(c); // Keep the separator as part of the name.
}
else
{
do
{
if (CharClass::isAsciiAlphaNumeric(c))
// allowed.
break;
if (c > 128)
// non-ASCII character is allowed.
break;
bool bValid = false;
switch (c)
{
case '_':
case '-':
case '.':
// these special characters are allowed.
bValid = true;
break;
}
if (bValid)
break;
return false;
}
while (false);
aTmpFile.Append(c);
}
}
cPrev = c;
}
if (!bInName)
{
// No name found - most likely the symbol has no '!'s.
return false;
}
xub_StrLen nNameLen = aTmpName.Len();
if (nNameLen < 2)
{
// Name must be at least 2-char long (separator plus name).
return false;
}
if (aTmpName.GetChar(0) != cSep)
{
// 1st char of the name must equal the separator.
return false;
}
sal_Unicode cLast = aTmpName.GetChar(nNameLen-1);
if (cLast == sal_Unicode('!'))
{
// Check against #REF!.
if (aTmpName.EqualsAscii("#REF!"))
return false;
}
rFile = aTmpFile;
rName = aTmpName.Copy(1); // Skip the first char as it is always the separator.
return true;
}
static String lcl_makeExternalNameStr( const String& rFile, const String& rName,
const sal_Unicode cSep, bool bODF )
{
String aFile( rFile), aName( rName), aEscQuote( RTL_CONSTASCII_USTRINGPARAM("''"));
aFile.SearchAndReplaceAllAscii( "'", aEscQuote);
if (bODF)
aName.SearchAndReplaceAllAscii( "'", aEscQuote);
rtl::OUStringBuffer aBuf( aFile.Len() + aName.Len() + 9);
if (bODF)
aBuf.append( sal_Unicode( '['));
aBuf.append( sal_Unicode( '\''));
aBuf.append( aFile);
aBuf.append( sal_Unicode( '\''));
aBuf.append( cSep);
if (bODF)
aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "$$'"));
aBuf.append( aName);
if (bODF)
aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "']"));
return String( aBuf.makeStringAndClear());
}
static bool lcl_getLastTabName( OUString& rTabName2, const OUString& rTabName1,
const vector<OUString>& rTabNames, const ScComplexRefData& rRef )
{
SCsTAB nTabSpan = rRef.Ref2.nTab - rRef.Ref1.nTab;
if (nTabSpan > 0)
{
size_t nCount = rTabNames.size();
vector<OUString>::const_iterator itrBeg = rTabNames.begin(), itrEnd = rTabNames.end();
vector<OUString>::const_iterator itr = ::std::find(itrBeg, itrEnd, rTabName1);
if (itr == rTabNames.end())
{
rTabName2 = ScGlobal::GetRscString(STR_NO_REF_TABLE);
return false;
}
size_t nDist = ::std::distance(itrBeg, itr);
if (nDist + static_cast<size_t>(nTabSpan) >= nCount)
{
rTabName2 = ScGlobal::GetRscString(STR_NO_REF_TABLE);
return false;
}
rTabName2 = rTabNames[nDist+nTabSpan];
}
else
rTabName2 = rTabName1;
return true;
}
struct Convention_A1 : public ScCompiler::Convention
{
Convention_A1( FormulaGrammar::AddressConvention eConv ) : ScCompiler::Convention( eConv ) { }
static void MakeColStr( rtl::OUStringBuffer& rBuffer, SCCOL nCol );
static void MakeRowStr( rtl::OUStringBuffer& rBuffer, SCROW nRow );
ParseResult parseAnyToken( const String& rFormula,
xub_StrLen nSrcPos,
const CharClass* pCharClass) const
{
ParseResult aRet;
if ( lcl_isValidQuotedText(rFormula, nSrcPos, aRet) )
return aRet;
static const sal_Int32 nStartFlags = KParseTokens::ANY_LETTER_OR_NUMBER |
KParseTokens::ASC_UNDERSCORE | KParseTokens::ASC_DOLLAR;
static const sal_Int32 nContFlags = nStartFlags | KParseTokens::ASC_DOT;
// '?' allowed in range names because of Xcl :-/
static const String aAddAllowed(String::CreateFromAscii("?#"));
return pCharClass->parseAnyToken( rFormula,
nSrcPos, nStartFlags, aAddAllowed, nContFlags, aAddAllowed );
}
virtual sal_uLong getCharTableFlags( sal_Unicode c, sal_Unicode /*cLast*/ ) const
{
return mpCharTable[static_cast<sal_uInt8>(c)];
}
};
void Convention_A1::MakeColStr( rtl::OUStringBuffer& rBuffer, SCCOL nCol )
{
if ( !ValidCol( nCol) )
rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
else
::ScColToAlpha( rBuffer, nCol);
}
void Convention_A1::MakeRowStr( rtl::OUStringBuffer& rBuffer, SCROW nRow )
{
if ( !ValidRow(nRow) )
rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
else
rBuffer.append(sal_Int32(nRow + 1));
}
//-----------------------------------------------------------------------------
struct ConventionOOO_A1 : public Convention_A1
{
ConventionOOO_A1() : Convention_A1 (FormulaGrammar::CONV_OOO) { }
ConventionOOO_A1( FormulaGrammar::AddressConvention eConv ) : Convention_A1 (eConv) { }
static String MakeTabStr( const ScCompiler& rComp, SCTAB nTab, String& aDoc )
{
String aString;
rtl::OUString aTmp;
if (!rComp.GetDoc()->GetName( nTab, aTmp ))
aString = ScGlobal::GetRscString(STR_NO_REF_TABLE);
else
{
aString = aTmp;
if ( aString.GetChar(0) == '\'' )
{ // "'Doc'#Tab"
xub_StrLen nPos = ScGlobal::FindUnquoted( aString, SC_COMPILER_FILE_TAB_SEP);
if (nPos != STRING_NOTFOUND && nPos > 0 && aString.GetChar(nPos-1) == '\'')
{
aDoc = aString.Copy( 0, nPos + 1 );
aString.Erase( 0, nPos + 1 );
aDoc = INetURLObject::decode( aDoc, INET_HEX_ESCAPE,
INetURLObject::DECODE_UNAMBIGUOUS );
}
else
aDoc.Erase();
}
else
aDoc.Erase();
ScCompiler::CheckTabQuotes( aString, FormulaGrammar::CONV_OOO );
}
aString += '.';
return aString;
}
void MakeOneRefStrImpl( rtl::OUStringBuffer& rBuffer,
const ScCompiler& rComp,
const ScSingleRefData& rRef,
bool bForceTab,
bool bODF ) const
{
if( rRef.IsFlag3D() || bForceTab )
{
if (rRef.IsTabDeleted())
{
if (!rRef.IsTabRel())
rBuffer.append(sal_Unicode('$'));
rBuffer.append( rComp.GetCurrentOpCodeMap()->getSymbol( ocErrRef));
rBuffer.append(sal_Unicode('.'));
}
else
{
String aDoc;
String aRefStr( MakeTabStr( rComp, rRef.nTab, aDoc ) );
rBuffer.append(aDoc);
if (!rRef.IsTabRel())
rBuffer.append(sal_Unicode('$'));
rBuffer.append(aRefStr);
}
}
else if (bODF)
rBuffer.append(sal_Unicode('.'));
if (!rRef.IsColRel())
rBuffer.append(sal_Unicode('$'));
if ( rRef.IsColDeleted() )
rBuffer.append( rComp.GetCurrentOpCodeMap()->getSymbol( ocErrRef));
else
MakeColStr(rBuffer, rRef.nCol );
if (!rRef.IsRowRel())
rBuffer.append(sal_Unicode('$'));
if ( rRef.IsRowDeleted() )
rBuffer.append( rComp.GetCurrentOpCodeMap()->getSymbol( ocErrRef));
else
MakeRowStr( rBuffer, rRef.nRow );
}
void MakeRefStrImpl( rtl::OUStringBuffer& rBuffer,
const ScCompiler& rComp,
const ScComplexRefData& rRef,
bool bSingleRef,
bool bODF ) const
{
if (bODF)
rBuffer.append(sal_Unicode('['));
ScComplexRefData aRef( rRef );
// In case absolute/relative positions weren't separately available:
// transform relative to absolute!
aRef.Ref1.CalcAbsIfRel( rComp.GetPos() );
if( !bSingleRef )
aRef.Ref2.CalcAbsIfRel( rComp.GetPos() );
if (bODF && FormulaGrammar::isODFF( rComp.GetGrammar()) &&
(aRef.Ref1.IsColDeleted() || aRef.Ref1.IsRowDeleted() || aRef.Ref1.IsTabDeleted() ||
aRef.Ref2.IsColDeleted() || aRef.Ref2.IsRowDeleted() || aRef.Ref2.IsTabDeleted()))
rBuffer.append( rComp.GetCurrentOpCodeMap()->getSymbol( ocErrRef));
// For ODFF write [#REF!], but not for PODF so apps reading ODF
// 1.0/1.1 may have a better chance if they implemented the old
// form.
else
{
MakeOneRefStrImpl( rBuffer, rComp, aRef.Ref1, false, bODF);
if (!bSingleRef)
{
rBuffer.append(sal_Unicode(':'));
MakeOneRefStrImpl( rBuffer, rComp, aRef.Ref2, (aRef.Ref2.nTab != aRef.Ref1.nTab), bODF);
}
}
if (bODF)
rBuffer.append(sal_Unicode(']'));
}
void MakeRefStr( rtl::OUStringBuffer& rBuffer,
const ScCompiler& rComp,
const ScComplexRefData& rRef,
bool bSingleRef ) const
{
MakeRefStrImpl( rBuffer, rComp, rRef, bSingleRef, false);
}
virtual sal_Unicode getSpecialSymbol( SpecialSymbolType eSymType ) const
{
switch (eSymType)
{
case ScCompiler::Convention::ABS_SHEET_PREFIX:
return '$';
case ScCompiler::Convention::SHEET_SEPARATOR:
return '.';
}
return sal_Unicode(0);
}
virtual bool parseExternalName( const String& rSymbol, String& rFile, String& rName,
const ScDocument* pDoc,
const ::com::sun::star::uno::Sequence<
const ::com::sun::star::sheet::ExternalLinkInfo > * pExternalLinks ) const
{
return lcl_parseExternalName(rSymbol, rFile, rName, sal_Unicode('#'), pDoc, pExternalLinks);
}
virtual String makeExternalNameStr( const String& rFile, const String& rName ) const
{
return lcl_makeExternalNameStr( rFile, rName, sal_Unicode('#'), false);
}
bool makeExternalSingleRefStr( ::rtl::OUStringBuffer& rBuffer, sal_uInt16 nFileId,
const String& rTabName, const ScSingleRefData& rRef,
ScExternalRefManager* pRefMgr, bool bDisplayTabName, bool bEncodeUrl ) const
{
if (bDisplayTabName)
{
String aFile;
const OUString* p = pRefMgr->getExternalFileName(nFileId);
if (p)
{
if (bEncodeUrl)
aFile = *p;
else
aFile = INetURLObject::decode(*p, INET_HEX_ESCAPE, INetURLObject::DECODE_UNAMBIGUOUS);
}
aFile.SearchAndReplaceAllAscii("'", String::CreateFromAscii("''"));
rBuffer.append(sal_Unicode('\''));
rBuffer.append(aFile);
rBuffer.append(sal_Unicode('\''));
rBuffer.append(sal_Unicode('#'));
if (!rRef.IsTabRel())
rBuffer.append(sal_Unicode('$'));
ScRangeStringConverter::AppendTableName(rBuffer, rTabName);
rBuffer.append(sal_Unicode('.'));
}
if (!rRef.IsColRel())
rBuffer.append(sal_Unicode('$'));
MakeColStr( rBuffer, rRef.nCol);
if (!rRef.IsRowRel())
rBuffer.append(sal_Unicode('$'));
MakeRowStr( rBuffer, rRef.nRow);
return true;
}
void makeExternalRefStrImpl( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
ScExternalRefManager* pRefMgr, bool bODF ) const
{
ScSingleRefData aRef(rRef);
aRef.CalcAbsIfRel(rCompiler.GetPos());
if (bODF)
rBuffer.append( sal_Unicode('['));
bool bEncodeUrl = true;
switch (rCompiler.GetEncodeUrlMode())
{
case ScCompiler::ENCODE_BY_GRAMMAR:
bEncodeUrl = bODF;
break;
case ScCompiler::ENCODE_ALWAYS:
bEncodeUrl = true;
break;
case ScCompiler::ENCODE_NEVER:
bEncodeUrl = false;
break;
default:
;
}
makeExternalSingleRefStr(rBuffer, nFileId, rTabName, aRef, pRefMgr, true, bEncodeUrl);
if (bODF)
rBuffer.append( sal_Unicode(']'));
}
virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
ScExternalRefManager* pRefMgr ) const
{
makeExternalRefStrImpl( rBuffer, rCompiler, nFileId, rTabName, rRef, pRefMgr, false);
}
void makeExternalRefStrImpl( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
ScExternalRefManager* pRefMgr, bool bODF ) const
{
ScComplexRefData aRef(rRef);
aRef.CalcAbsIfRel(rCompiler.GetPos());
if (bODF)
rBuffer.append( sal_Unicode('['));
// Ensure that there's always a closing bracket, no premature returns.
bool bEncodeUrl = true;
switch (rCompiler.GetEncodeUrlMode())
{
case ScCompiler::ENCODE_BY_GRAMMAR:
bEncodeUrl = bODF;
break;
case ScCompiler::ENCODE_ALWAYS:
bEncodeUrl = true;
break;
case ScCompiler::ENCODE_NEVER:
bEncodeUrl = false;
break;
default:
;
}
do
{
if (!makeExternalSingleRefStr(rBuffer, nFileId, rTabName, aRef.Ref1, pRefMgr, true, bEncodeUrl))
break;
rBuffer.append(sal_Unicode(':'));
OUString aLastTabName;
bool bDisplayTabName = (aRef.Ref1.nTab != aRef.Ref2.nTab);
if (bDisplayTabName)
{
// Get the name of the last table.
vector<OUString> aTabNames;
pRefMgr->getAllCachedTableNames(nFileId, aTabNames);
if (aTabNames.empty())
{
OSL_TRACE( "ConventionOOO_A1::makeExternalRefStrImpl: no sheet names for document ID %s", nFileId);
}
if (!lcl_getLastTabName(aLastTabName, rTabName, aTabNames, aRef))
{
OSL_FAIL( "ConventionOOO_A1::makeExternalRefStrImpl: sheet name not found");
// aLastTabName contains #REF!, proceed.
}
}
else if (bODF)
rBuffer.append( sal_Unicode('.')); // need at least the sheet separator in ODF
makeExternalSingleRefStr( rBuffer, nFileId, aLastTabName,
aRef.Ref2, pRefMgr, bDisplayTabName, bEncodeUrl);
} while (0);
if (bODF)
rBuffer.append( sal_Unicode(']'));
}
virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
ScExternalRefManager* pRefMgr ) const
{
makeExternalRefStrImpl( rBuffer, rCompiler, nFileId, rTabName, rRef, pRefMgr, false);
}
};
static const ConventionOOO_A1 ConvOOO_A1;
const ScCompiler::Convention * const ScCompiler::pConvOOO_A1 = &ConvOOO_A1;
//-----------------------------------------------------------------------------
struct ConventionOOO_A1_ODF : public ConventionOOO_A1
{
ConventionOOO_A1_ODF() : ConventionOOO_A1 (FormulaGrammar::CONV_ODF) { }
void MakeRefStr( rtl::OUStringBuffer& rBuffer,
const ScCompiler& rComp,
const ScComplexRefData& rRef,
bool bSingleRef ) const
{
MakeRefStrImpl( rBuffer, rComp, rRef, bSingleRef, true);
}
virtual String makeExternalNameStr( const String& rFile, const String& rName ) const
{
return lcl_makeExternalNameStr( rFile, rName, sal_Unicode('#'), true);
}
virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
ScExternalRefManager* pRefMgr ) const
{
makeExternalRefStrImpl( rBuffer, rCompiler, nFileId, rTabName, rRef, pRefMgr, true);
}
virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
ScExternalRefManager* pRefMgr ) const
{
makeExternalRefStrImpl( rBuffer, rCompiler, nFileId, rTabName, rRef, pRefMgr, true);
}
};
static const ConventionOOO_A1_ODF ConvOOO_A1_ODF;
const ScCompiler::Convention * const ScCompiler::pConvOOO_A1_ODF = &ConvOOO_A1_ODF;
//-----------------------------------------------------------------------------
struct ConventionXL
{
static bool GetDocAndTab( const ScCompiler& rComp,
const ScSingleRefData& rRef,
String& rDocName,
String& rTabName )
{
bool bHasDoc = false;
rDocName.Erase();
rtl::OUString aTmp;
if (rRef.IsTabDeleted() ||
!rComp.GetDoc()->GetName( rRef.nTab, aTmp ))
{
rTabName = ScGlobal::GetRscString( STR_NO_REF_TABLE );
return false;
}
rTabName = aTmp;
// Cheesy hack to unparse the OOO style "'Doc'#Tab"
if ( rTabName.GetChar(0) == '\'' )
{
xub_StrLen nPos = ScGlobal::FindUnquoted( rTabName, SC_COMPILER_FILE_TAB_SEP);
if (nPos != STRING_NOTFOUND && nPos > 0 && rTabName.GetChar(nPos-1) == '\'')
{
rDocName = rTabName.Copy( 0, nPos );
// TODO : More research into how XL escapes the doc path
rDocName = INetURLObject::decode( rDocName, INET_HEX_ESCAPE,
INetURLObject::DECODE_UNAMBIGUOUS );
rTabName.Erase( 0, nPos + 1 );
bHasDoc = true;
}
}
// XL uses the same sheet name quoting conventions in both modes
// it is safe to use A1 here
ScCompiler::CheckTabQuotes( rTabName, FormulaGrammar::CONV_XL_A1 );
return bHasDoc;
}
static void MakeDocStr( rtl::OUStringBuffer& rBuf,
const ScCompiler& rComp,
const ScComplexRefData& rRef,
bool bSingleRef )
{
if( rRef.Ref1.IsFlag3D() )
{
String aStartTabName, aStartDocName, aEndTabName, aEndDocName;
bool bStartHasDoc = false, bEndHasDoc = false;
bStartHasDoc = GetDocAndTab( rComp, rRef.Ref1,
aStartDocName, aStartTabName);
if( !bSingleRef && rRef.Ref2.IsFlag3D() )
{
bEndHasDoc = GetDocAndTab( rComp, rRef.Ref2,
aEndDocName, aEndTabName);
}
else
bEndHasDoc = bStartHasDoc;
if( bStartHasDoc )
{
// A ref across multipled workbooks ?
if( !bEndHasDoc )
return;
rBuf.append( sal_Unicode( '[' ) );
rBuf.append( aStartDocName );
rBuf.append( sal_Unicode( ']' ) );
}
rBuf.append( aStartTabName );
if( !bSingleRef && rRef.Ref2.IsFlag3D() && aStartTabName != aEndTabName )
{
rBuf.append( sal_Unicode( ':' ) );
rBuf.append( aEndTabName );
}
rBuf.append( sal_Unicode( '!' ) );
}
}
static sal_Unicode getSpecialSymbol( ScCompiler::Convention::SpecialSymbolType eSymType )
{
switch (eSymType)
{
case ScCompiler::Convention::ABS_SHEET_PREFIX:
return sal_Unicode(0);
case ScCompiler::Convention::SHEET_SEPARATOR:
return '!';
}
return sal_Unicode(0);
}
static bool parseExternalName( const String& rSymbol, String& rFile, String& rName,
const ScDocument* pDoc,
const ::com::sun::star::uno::Sequence<
const ::com::sun::star::sheet::ExternalLinkInfo > * pExternalLinks )
{
return lcl_parseExternalName( rSymbol, rFile, rName, sal_Unicode('!'), pDoc, pExternalLinks);
}
static String makeExternalNameStr( const String& rFile, const String& rName )
{
return lcl_makeExternalNameStr( rFile, rName, sal_Unicode('!'), false);
}
static void makeExternalDocStr( ::rtl::OUStringBuffer& rBuffer, const String& rFullName, bool bEncodeUrl )
{
// Format that is easier to deal with inside OOo, because we use file
// URL, and all characetrs are allowed. Check if it makes sense to do
// it the way Gnumeric does it. Gnumeric doesn't use the URL form
// and allows relative file path.
//
// ['file:///path/to/source/filename.xls']
rBuffer.append(sal_Unicode('['));
rBuffer.append(sal_Unicode('\''));
String aFullName;
if (bEncodeUrl)
aFullName = rFullName;
else
aFullName = INetURLObject::decode(rFullName, INET_HEX_ESCAPE, INetURLObject::DECODE_UNAMBIGUOUS);
const sal_Unicode* pBuf = aFullName.GetBuffer();
xub_StrLen nLen = aFullName.Len();
for (xub_StrLen i = 0; i < nLen; ++i)
{
const sal_Unicode c = pBuf[i];
if (c == sal_Unicode('\''))
rBuffer.append(c);
rBuffer.append(c);
}
rBuffer.append(sal_Unicode('\''));
rBuffer.append(sal_Unicode(']'));
}
static void makeExternalTabNameRange( ::rtl::OUStringBuffer& rBuf, const OUString& rTabName,
const vector<OUString>& rTabNames,
const ScComplexRefData& rRef )
{
OUString aLastTabName;
if (!lcl_getLastTabName(aLastTabName, rTabName, rTabNames, rRef))
{
ScRangeStringConverter::AppendTableName(rBuf, aLastTabName);
return;
}
ScRangeStringConverter::AppendTableName(rBuf, rTabName);
if (rTabName != aLastTabName)
{
rBuf.append(sal_Unicode(':'));
ScRangeStringConverter::AppendTableName(rBuf, rTabName);
}
}
static void parseExternalDocName( const String& rFormula, xub_StrLen& rSrcPos )
{
xub_StrLen nLen = rFormula.Len();
const sal_Unicode* p = rFormula.GetBuffer();
sal_Unicode cPrev = 0;
for (xub_StrLen i = rSrcPos; i < nLen; ++i)
{
sal_Unicode c = p[i];
if (i == rSrcPos)
{
// first character must be '['.
if (c != '[')
return;
}
else if (i == rSrcPos + 1)
{
// second character must be a single quote.
if (c != '\'')
return;
}
else if (c == '\'')
{
if (cPrev == '\'')
// two successive single quote is treated as a single
// valid character.
c = 'a';
}
else if (c == ']')
{
if (cPrev == '\'')
{
// valid source document path found. Increment the
// current position to skip the source path.
rSrcPos = i + 1;
if (rSrcPos >= nLen)
rSrcPos = nLen - 1;
return;
}
else
return;
}
else
{
// any other character
if (i > rSrcPos + 2 && cPrev == '\'')
// unless it's the 3rd character, a normal character
// following immediately a single quote is invalid.
return;
}
cPrev = c;
}
}
};
struct ConventionXL_A1 : public Convention_A1, public ConventionXL
{
ConventionXL_A1() : Convention_A1( FormulaGrammar::CONV_XL_A1 ) { }
ConventionXL_A1( FormulaGrammar::AddressConvention eConv ) : Convention_A1( eConv ) { }
void makeSingleCellStr( ::rtl::OUStringBuffer& rBuf, const ScSingleRefData& rRef ) const
{
if (!rRef.IsColRel())
rBuf.append(sal_Unicode('$'));
MakeColStr(rBuf, rRef.nCol);
if (!rRef.IsRowRel())
rBuf.append(sal_Unicode('$'));
MakeRowStr(rBuf, rRef.nRow);
}
void MakeRefStr( rtl::OUStringBuffer& rBuf,
const ScCompiler& rComp,
const ScComplexRefData& rRef,
bool bSingleRef ) const
{
ScComplexRefData aRef( rRef );
// Play fast and loose with invalid refs. There is not much point in producing
// Foo!A1:#REF! versus #REF! at this point
aRef.Ref1.CalcAbsIfRel( rComp.GetPos() );
MakeDocStr( rBuf, rComp, aRef, bSingleRef );
if( aRef.Ref1.IsColDeleted() || aRef.Ref1.IsRowDeleted() )
{
rBuf.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
return;
}
if( !bSingleRef )
{
aRef.Ref2.CalcAbsIfRel( rComp.GetPos() );
if( aRef.Ref2.IsColDeleted() || aRef.Ref2.IsRowDeleted() )
{
rBuf.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
return;
}
if( aRef.Ref1.nCol == 0 && aRef.Ref2.nCol >= MAXCOL )
{
if (!aRef.Ref1.IsRowRel())
rBuf.append(sal_Unicode( '$' ));
MakeRowStr( rBuf, aRef.Ref1.nRow );
rBuf.append(sal_Unicode( ':' ));
if (!aRef.Ref2.IsRowRel())
rBuf.append(sal_Unicode( '$' ));
MakeRowStr( rBuf, aRef.Ref2.nRow );
return;
}
if( aRef.Ref1.nRow == 0 && aRef.Ref2.nRow >= MAXROW )
{
if (!aRef.Ref1.IsColRel())
rBuf.append(sal_Unicode( '$' ));
MakeColStr(rBuf, aRef.Ref1.nCol );
rBuf.append(sal_Unicode( ':' ));
if (!aRef.Ref2.IsColRel())
rBuf.append(sal_Unicode( '$' ));
MakeColStr(rBuf, aRef.Ref2.nCol );
return;
}
}
makeSingleCellStr(rBuf, aRef.Ref1);
if (!bSingleRef)
{
rBuf.append(sal_Unicode( ':' ));
makeSingleCellStr(rBuf, aRef.Ref2);
}
}
virtual ParseResult parseAnyToken( const String& rFormula,
xub_StrLen nSrcPos,
const CharClass* pCharClass) const
{
ParseResult aRet;
if ( lcl_isValidQuotedText(rFormula, nSrcPos, aRet) )
return aRet;
static const sal_Int32 nStartFlags = KParseTokens::ANY_LETTER_OR_NUMBER |
KParseTokens::ASC_UNDERSCORE | KParseTokens::ASC_DOLLAR;
static const sal_Int32 nContFlags = nStartFlags | KParseTokens::ASC_DOT;
// '?' allowed in range names
static const String aAddAllowed = String::CreateFromAscii("?!");
return pCharClass->parseAnyToken( rFormula,
nSrcPos, nStartFlags, aAddAllowed, nContFlags, aAddAllowed );
}
virtual sal_Unicode getSpecialSymbol( SpecialSymbolType eSymType ) const
{
return ConventionXL::getSpecialSymbol(eSymType);
}
virtual bool parseExternalName( const String& rSymbol, String& rFile, String& rName,
const ScDocument* pDoc,
const ::com::sun::star::uno::Sequence<
const ::com::sun::star::sheet::ExternalLinkInfo > * pExternalLinks ) const
{
return ConventionXL::parseExternalName( rSymbol, rFile, rName, pDoc, pExternalLinks);
}
virtual String makeExternalNameStr( const String& rFile, const String& rName ) const
{
return ConventionXL::makeExternalNameStr(rFile, rName);
}
virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
ScExternalRefManager* pRefMgr ) const
{
// ['file:///path/to/file/filename.xls']'Sheet Name'!$A$1
// This is a little different from the format Excel uses, as Excel
// puts [] only around the file name. But we need to enclose the
// whole file path with [] because the file name can contain any
// characters.
const OUString* pFullName = pRefMgr->getExternalFileName(nFileId);
if (!pFullName)
return;
ScSingleRefData aRef(rRef);
aRef.CalcAbsIfRel(rCompiler.GetPos());
ConventionXL::makeExternalDocStr(
rBuffer, *pFullName, rCompiler.GetEncodeUrlMode() == ScCompiler::ENCODE_ALWAYS);
ScRangeStringConverter::AppendTableName(rBuffer, rTabName);
rBuffer.append(sal_Unicode('!'));
makeSingleCellStr(rBuffer, aRef);
}
virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
ScExternalRefManager* pRefMgr ) const
{
const OUString* pFullName = pRefMgr->getExternalFileName(nFileId);
if (!pFullName)
return;
vector<OUString> aTabNames;
pRefMgr->getAllCachedTableNames(nFileId, aTabNames);
if (aTabNames.empty())
return;
ScComplexRefData aRef(rRef);
aRef.CalcAbsIfRel(rCompiler.GetPos());
ConventionXL::makeExternalDocStr(
rBuffer, *pFullName, rCompiler.GetEncodeUrlMode() == ScCompiler::ENCODE_ALWAYS);
ConventionXL::makeExternalTabNameRange(rBuffer, rTabName, aTabNames, aRef);
rBuffer.append(sal_Unicode('!'));
makeSingleCellStr(rBuffer, aRef.Ref1);
if (aRef.Ref1 != aRef.Ref2)
{
rBuffer.append(sal_Unicode(':'));
makeSingleCellStr(rBuffer, aRef.Ref2);
}
}
};
static const ConventionXL_A1 ConvXL_A1;
const ScCompiler::Convention * const ScCompiler::pConvXL_A1 = &ConvXL_A1;
struct ConventionXL_OOX : public ConventionXL_A1
{
ConventionXL_OOX() : ConventionXL_A1( FormulaGrammar::CONV_XL_OOX ) { }
};
static const ConventionXL_OOX ConvXL_OOX;
const ScCompiler::Convention * const ScCompiler::pConvXL_OOX = &ConvXL_OOX;
//-----------------------------------------------------------------------------
static void
r1c1_add_col( rtl::OUStringBuffer &rBuf, const ScSingleRefData& rRef )
{
rBuf.append( sal_Unicode( 'C' ) );
if( rRef.IsColRel() )
{
if (rRef.nRelCol != 0)
{
rBuf.append( sal_Unicode( '[' ) );
rBuf.append( String::CreateFromInt32( rRef.nRelCol ) );
rBuf.append( sal_Unicode( ']' ) );
}
}
else
rBuf.append( String::CreateFromInt32( rRef.nCol + 1 ) );
}
static void
r1c1_add_row( rtl::OUStringBuffer &rBuf, const ScSingleRefData& rRef )
{
rBuf.append( sal_Unicode( 'R' ) );
if( rRef.IsRowRel() )
{
if (rRef.nRelRow != 0)
{
rBuf.append( sal_Unicode( '[' ) );
rBuf.append( String::CreateFromInt32( rRef.nRelRow ) );
rBuf.append( sal_Unicode( ']' ) );
}
}
else
rBuf.append( String::CreateFromInt32( rRef.nRow + 1 ) );
}
struct ConventionXL_R1C1 : public ScCompiler::Convention, public ConventionXL
{
ConventionXL_R1C1() : ScCompiler::Convention( FormulaGrammar::CONV_XL_R1C1 ) { }
void MakeRefStr( rtl::OUStringBuffer& rBuf,
const ScCompiler& rComp,
const ScComplexRefData& rRef,
bool bSingleRef ) const
{
ScComplexRefData aRef( rRef );
MakeDocStr( rBuf, rComp, aRef, bSingleRef );
// Play fast and loose with invalid refs. There is not much point in producing
// Foo!A1:#REF! versus #REF! at this point
aRef.Ref1.CalcAbsIfRel( rComp.GetPos() );
if( aRef.Ref1.IsColDeleted() || aRef.Ref1.IsRowDeleted() )
{
rBuf.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
return;
}
if( !bSingleRef )
{
aRef.Ref2.CalcAbsIfRel( rComp.GetPos() );
if( aRef.Ref2.IsColDeleted() || aRef.Ref2.IsRowDeleted() )
{
rBuf.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
return;
}
if( aRef.Ref1.nCol == 0 && aRef.Ref2.nCol >= MAXCOL )
{
r1c1_add_row( rBuf, rRef.Ref1 );
if( rRef.Ref1.nRow != rRef.Ref2.nRow ||
rRef.Ref1.IsRowRel() != rRef.Ref2.IsRowRel() ) {
rBuf.append (sal_Unicode ( ':' ) );
r1c1_add_row( rBuf, rRef.Ref2 );
}
return;
}
if( aRef.Ref1.nRow == 0 && aRef.Ref2.nRow >= MAXROW )
{
r1c1_add_col( rBuf, rRef.Ref1 );
if( rRef.Ref1.nCol != rRef.Ref2.nCol ||
rRef.Ref1.IsColRel() != rRef.Ref2.IsColRel() )
{
rBuf.append (sal_Unicode ( ':' ) );
r1c1_add_col( rBuf, rRef.Ref2 );
}
return;
}
}
r1c1_add_row( rBuf, rRef.Ref1 );
r1c1_add_col( rBuf, rRef.Ref1 );
if (!bSingleRef)
{
rBuf.append (sal_Unicode ( ':' ) );
r1c1_add_row( rBuf, rRef.Ref2 );
r1c1_add_col( rBuf, rRef.Ref2 );
}
}
ParseResult parseAnyToken( const String& rFormula,
xub_StrLen nSrcPos,
const CharClass* pCharClass) const
{
ConventionXL::parseExternalDocName(rFormula, nSrcPos);
ParseResult aRet;
if ( lcl_isValidQuotedText(rFormula, nSrcPos, aRet) )
return aRet;
static const sal_Int32 nStartFlags = KParseTokens::ANY_LETTER_OR_NUMBER |
KParseTokens::ASC_UNDERSCORE ;
static const sal_Int32 nContFlags = nStartFlags | KParseTokens::ASC_DOT;
// '?' allowed in range names
static const String aAddAllowed = String::CreateFromAscii( "?-[]!" );
return pCharClass->parseAnyToken( rFormula,
nSrcPos, nStartFlags, aAddAllowed, nContFlags, aAddAllowed );
}
virtual sal_Unicode getSpecialSymbol( SpecialSymbolType eSymType ) const
{
return ConventionXL::getSpecialSymbol(eSymType);
}
virtual bool parseExternalName( const String& rSymbol, String& rFile, String& rName,
const ScDocument* pDoc,
const ::com::sun::star::uno::Sequence<
const ::com::sun::star::sheet::ExternalLinkInfo > * pExternalLinks ) const
{
return ConventionXL::parseExternalName( rSymbol, rFile, rName, pDoc, pExternalLinks);
}
virtual String makeExternalNameStr( const String& rFile, const String& rName ) const
{
return ConventionXL::makeExternalNameStr(rFile, rName);
}
virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScSingleRefData& rRef,
ScExternalRefManager* pRefMgr ) const
{
// ['file:///path/to/file/filename.xls']'Sheet Name'!$A$1
// This is a little different from the format Excel uses, as Excel
// puts [] only around the file name. But we need to enclose the
// whole file path with [] because the file name can contain any
// characters.
const OUString* pFullName = pRefMgr->getExternalFileName(nFileId);
if (!pFullName)
return;
ScSingleRefData aRef(rRef);
aRef.CalcAbsIfRel(rCompiler.GetPos());
ConventionXL::makeExternalDocStr(
rBuffer, *pFullName, rCompiler.GetEncodeUrlMode() == ScCompiler::ENCODE_ALWAYS);
ScRangeStringConverter::AppendTableName(rBuffer, rTabName);
rBuffer.append(sal_Unicode('!'));
r1c1_add_row(rBuffer, aRef);
r1c1_add_col(rBuffer, aRef);
}
virtual void makeExternalRefStr( ::rtl::OUStringBuffer& rBuffer, const ScCompiler& rCompiler,
sal_uInt16 nFileId, const String& rTabName, const ScComplexRefData& rRef,
ScExternalRefManager* pRefMgr ) const
{
const OUString* pFullName = pRefMgr->getExternalFileName(nFileId);
if (!pFullName)
return;
vector<OUString> aTabNames;
pRefMgr->getAllCachedTableNames(nFileId, aTabNames);
if (aTabNames.empty())
return;
ScComplexRefData aRef(rRef);
aRef.CalcAbsIfRel(rCompiler.GetPos());
ConventionXL::makeExternalDocStr(
rBuffer, *pFullName, rCompiler.GetEncodeUrlMode() == ScCompiler::ENCODE_ALWAYS);
ConventionXL::makeExternalTabNameRange(rBuffer, rTabName, aTabNames, aRef);
rBuffer.append(sal_Unicode('!'));
if (aRef.Ref2.IsColDeleted() || aRef.Ref2.IsRowDeleted())
{
rBuffer.append(ScGlobal::GetRscString(STR_NO_REF_TABLE));
return;
}
if (aRef.Ref1.nCol == 0 && aRef.Ref2.nCol >= MAXCOL)
{
r1c1_add_row(rBuffer, rRef.Ref1);
if (rRef.Ref1.nRow != rRef.Ref2.nRow || rRef.Ref1.IsRowRel() != rRef.Ref2.IsRowRel())
{
rBuffer.append (sal_Unicode(':'));
r1c1_add_row(rBuffer, rRef.Ref2);
}
return;
}
if (aRef.Ref1.nRow == 0 && aRef.Ref2.nRow >= MAXROW)
{
r1c1_add_col(rBuffer, aRef.Ref1);
if (aRef.Ref1.nCol != aRef.Ref2.nCol || aRef.Ref1.IsColRel() != aRef.Ref2.IsColRel())
{
rBuffer.append (sal_Unicode(':'));
r1c1_add_col(rBuffer, aRef.Ref2);
}
return;
}
r1c1_add_row(rBuffer, aRef.Ref1);
r1c1_add_col(rBuffer, aRef.Ref1);
rBuffer.append (sal_Unicode (':'));
r1c1_add_row(rBuffer, aRef.Ref2);
r1c1_add_col(rBuffer, aRef.Ref2);
}
virtual sal_uLong getCharTableFlags( sal_Unicode c, sal_Unicode cLast ) const
{
sal_uLong nFlags = mpCharTable[static_cast<sal_uInt8>(c)];
if (c == '-' && cLast == '[')
// '-' can occur within a reference string only after '[' e.g. R[-1]C.
nFlags |= SC_COMPILER_C_IDENT;
return nFlags;
}
};
static const ConventionXL_R1C1 ConvXL_R1C1;
const ScCompiler::Convention * const ScCompiler::pConvXL_R1C1 = &ConvXL_R1C1;
//-----------------------------------------------------------------------------
ScCompiler::ScCompiler( ScDocument* pDocument, const ScAddress& rPos,ScTokenArray& rArr)
: FormulaCompiler(rArr),
pDoc( pDocument ),
aPos( rPos ),
pCharClass( ScGlobal::pCharClass ),
mnPredetectedReference(0),
mnRangeOpPosInSymbol(-1),
pConv( pConvOOO_A1 ),
meEncodeUrlMode( ENCODE_BY_GRAMMAR ),
meExtendedErrorDetection( EXTENDED_ERROR_DETECTION_NONE ),
mbCloseBrackets( true ),
mbRewind( false )
{
nMaxTab = pDoc ? pDoc->GetTableCount() - 1 : 0;
}
ScCompiler::ScCompiler( ScDocument* pDocument, const ScAddress& rPos)
:
pDoc( pDocument ),
aPos( rPos ),
pCharClass( ScGlobal::pCharClass ),
mnPredetectedReference(0),
mnRangeOpPosInSymbol(-1),
pConv( pConvOOO_A1 ),
meEncodeUrlMode( ENCODE_BY_GRAMMAR ),
meExtendedErrorDetection( EXTENDED_ERROR_DETECTION_NONE ),
mbCloseBrackets( true ),
mbRewind( false )
{
nMaxTab = pDoc ? pDoc->GetTableCount() - 1 : 0;
}
void ScCompiler::CheckTabQuotes( String& rString,
const FormulaGrammar::AddressConvention eConv )
{
using namespace ::com::sun::star::i18n;
sal_Int32 nStartFlags = KParseTokens::ANY_LETTER_OR_NUMBER | KParseTokens::ASC_UNDERSCORE;
sal_Int32 nContFlags = nStartFlags;
ParseResult aRes = ScGlobal::pCharClass->parsePredefinedToken(
KParseType::IDENTNAME, rString, 0, nStartFlags, EMPTY_STRING, nContFlags, EMPTY_STRING);
bool bNeedsQuote = !((aRes.TokenType & KParseType::IDENTNAME) && aRes.EndPos == rString.Len());
switch ( eConv )
{
default :
case FormulaGrammar::CONV_UNSPECIFIED :
break;
case FormulaGrammar::CONV_OOO :
case FormulaGrammar::CONV_XL_A1 :
case FormulaGrammar::CONV_XL_R1C1 :
case FormulaGrammar::CONV_XL_OOX :
if( bNeedsQuote )
{
static const String one_quote = static_cast<sal_Unicode>( '\'' );
static const String two_quote = String::CreateFromAscii( "''" );
// escape embedded quotes
rString.SearchAndReplaceAll( one_quote, two_quote );
}
break;
}
if ( !bNeedsQuote && CharClass::isAsciiNumeric( rString ) )
{
// Prevent any possible confusion resulting from pure numeric sheet names.
bNeedsQuote = true;
}
if( bNeedsQuote )
{
rString.Insert( '\'', 0 );
rString += '\'';
}
}
//---------------------------------------------------------------------------
void ScCompiler::SetRefConvention( FormulaGrammar::AddressConvention eConv )
{
switch ( eConv ) {
case FormulaGrammar::CONV_UNSPECIFIED :
break;
default :
case FormulaGrammar::CONV_OOO : SetRefConvention( pConvOOO_A1 ); break;
case FormulaGrammar::CONV_ODF : SetRefConvention( pConvOOO_A1_ODF ); break;
case FormulaGrammar::CONV_XL_A1 : SetRefConvention( pConvXL_A1 ); break;
case FormulaGrammar::CONV_XL_R1C1 : SetRefConvention( pConvXL_R1C1 ); break;
case FormulaGrammar::CONV_XL_OOX : SetRefConvention( pConvXL_OOX ); break;
}
}
void ScCompiler::SetRefConvention( const ScCompiler::Convention *pConvP )
{
pConv = pConvP;
meGrammar = FormulaGrammar::mergeToGrammar( meGrammar, pConv->meConv);
OSL_ENSURE( FormulaGrammar::isSupported( meGrammar),
"ScCompiler::SetRefConvention: unsupported grammar resulting");
}
void ScCompiler::SetError(sal_uInt16 nError)
{
if( !pArr->GetCodeError() )
pArr->SetCodeError( nError);
}
sal_Unicode* lcl_UnicodeStrNCpy( sal_Unicode* pDst, const sal_Unicode* pSrc, xub_StrLen nMax )
{
const sal_Unicode* const pStop = pDst + nMax;
while ( *pSrc && pDst < pStop )
{
*pDst++ = *pSrc++;
}
*pDst = 0;
return pDst;
}
//---------------------------------------------------------------------------
// NextSymbol
//---------------------------------------------------------------------------
// Zerlegt die Formel in einzelne Symbole fuer die weitere
// Verarbeitung (Turing-Maschine).
//---------------------------------------------------------------------------
// Ausgangs Zustand = GetChar
//---------------+-------------------+-----------------------+---------------
// Alter Zustand | gelesenes Zeichen | Aktion | Neuer Zustand
//---------------+-------------------+-----------------------+---------------
// GetChar | ;()+-*/^=& | Symbol=Zeichen | Stop
// | <> | Symbol=Zeichen | GetBool
// | $ Buchstabe | Symbol=Zeichen | GetWord
// | Ziffer | Symbol=Zeichen | GetValue
// | " | Keine | GetString
// | Sonst | Keine | GetChar
//---------------+-------------------+-----------------------+---------------
// GetBool | => | Symbol=Symbol+Zeichen | Stop
// | Sonst | Dec(CharPos) | Stop
//---------------+-------------------+-----------------------+---------------
// GetWord | SepSymbol | Dec(CharPos) | Stop
// | ()+-*/^=<>&~ | |
// | Leerzeichen | Dec(CharPos) | Stop
// | $_:. | |
// | Buchstabe,Ziffer | Symbol=Symbol+Zeichen | GetWord
// | Sonst | Fehler | Stop
//---------------|-------------------+-----------------------+---------------
// GetValue | ;()*/^=<>& | |
// | Leerzeichen | Dec(CharPos) | Stop
// | Ziffer E+-%,. | Symbol=Symbol+Zeichen | GetValue
// | Sonst | Fehler | Stop
//---------------+-------------------+-----------------------+---------------
// GetString | " | Keine | Stop
// | Sonst | Symbol=Symbol+Zeichen | GetString
//---------------+-------------------+-----------------------+---------------
xub_StrLen ScCompiler::NextSymbol(bool bInArray)
{
cSymbol[MAXSTRLEN-1] = 0; // Stopper
sal_Unicode* pSym = cSymbol;
const sal_Unicode* const pStart = aFormula.GetBuffer();
const sal_Unicode* pSrc = pStart + nSrcPos;
bool bi18n = false;
sal_Unicode c = *pSrc;
sal_Unicode cLast = 0;
bool bQuote = false;
mnRangeOpPosInSymbol = -1;
ScanState eState = ssGetChar;
xub_StrLen nSpaces = 0;
sal_Unicode cSep = mxSymbols->getSymbol( ocSep).GetChar(0);
sal_Unicode cArrayColSep = mxSymbols->getSymbol( ocArrayColSep).GetChar(0);
sal_Unicode cArrayRowSep = mxSymbols->getSymbol( ocArrayRowSep).GetChar(0);
sal_Unicode cDecSep = (mxSymbols->isEnglish() ? '.' :
ScGlobal::pLocaleData->getNumDecimalSep().GetChar(0));
// special symbols specific to address convention used
sal_Unicode cSheetPrefix = pConv->getSpecialSymbol(ScCompiler::Convention::ABS_SHEET_PREFIX);
sal_Unicode cSheetSep = pConv->getSpecialSymbol(ScCompiler::Convention::SHEET_SEPARATOR);
int nDecSeps = 0;
bool bAutoIntersection = false;
int nRefInName = 0;
bool bErrorConstantHadSlash = false;
mnPredetectedReference = 0;
// try to parse simple tokens before calling i18n parser
while ((c != 0) && (eState != ssStop) )
{
pSrc++;
sal_uLong nMask = GetCharTableFlags( c, cLast );
// The parameter separator and the array column and row separators end
// things unconditionally if not in string or reference.
if (c == cSep || (bInArray && (c == cArrayColSep || c == cArrayRowSep)))
{
switch (eState)
{
// these are to be continued
case ssGetString:
case ssSkipString:
case ssGetReference:
case ssSkipReference:
break;
default:
if (eState == ssGetChar)
*pSym++ = c;
else
pSrc--;
eState = ssStop;
}
}
Label_MaskStateMachine:
switch (eState)
{
case ssGetChar :
{
// Order is important!
if( nMask & SC_COMPILER_C_ODF_LABEL_OP )
{
// '!!' automatic intersection
if (GetCharTableFlags( pSrc[0], 0 ) & SC_COMPILER_C_ODF_LABEL_OP)
{
/* TODO: For now the UI "space operator" is used, this
* could be enhanced using a specialized OpCode to get
* rid of the space ambiguity, which would need some
* places to be adapted though. And we would still need
* to support the ambiguous space operator for UI
* purposes anyway. However, we then could check for
* invalid usage of '!!', which currently isn't
* possible. */
if (!bAutoIntersection)
{
++pSrc;
nSpaces += 2; // must match the character count
bAutoIntersection = true;
}
else
{
pSrc--;
eState = ssStop;
}
}
else
{
nMask &= ~SC_COMPILER_C_ODF_LABEL_OP;
goto Label_MaskStateMachine;
}
}
else if( nMask & SC_COMPILER_C_ODF_NAME_MARKER )
{
// '$$' defined name marker
if (GetCharTableFlags( pSrc[0], 0 ) & SC_COMPILER_C_ODF_NAME_MARKER)
{
// both eaten, not added to pSym
++pSrc;
}
else
{
nMask &= ~SC_COMPILER_C_ODF_NAME_MARKER;
goto Label_MaskStateMachine;
}
}
else if( nMask & SC_COMPILER_C_CHAR )
{
*pSym++ = c;
eState = ssStop;
}
else if( nMask & SC_COMPILER_C_ODF_LBRACKET )
{
// eaten, not added to pSym
eState = ssGetReference;
mnPredetectedReference = 1;
}
else if( nMask & SC_COMPILER_C_CHAR_BOOL )
{
*pSym++ = c;
eState = ssGetBool;
}
else if( nMask & SC_COMPILER_C_CHAR_VALUE )
{
*pSym++ = c;
eState = ssGetValue;
}
else if( nMask & SC_COMPILER_C_CHAR_STRING )
{
*pSym++ = c;
eState = ssGetString;
}
else if( nMask & SC_COMPILER_C_CHAR_ERRCONST )
{
*pSym++ = c;
eState = ssGetErrorConstant;
}
else if( nMask & SC_COMPILER_C_CHAR_DONTCARE )
{
nSpaces++;
}
else if( nMask & SC_COMPILER_C_CHAR_IDENT )
{ // try to get a simple ASCII identifier before calling
// i18n, to gain performance during import
*pSym++ = c;
eState = ssGetIdent;
}
else
{
bi18n = true;
eState = ssStop;
}
}
break;
case ssGetIdent:
{
if ( nMask & SC_COMPILER_C_IDENT )
{ // This catches also $Sheet1.A$1, for example.
if( pSym == &cSymbol[ MAXSTRLEN-1 ] )
{
SetError(errStringOverflow);
eState = ssStop;
}
else
*pSym++ = c;
}
else if (c == ':' && mnRangeOpPosInSymbol < 0)
{
// One range operator may form Sheet1.A:A, which we need to
// pass as one entity to IsReference().
mnRangeOpPosInSymbol = pSym - &cSymbol[0];
if( pSym == &cSymbol[ MAXSTRLEN-1 ] )
{
SetError(errStringOverflow);
eState = ssStop;
}
else
*pSym++ = c;
}
else if ( 128 <= c || '\'' == c )
{ // High values need reparsing with i18n,
// single quoted $'sheet' names too (otherwise we'd had to
// implement everything twice).
bi18n = true;
eState = ssStop;
}
else
{
pSrc--;
eState = ssStop;
}
}
break;
case ssGetBool :
{
if( nMask & SC_COMPILER_C_BOOL )
{
*pSym++ = c;
eState = ssStop;
}
else
{
pSrc--;
eState = ssStop;
}
}
break;
case ssGetValue :
{
if( pSym == &cSymbol[ MAXSTRLEN-1 ] )
{
SetError(errStringOverflow);
eState = ssStop;
}
else if (c == cDecSep)
{
if (++nDecSeps > 1)
{
// reparse with i18n, may be numeric sheet name as well
bi18n = true;
eState = ssStop;
}
else
*pSym++ = c;
}
else if( nMask & SC_COMPILER_C_VALUE )
*pSym++ = c;
else if( nMask & SC_COMPILER_C_VALUE_SEP )
{
pSrc--;
eState = ssStop;
}
else if (c == 'E' || c == 'e')
{
if (GetCharTableFlags( pSrc[0], 0 ) & SC_COMPILER_C_VALUE_EXP)
*pSym++ = c;
else
{
// reparse with i18n
bi18n = true;
eState = ssStop;
}
}
else if( nMask & SC_COMPILER_C_VALUE_SIGN )
{
if (((cLast == 'E') || (cLast == 'e')) &&
(GetCharTableFlags( pSrc[0], 0 ) & SC_COMPILER_C_VALUE_VALUE))
{
*pSym++ = c;
}
else
{
pSrc--;
eState = ssStop;
}
}
else
{
// reparse with i18n
bi18n = true;
eState = ssStop;
}
}
break;
case ssGetString :
{
if( nMask & SC_COMPILER_C_STRING_SEP )
{
if ( !bQuote )
{
if ( *pSrc == '"' )
bQuote = true; // "" => literal "
else
eState = ssStop;
}
else
bQuote = false;
}
if ( !bQuote )
{
if( pSym == &cSymbol[ MAXSTRLEN-1 ] )
{
SetError(errStringOverflow);
eState = ssSkipString;
}
else
*pSym++ = c;
}
}
break;
case ssSkipString:
if( nMask & SC_COMPILER_C_STRING_SEP )
eState = ssStop;
break;
case ssGetErrorConstant:
{
// ODFF Error ::= '#' [A-Z0-9]+ ([!?] | ('/' ([A-Z] | ([0-9] [!?]))))
// BUT, in UI these may have been translated! So don't
// check for ASCII alnum. Note that this construct can't be
// parsed with i18n.
/* TODO: be strict when reading ODFF, check for ASCII alnum
* and proper continuation after '/'. However, even with
* the lax parsing only the error constants we have defined
* as opcode symbols will be recognized and others result
* in ocBad, so the result is actually conformant. */
bool bAdd = true;
if ('!' == c || '?' == c)
eState = ssStop;
else if ('/' == c)
{
if (!bErrorConstantHadSlash)
bErrorConstantHadSlash = true;
else
{
bAdd = false;
eState = ssStop;
}
}
else if ((nMask & SC_COMPILER_C_WORD_SEP) ||
(c < 128 && !CharClass::isAsciiAlphaNumeric( c)))
{
bAdd = false;
eState = ssStop;
}
if (!bAdd)
--pSrc;
else
{
if (pSym == &cSymbol[ MAXSTRLEN-1 ])
{
SetError( errStringOverflow);
eState = ssStop;
}
else
*pSym++ = c;
}
}
break;
case ssGetReference:
if( pSym == &cSymbol[ MAXSTRLEN-1 ] )
{
SetError( errStringOverflow);
eState = ssSkipReference;
}
// fall through and follow logic
case ssSkipReference:
// ODF reference: ['External'#$'Sheet'.A1:.B2] with dots being
// mandatory also if no sheet name. 'External'# is optional,
// sheet name is optional, quotes around sheet name are
// optional if no quote contained. [#REF!] is valid.
// 2nd usage: ['Sheet'.$$'DefinedName']
// 3rd usage: ['External'#$$'DefinedName']
// 4th usage: ['External'#$'Sheet'.$$'DefinedName']
// Also for all these names quotes are optional if no quote
// contained.
{
// nRefInName: 0 := not in sheet name yet. 'External'
// is parsed as if it was a sheet name and nRefInName
// is reset when # is encountered immediately after closing
// quote. Same with 'DefinedName', nRefInName is cleared
// when : is encountered.
// Encountered leading $ before sheet name.
static const int kDollar = (1 << 1);
// Encountered ' opening quote, which may be after $ or
// not.
static const int kOpen = (1 << 2);
// Somewhere in name.
static const int kName = (1 << 3);
// Encountered ' in name, will be cleared if double or
// transformed to kClose if not, in which case kOpen is
// cleared.
static const int kQuote = (1 << 4);
// Past ' closing quote.
static const int kClose = (1 << 5);
// Encountered # file/sheet separator.
static const int kFileSep = (1 << 6);
// Past . sheet name separator.
static const int kPast = (1 << 7);
// Marked name $$ follows sheet name separator, detected
// while we're still on the separator. Will be cleared when
// entering the name.
static const int kMarkAhead = (1 << 8);
// In marked defined name.
static const int kDefName = (1 << 9);
// Encountered # of #REF!
static const int kRefErr = (1 << 10);
bool bAddToSymbol = true;
if ((nMask & SC_COMPILER_C_ODF_RBRACKET) && !(nRefInName & kOpen))
{
OSL_ENSURE( nRefInName & (kPast | kDefName | kRefErr),
"ScCompiler::NextSymbol: reference: "
"closing bracket ']' without prior sheet name separator '.' violates ODF spec");
// eaten, not added to pSym
bAddToSymbol = false;
eState = ssStop;
}
else if (cSheetSep == c && nRefInName == 0)
{
// eat it, no sheet name [.A1]
bAddToSymbol = false;
nRefInName |= kPast;
if ('$' == pSrc[0] && '$' == pSrc[1])
nRefInName |= kMarkAhead;
}
else if (!(nRefInName & kPast) || (nRefInName & (kMarkAhead | kDefName)))
{
// Not in col/row yet.
if (SC_COMPILER_FILE_TAB_SEP == c && (nRefInName & kFileSep))
nRefInName = 0;
else if ('$' == c && '$' == pSrc[0] && !(nRefInName & kOpen))
{
nRefInName &= ~kMarkAhead;
if (!(nRefInName & kDefName))
{
// eaten, not added to pSym (2 chars)
bAddToSymbol = false;
++pSrc;
nRefInName &= kPast;
nRefInName |= kDefName;
}
else
{
// ScAddress::Parse() will recognize this as
// invalid later.
if (eState != ssSkipReference)
{
*pSym++ = c;
*pSym++ = *pSrc++;
}
bAddToSymbol = false;
}
}
else if (cSheetPrefix == c && nRefInName == 0)
nRefInName |= kDollar;
else if ('\'' == c)
{
// TODO: The conventions' parseExternalName()
// should handle quoted names, but as long as they
// don't remove non-embedded quotes here.
if (!(nRefInName & kName))
{
nRefInName |= (kOpen | kName);
bAddToSymbol = !(nRefInName & kDefName);
}
else if (!(nRefInName & kOpen))
{
OSL_FAIL("ScCompiler::NextSymbol: reference: "
"a ''' without the name being enclosed in '...' violates ODF spec");
}
else if (nRefInName & kQuote)
{
// escaped embedded quote
nRefInName &= ~kQuote;
}
else
{
switch (pSrc[0])
{
case '\'':
// escapes embedded quote
nRefInName |= kQuote;
break;
case SC_COMPILER_FILE_TAB_SEP:
// sheet name should follow
nRefInName |= kFileSep;
// fallthru
default:
// quote not followed by quote => close
nRefInName |= kClose;
nRefInName &= ~kOpen;
}
bAddToSymbol = !(nRefInName & kDefName);
}
}
else if ('#' == c && nRefInName == 0)
nRefInName |= kRefErr;
else if (cSheetSep == c && !(nRefInName & kOpen))
{
// unquoted sheet name separator
nRefInName |= kPast;
if ('$' == pSrc[0] && '$' == pSrc[1])
nRefInName |= kMarkAhead;
}
else if (':' == c && !(nRefInName & kOpen))
{
OSL_FAIL("ScCompiler::NextSymbol: reference: "
"range operator ':' without prior sheet name separator '.' violates ODF spec");
nRefInName = 0;
++mnPredetectedReference;
}
else if (!(nRefInName & kName))
{
// start unquoted name
nRefInName |= kName;
}
}
else if (':' == c)
{
// range operator
nRefInName = 0;
++mnPredetectedReference;
}
if (bAddToSymbol && eState != ssSkipReference)
*pSym++ = c; // everything is part of reference
}
break;
case ssStop:
; // nothing, prevent warning
break;
}
cLast = c;
c = *pSrc;
}
if ( bi18n )
{
nSrcPos = sal::static_int_cast<xub_StrLen>( nSrcPos + nSpaces );
String aSymbol;
mnRangeOpPosInSymbol = -1;
sal_uInt16 nErr = 0;
do
{
bi18n = false;
// special case (e.g. $'sheetname' in OOO A1)
if ( pStart[nSrcPos] == cSheetPrefix && pStart[nSrcPos+1] == '\'' )
aSymbol += pStart[nSrcPos++];
ParseResult aRes = pConv->parseAnyToken( aFormula, nSrcPos, pCharClass );
if ( !aRes.TokenType )
SetError( nErr = errIllegalChar ); // parsed chars as string
if ( aRes.EndPos <= nSrcPos )
{ // ?!?
SetError( nErr = errIllegalChar );
nSrcPos = aFormula.Len();
aSymbol.Erase();
}
else
{
aSymbol.Append( pStart + nSrcPos, (xub_StrLen)aRes.EndPos - nSrcPos );
nSrcPos = (xub_StrLen) aRes.EndPos;
c = pStart[nSrcPos];
if ( aRes.TokenType & KParseType::SINGLE_QUOTE_NAME )
{ // special cases (e.g. 'sheetname'. or 'filename'# in OOO A1)
bi18n = (c == cSheetSep || c == SC_COMPILER_FILE_TAB_SEP);
}
// One range operator restarts parsing for second reference.
if (c == ':' && mnRangeOpPosInSymbol < 0)
{
mnRangeOpPosInSymbol = aSymbol.Len();
bi18n = true;
}
if ( bi18n )
aSymbol += pStart[nSrcPos++];
}
} while ( bi18n && !nErr );
xub_StrLen nLen = aSymbol.Len();
if ( nLen >= MAXSTRLEN )
{
SetError( errStringOverflow );
nLen = MAXSTRLEN-1;
}
lcl_UnicodeStrNCpy( cSymbol, aSymbol.GetBuffer(), nLen );
pSym = &cSymbol[nLen];
}
else
{
nSrcPos = sal::static_int_cast<xub_StrLen>( pSrc - pStart );
*pSym = 0;
}
if (mnRangeOpPosInSymbol >= 0 && mnRangeOpPosInSymbol == (pSym-1) - &cSymbol[0])
{
// This is a trailing range operator, which is nonsense. Will be caught
// in next round.
mnRangeOpPosInSymbol = -1;
*--pSym = 0;
--nSrcPos;
}
if ( bAutoCorrect )
aCorrectedSymbol = cSymbol;
if (bAutoIntersection && nSpaces > 1)
--nSpaces; // replace '!!' with only one space
return nSpaces;
}
//---------------------------------------------------------------------------
// Convert symbol to token
//---------------------------------------------------------------------------
bool ScCompiler::IsOpCode( const String& rName, bool bInArray )
{
OpCodeHashMap::const_iterator iLook( mxSymbols->getHashMap()->find( rName));
bool bFound = (iLook != mxSymbols->getHashMap()->end());
if (bFound)
{
ScRawToken aToken;
OpCode eOp = iLook->second;
if (bInArray)
{
if (rName.Equals(mxSymbols->getSymbol(ocArrayColSep)))
eOp = ocArrayColSep;
else if (rName.Equals(mxSymbols->getSymbol(ocArrayRowSep)))
eOp = ocArrayRowSep;
}
aToken.SetOpCode(eOp);
pRawToken = aToken.Clone();
}
else if (mxSymbols->isODFF())
{
// ODFF names that are not written in the current mapping but to be
// recognized. New names will be written in a future relase, then
// exchange (!) with the names in
// formula/source/core/resource/core_resource.src to be able to still
// read the old names as well.
struct FunctionName
{
const sal_Char* pName;
OpCode eOp;
};
static const FunctionName aOdffAliases[] = {
// Renamed old names:
{ "B", ocB }, // B -> BINOM.DIST.RANGE
{ "TDIST", ocTDist }, // TDIST -> LEGACY.TDIST
{ "EASTERSUNDAY", ocEasterSunday } // EASTERSUNDAY -> ORG.OPENOFFICE.EASTERSUNDAY
// Renamed new names:
// XXX none currently. Example:
//{ "ORG.OPENOFFICE.EASTERSUNDAY", ocEasterSunday }
};
static const size_t nOdffAliases = SAL_N_ELEMENTS(aOdffAliases);
for (size_t i=0; i<nOdffAliases; ++i)
{
if (rName.EqualsIgnoreCaseAscii( aOdffAliases[i].pName))
{
ScRawToken aToken;
aToken.SetOpCode( aOdffAliases[i].eOp);
pRawToken = aToken.Clone();
bFound = true;
break; // for
}
}
}
if (!bFound)
{
String aIntName;
if (mxSymbols->hasExternals())
{
// If symbols are set by filters get mapping to exact name.
ExternalHashMap::const_iterator iExt(
mxSymbols->getExternalHashMap()->find( rName));
if (iExt != mxSymbols->getExternalHashMap()->end())
{
if (ScGlobal::GetAddInCollection()->GetFuncData( (*iExt).second))
aIntName = (*iExt).second;
}
if (!aIntName.Len())
{
// If that isn't found we might continue with rName lookup as a
// last resort by just falling through to FindFunction(), but
// it shouldn't happen if the map was setup correctly. Don't
// waste time and bail out.
return false;
}
}
if (!aIntName.Len())
{
// Old (deprecated) addins first for legacy.
sal_uInt16 nIndex;
bFound = ScGlobal::GetFuncCollection()->SearchFunc( cSymbol, nIndex);
if (bFound)
{
ScRawToken aToken;
aToken.SetExternal( cSymbol );
pRawToken = aToken.Clone();
}
else
// bLocalFirst=false for (English) upper full original name
// (service.function)
aIntName = ScGlobal::GetAddInCollection()->FindFunction(
rName, !mxSymbols->isEnglish());
}
if (aIntName.Len())
{
ScRawToken aToken;
aToken.SetExternal( aIntName.GetBuffer() ); // international name
pRawToken = aToken.Clone();
bFound = true;
}
}
OpCode eOp;
if (bFound && ((eOp = pRawToken->GetOpCode()) == ocSub || eOp == ocNegSub))
{
bool bShouldBeNegSub =
(eLastOp == ocOpen || eLastOp == ocSep || eLastOp == ocNegSub ||
(SC_OPCODE_START_BIN_OP <= eLastOp && eLastOp < SC_OPCODE_STOP_BIN_OP) ||
eLastOp == ocArrayOpen ||
eLastOp == ocArrayColSep || eLastOp == ocArrayRowSep);
if (bShouldBeNegSub && eOp == ocSub)
pRawToken->NewOpCode( ocNegSub );
//! if ocNegSub had ForceArray we'd have to set it here
else if (!bShouldBeNegSub && eOp == ocNegSub)
pRawToken->NewOpCode( ocSub );
}
return bFound;
}
bool ScCompiler::IsOpCode2( const String& rName )
{
bool bFound = false;
sal_uInt16 i;
for( i = ocInternalBegin; i <= ocInternalEnd && !bFound; i++ )
bFound = rName.EqualsAscii( pInternal[ i-ocInternalBegin ] );
if (bFound)
{
ScRawToken aToken;
aToken.SetOpCode( (OpCode) --i );
pRawToken = aToken.Clone();
}
return bFound;
}
bool ScCompiler::IsValue( const String& rSym )
{
double fVal;
sal_uInt32 nIndex = ( mxSymbols->isEnglish() ?
pDoc->GetFormatTable()->GetStandardIndex( LANGUAGE_ENGLISH_US ) : 0 );
if (pDoc->GetFormatTable()->IsNumberFormat( rSym, nIndex, fVal ) )
{
sal_uInt16 nType = pDoc->GetFormatTable()->GetType(nIndex);
// Don't accept 3:3 as time, it is a reference to entire row 3 instead.
// Dates should never be entered directly and automatically converted
// to serial, because the serial would be wrong if null-date changed.
// Usually it wouldn't be accepted anyway because the date separator
// clashed with other separators or operators.
if (nType & (NUMBERFORMAT_TIME | NUMBERFORMAT_DATE))
return false;
if (nType == NUMBERFORMAT_LOGICAL)
{
const sal_Unicode* p = aFormula.GetBuffer() + nSrcPos;
while( *p == ' ' )
p++;
if (*p == '(')
return false; // Boolean function instead.
}
if( nType == NUMBERFORMAT_TEXT )
// HACK: number too big!
SetError( errIllegalArgument );
ScRawToken aToken;
aToken.SetDouble( fVal );
pRawToken = aToken.Clone();
return true;
}
else
return false;
}
bool ScCompiler::IsString()
{
register const sal_Unicode* p = cSymbol;
while ( *p )
p++;
xub_StrLen nLen = sal::static_int_cast<xub_StrLen>( p - cSymbol - 1 );
bool bQuote = ((cSymbol[0] == '"') && (cSymbol[nLen] == '"'));
if ((bQuote ? nLen-2 : nLen) > MAXSTRLEN-1)
{
SetError(errStringOverflow);
return false;
}
if ( bQuote )
{
cSymbol[nLen] = '\0';
ScRawToken aToken;
aToken.SetString( cSymbol+1 );
pRawToken = aToken.Clone();
return true;
}
return false;
}
bool ScCompiler::IsPredetectedReference( const String& rName )
{
// Speedup documents with lots of broken references, e.g. sheet deleted.
xub_StrLen nPos = rName.SearchAscii( "#REF!");
if (nPos != STRING_NOTFOUND)
{
/* TODO: this may be enhanced by reusing scan information from
* NextSymbol(), the positions of quotes and special characters found
* there for $'sheet'.A1:... could be stored in a vector. We don't
* fully rescan here whether found positions are within single quotes
* for performance reasons. This code does not check for possible
* occurrences of insane "valid" sheet names like
* 'haha.#REF!1fooledyou' and will generate an error on such. */
if (nPos == 0)
{
// Per ODFF the correct string for a reference error is just #REF!,
// so pass it on.
if (rName.Len() == 5)
return IsErrorConstant( rName);
return false; // #REF!.AB42 or #REF!42 or #REF!#REF!
}
sal_Unicode c = rName.GetChar(nPos-1); // before #REF!
if ('$' == c)
{
if (nPos == 1)
return false; // $#REF!.AB42 or $#REF!42 or $#REF!#REF!
c = rName.GetChar(nPos-2); // before $#REF!
}
sal_Unicode c2 = rName.GetChar(nPos+5); // after #REF!
switch (c)
{
case '.':
if ('$' == c2 || '#' == c2 || ('0' <= c2 && c2 <= '9'))
return false; // sheet.#REF!42 or sheet.#REF!#REF!
break;
case ':':
if (mnPredetectedReference > 1 &&
('.' == c2 || '$' == c2 || '#' == c2 ||
('0' <= c2 && c2 <= '9')))
return false; // :#REF!.AB42 or :#REF!42 or :#REF!#REF!
break;
default:
if (comphelper::string::isalphaAscii(c) &&
((mnPredetectedReference > 1 && ':' == c2) || 0 == c2))
return false; // AB#REF!: or AB#REF!
}
}
switch (mnPredetectedReference)
{
case 1:
return IsSingleReference( rName);
case 2:
return IsDoubleReference( rName);
}
return false;
}
bool ScCompiler::IsDoubleReference( const String& rName )
{
ScRange aRange( aPos, aPos );
const ScAddress::Details aDetails( pConv->meConv, aPos );
ScAddress::ExternalInfo aExtInfo;
sal_uInt16 nFlags = aRange.Parse( rName, pDoc, aDetails, &aExtInfo, &maExternalLinks );
if( nFlags & SCA_VALID )
{
ScRawToken aToken;
ScComplexRefData aRef;
aRef.InitRange( aRange );
aRef.Ref1.SetColRel( (nFlags & SCA_COL_ABSOLUTE) == 0 );
aRef.Ref1.SetRowRel( (nFlags & SCA_ROW_ABSOLUTE) == 0 );
aRef.Ref1.SetTabRel( (nFlags & SCA_TAB_ABSOLUTE) == 0 );
if ( !(nFlags & SCA_VALID_TAB) )
aRef.Ref1.SetTabDeleted( true ); // #REF!
aRef.Ref1.SetFlag3D( ( nFlags & SCA_TAB_3D ) != 0 );
aRef.Ref2.SetColRel( (nFlags & SCA_COL2_ABSOLUTE) == 0 );
aRef.Ref2.SetRowRel( (nFlags & SCA_ROW2_ABSOLUTE) == 0 );
aRef.Ref2.SetTabRel( (nFlags & SCA_TAB2_ABSOLUTE) == 0 );
if ( !(nFlags & SCA_VALID_TAB2) )
aRef.Ref2.SetTabDeleted( true ); // #REF!
aRef.Ref2.SetFlag3D( ( nFlags & SCA_TAB2_3D ) != 0 );
aRef.CalcRelFromAbs( aPos );
if (aExtInfo.mbExternal)
{
ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
const OUString* pRealTab = pRefMgr->getRealTableName(aExtInfo.mnFileId, aExtInfo.maTabName);
aToken.SetExternalDoubleRef(
aExtInfo.mnFileId, pRealTab ? *pRealTab : aExtInfo.maTabName, aRef);
}
else
{
aToken.SetDoubleReference(aRef);
}
pRawToken = aToken.Clone();
}
return ( nFlags & SCA_VALID ) != 0;
}
bool ScCompiler::IsSingleReference( const String& rName )
{
ScAddress aAddr( aPos );
const ScAddress::Details aDetails( pConv->meConv, aPos );
ScAddress::ExternalInfo aExtInfo;
sal_uInt16 nFlags = aAddr.Parse( rName, pDoc, aDetails, &aExtInfo, &maExternalLinks );
// Something must be valid in order to recognize Sheet1.blah or blah.a1
// as a (wrong) reference.
if( nFlags & ( SCA_VALID_COL|SCA_VALID_ROW|SCA_VALID_TAB ) )
{
ScRawToken aToken;
ScSingleRefData aRef;
aRef.InitAddress( aAddr );
aRef.SetColRel( (nFlags & SCA_COL_ABSOLUTE) == 0 );
aRef.SetRowRel( (nFlags & SCA_ROW_ABSOLUTE) == 0 );
aRef.SetTabRel( (nFlags & SCA_TAB_ABSOLUTE) == 0 );
aRef.SetFlag3D( ( nFlags & SCA_TAB_3D ) != 0 );
// the reference is really invalid
if( !( nFlags & SCA_VALID ) )
{
if( !( nFlags & SCA_VALID_COL ) )
aRef.nCol = MAXCOL+1;
if( !( nFlags & SCA_VALID_ROW ) )
aRef.nRow = MAXROW+1;
if( !( nFlags & SCA_VALID_TAB ) )
aRef.nTab = MAXTAB+3;
nFlags |= SCA_VALID;
}
aRef.CalcRelFromAbs( aPos );
if (aExtInfo.mbExternal)
{
ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
const OUString* pRealTab = pRefMgr->getRealTableName(aExtInfo.mnFileId, aExtInfo.maTabName);
aToken.SetExternalSingleRef(
aExtInfo.mnFileId, pRealTab ? *pRealTab : aExtInfo.maTabName, aRef);
}
else
aToken.SetSingleReference(aRef);
pRawToken = aToken.Clone();
}
return ( nFlags & SCA_VALID ) != 0;
}
bool ScCompiler::IsReference( const String& rName )
{
// Has to be called before IsValue
sal_Unicode ch1 = rName.GetChar(0);
sal_Unicode cDecSep = ( mxSymbols->isEnglish() ? '.' :
ScGlobal::pLocaleData->getNumDecimalSep().GetChar(0) );
if ( ch1 == cDecSep )
return false;
// Who was that imbecile introducing '.' as the sheet name separator!?!
if ( CharClass::isAsciiNumeric( ch1 ) )
{
// Numerical sheet name is valid.
// But English 1.E2 or 1.E+2 is value 100, 1.E-2 is 0.01
// Don't create a #REF! of values. But also do not bail out on
// something like 3:3, meaning entire row 3.
do
{
const xub_StrLen nPos = ScGlobal::FindUnquoted( rName, '.');
if ( nPos == STRING_NOTFOUND )
{
if (ScGlobal::FindUnquoted( rName, ':') != STRING_NOTFOUND)
break; // may be 3:3, continue as usual
return false;
}
sal_Unicode const * const pTabSep = rName.GetBuffer() + nPos;
sal_Unicode ch2 = pTabSep[1]; // maybe a column identifier
if ( !(ch2 == '$' || CharClass::isAsciiAlpha( ch2 )) )
return false;
if ( cDecSep == '.' && (ch2 == 'E' || ch2 == 'e') // E + - digit
&& (GetCharTableFlags( pTabSep[2], pTabSep[1] ) & SC_COMPILER_C_VALUE_EXP) )
{ // #91053#
// If it is an 1.E2 expression check if "1" is an existent sheet
// name. If so, a desired value 1.E2 would have to be entered as
// 1E2 or 1.0E2 or 1.E+2, sorry. Another possibility would be to
// require numerical sheet names always being entered quoted, which
// is not desirable (too many 1999, 2000, 2001 sheets in use).
// Furthermore, XML files created with versions prior to SRC640e
// wouldn't contain the quotes added by MakeTabStr()/CheckTabQuotes()
// and would produce wrong formulas if the conditions here are met.
// If you can live with these restrictions you may remove the
// check and return an unconditional FALSE.
String aTabName( rName.Copy( 0, nPos ) );
SCTAB nTab;
if ( !pDoc->GetTable( aTabName, nTab ) )
return false;
// If sheet "1" exists and the expression is 1.E+2 continue as
// usual, the ScRange/ScAddress parser will take care of it.
}
} while(0);
}
if (IsSingleReference( rName))
return true;
// Though the range operator is handled explicitly, when encountering
// something like Sheet1.A:A we will have to treat it as one entity if it
// doesn't pass as single cell reference.
if (mnRangeOpPosInSymbol > 0) // ":foo" would be nonsense
{
if (IsDoubleReference( rName))
return true;
// Now try with a symbol up to the range operator, rewind source
// position.
sal_Int32 nLen = mnRangeOpPosInSymbol;
while (cSymbol[++nLen])
;
cSymbol[mnRangeOpPosInSymbol] = 0;
nSrcPos -= static_cast<xub_StrLen>(nLen - mnRangeOpPosInSymbol);
mnRangeOpPosInSymbol = -1;
mbRewind = true;
return true; // end all checks
}
else
{
// Special treatment for the 'E:\[doc]Sheet1:Sheet3'!D5 Excel sickness,
// mnRangeOpPosInSymbol did not catch the range operator as it is
// within a quoted name.
switch (pConv->meConv)
{
case FormulaGrammar::CONV_XL_A1:
case FormulaGrammar::CONV_XL_R1C1:
case FormulaGrammar::CONV_XL_OOX:
if (rName.GetChar(0) == '\'' && IsDoubleReference( rName))
return true;
break;
default:
; // nothing
}
}
return false;
}
bool ScCompiler::IsMacro( const String& rName )
{
String aName( rName);
StarBASIC* pObj = 0;
SfxObjectShell* pDocSh = pDoc->GetDocumentShell();
SfxApplication* pSfxApp = SFX_APP();
if( pDocSh )//XXX
pObj = pDocSh->GetBasic();
else
pObj = pSfxApp->GetBasic();
// ODFF recommends to store user-defined functions prefixed with "USER.",
// use only unprefixed name if encountered. BASIC doesn't allow '.' in a
// function name so a function "USER.FOO" could not exist, and macro check
// is assigned the lowest priority in function name check.
if (FormulaGrammar::isODFF( GetGrammar()) && aName.EqualsIgnoreCaseAscii( "USER.", 0, 5))
aName.Erase( 0, 5);
SbxMethod* pMeth = (SbxMethod*) pObj->Find( aName, SbxCLASS_METHOD );
if( !pMeth )
{
return false;
}
// It really should be a BASIC function!
if( pMeth->GetType() == SbxVOID
|| ( pMeth->IsFixed() && pMeth->GetType() == SbxEMPTY )
|| !pMeth->ISA(SbMethod) )
{
return false;
}
ScRawToken aToken;
aToken.SetExternal( aName.GetBuffer() );
aToken.eOp = ocMacro;
pRawToken = aToken.Clone();
return true;
}
bool ScCompiler::IsNamedRange( const String& rUpperName )
{
// IsNamedRange is called only from NextNewToken, with an upper-case string
// try local names first
bool bGlobal = false;
ScRangeName* pRangeName = pDoc->GetRangeName(aPos.Tab());
const ScRangeData* pData = NULL;
if (pRangeName)
pData = pRangeName->findByUpperName(rUpperName);
if (!pData)
{
pRangeName = pDoc->GetRangeName();
if (pRangeName)
pData = pRangeName->findByUpperName(rUpperName);
if (pData)
bGlobal = true;
}
if (pData)
{
ScRawToken aToken;
aToken.SetName(bGlobal, pData->GetIndex());
pRawToken = aToken.Clone();
return true;
}
else
return false;
}
bool ScCompiler::IsExternalNamedRange( const String& rSymbol )
{
/* FIXME: This code currently (2008-12-02T15:41+0100 in CWS mooxlsc)
* correctly parses external named references in OOo, as required per RFE
* #i3740#, just that we can't store them in ODF yet. We will need an OASIS
* spec first. Until then don't pretend to support external names that
* wouldn't survive a save and reload cycle, return false instead. */
if (!pConv)
return false;
String aFile, aName;
if (!pConv->parseExternalName( rSymbol, aFile, aName, pDoc, &maExternalLinks))
return false;
ScRawToken aToken;
if (aFile.Len() > MAXSTRLEN || aName.Len() > MAXSTRLEN)
return false;
ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
OUString aTmp = aFile;
pRefMgr->convertToAbsName(aTmp);
aFile = aTmp;
sal_uInt16 nFileId = pRefMgr->getExternalFileId(aFile);
if (!pRefMgr->getRangeNameTokens(nFileId, aName).get())
// range name doesn't exist in the source document.
return false;
const OUString* pRealName = pRefMgr->getRealRangeName(nFileId, aName);
aToken.SetExternalName(nFileId, pRealName ? *pRealName : OUString(aTmp));
pRawToken = aToken.Clone();
return true;
}
bool ScCompiler::IsDBRange( const String& rName )
{
if (rName.EqualsAscii("[]"))
{
if (pRawToken && pRawToken->GetOpCode() == ocDBArea)
{
// In OOXML, a database range is named Table1[], Table2[] etc.
// Skip the [] part if the previous token is a valid db range.
ScRawToken aToken;
aToken.eOp = ocSkip;
pRawToken = aToken.Clone();
return true;
}
}
ScDBCollection::NamedDBs& rDBs = pDoc->GetDBCollection()->getNamedDBs();
const ScDBData* p = rDBs.findByUpperName(rName);
if (!p)
return false;
ScRawToken aToken;
aToken.SetName(true, p->GetIndex()); // DB range is always global.
aToken.eOp = ocDBArea;
pRawToken = aToken.Clone();
return true;
}
bool ScCompiler::IsColRowName( const String& rName )
{
bool bInList = false;
bool bFound = false;
ScSingleRefData aRef;
String aName( rName );
DeQuote( aName );
SCTAB nThisTab = aPos.Tab();
for ( short jThisTab = 1; jThisTab >= 0 && !bInList; jThisTab-- )
{ // first check ranges on this sheet, in case of duplicated names
for ( short jRow=0; jRow<2 && !bInList; jRow++ )
{
ScRangePairList* pRL;
if ( !jRow )
pRL = pDoc->GetColNameRanges();
else
pRL = pDoc->GetRowNameRanges();
for ( size_t iPair = 0, nPairs = pRL->size(); iPair < nPairs && !bInList; ++iPair )
{
ScRangePair* pR = (*pRL)[iPair];
const ScRange& rNameRange = pR->GetRange(0);
if ( jThisTab && !(rNameRange.aStart.Tab() <= nThisTab &&
nThisTab <= rNameRange.aEnd.Tab()) )
continue; // for
ScCellIterator aIter( pDoc, rNameRange );
for ( ScBaseCell* pCell = aIter.GetFirst(); pCell && !bInList;
pCell = aIter.GetNext() )
{
// Don't crash if cell (via CompileNameFormula) encounters
// a formula cell without code and
// HasStringData/Interpret/Compile is executed and all that
// recursive..
// Furthermore, *this* cell won't be touched, since no RPN exists yet.
CellType eType = pCell->GetCellType();
bool bOk = ( (eType == CELLTYPE_FORMULA ?
((ScFormulaCell*)pCell)->GetCode()->GetCodeLen() > 0
&& ((ScFormulaCell*)pCell)->aPos != aPos // noIter
: true ) );
if ( bOk && pCell->HasStringData() )
{
String aStr;
switch ( eType )
{
case CELLTYPE_STRING:
((ScStringCell*)pCell)->GetString( aStr );
break;
case CELLTYPE_FORMULA:
((ScFormulaCell*)pCell)->GetString( aStr );
break;
case CELLTYPE_EDIT:
((ScEditCell*)pCell)->GetString( aStr );
break;
case CELLTYPE_NONE:
case CELLTYPE_VALUE:
case CELLTYPE_NOTE:
case CELLTYPE_SYMBOLS:
#if OSL_DEBUG_LEVEL > 0
case CELLTYPE_DESTROYED:
#endif
; // nothing, prevent compiler warning
break;
}
if ( ScGlobal::GetpTransliteration()->isEqual( aStr, aName ) )
{
aRef.InitFlags();
aRef.nCol = aIter.GetCol();
aRef.nRow = aIter.GetRow();
aRef.nTab = aIter.GetTab();
if ( !jRow )
aRef.SetColRel( true ); // ColName
else
aRef.SetRowRel( true ); // RowName
aRef.CalcRelFromAbs( aPos );
bInList = bFound = true;
}
}
}
}
}
}
if ( !bInList && pDoc->GetDocOptions().IsLookUpColRowNames() )
{ // search in current sheet
long nDistance = 0, nMax = 0;
long nMyCol = (long) aPos.Col();
long nMyRow = (long) aPos.Row();
bool bTwo = false;
ScAddress aOne( 0, 0, aPos.Tab() );
ScAddress aTwo( MAXCOL, MAXROW, aPos.Tab() );
ScAutoNameCache* pNameCache = pDoc->GetAutoNameCache();
if ( pNameCache )
{
// use GetNameOccurrences to collect all positions of aName on the sheet
// (only once), similar to the outer part of the loop in the "else" branch.
const ScAutoNameAddresses& rAddresses = pNameCache->GetNameOccurrences( aName, aPos.Tab() );
// Loop through the found positions, similar to the inner part of the loop in the "else" branch.
// The order of addresses in the vector is the same as from ScCellIterator.
ScAutoNameAddresses::const_iterator aEnd(rAddresses.end());
for ( ScAutoNameAddresses::const_iterator aAdrIter(rAddresses.begin()); aAdrIter != aEnd; ++aAdrIter )
{
ScAddress aAddress( *aAdrIter ); // cell address with an equal string
if ( bFound )
{ // stop if everything else is further away
if ( nMax < (long)aAddress.Col() )
break; // aIter
}
if ( aAddress != aPos )
{
// same treatment as in isEqual case below
SCCOL nCol = aAddress.Col();
SCROW nRow = aAddress.Row();
long nC = nMyCol - nCol;
long nR = nMyRow - nRow;
if ( bFound )
{
long nD = nC * nC + nR * nR;
if ( nD < nDistance )
{
if ( nC < 0 || nR < 0 )
{ // right or below
bTwo = true;
aTwo.Set( nCol, nRow, aAddress.Tab() );
nMax = Max( nMyCol + Abs( nC ), nMyRow + Abs( nR ) );
nDistance = nD;
}
else if ( !(nRow < aOne.Row() && nMyRow >= (long)aOne.Row()) )
{
// upper left, only if not further up than the
// current entry and nMyRow is below (CellIter
// runs column-wise)
bTwo = false;
aOne.Set( nCol, nRow, aAddress.Tab() );
nMax = Max( nMyCol + nC, nMyRow + nR );
nDistance = nD;
}
}
}
else
{
aOne.Set( nCol, nRow, aAddress.Tab() );
nDistance = nC * nC + nR * nR;
nMax = Max( nMyCol + Abs( nC ), nMyRow + Abs( nR ) );
}
bFound = true;
}
}
}
else
{
ScCellIterator aIter( pDoc, ScRange( aOne, aTwo ) );
for ( ScBaseCell* pCell = aIter.GetFirst(); pCell; pCell = aIter.GetNext() )
{
if ( bFound )
{ // stop if everything else is further away
if ( nMax < (long)aIter.GetCol() )
break; // aIter
}
CellType eType = pCell->GetCellType();
bool bOk = ( (eType == CELLTYPE_FORMULA ?
((ScFormulaCell*)pCell)->GetCode()->GetCodeLen() > 0
&& ((ScFormulaCell*)pCell)->aPos != aPos // noIter
: true ) );
if ( bOk && pCell->HasStringData() )
{
String aStr;
switch ( eType )
{
case CELLTYPE_STRING:
((ScStringCell*)pCell)->GetString( aStr );
break;
case CELLTYPE_FORMULA:
((ScFormulaCell*)pCell)->GetString( aStr );
break;
case CELLTYPE_EDIT:
((ScEditCell*)pCell)->GetString( aStr );
break;
case CELLTYPE_NONE:
case CELLTYPE_VALUE:
case CELLTYPE_NOTE:
case CELLTYPE_SYMBOLS:
#if OSL_DEBUG_LEVEL > 0
case CELLTYPE_DESTROYED:
#endif
; // nothing, prevent compiler warning
break;
}
if ( ScGlobal::GetpTransliteration()->isEqual( aStr, aName ) )
{
SCCOL nCol = aIter.GetCol();
SCROW nRow = aIter.GetRow();
long nC = nMyCol - nCol;
long nR = nMyRow - nRow;
if ( bFound )
{
long nD = nC * nC + nR * nR;
if ( nD < nDistance )
{
if ( nC < 0 || nR < 0 )
{ // right or below
bTwo = true;
aTwo.Set( nCol, nRow, aIter.GetTab() );
nMax = Max( nMyCol + Abs( nC ), nMyRow + Abs( nR ) );
nDistance = nD;
}
else if ( !(nRow < aOne.Row() && nMyRow >= (long)aOne.Row()) )
{
// upper left, only if not further up than the
// current entry and nMyRow is below (CellIter
// runs column-wise)
bTwo = false;
aOne.Set( nCol, nRow, aIter.GetTab() );
nMax = Max( nMyCol + nC, nMyRow + nR );
nDistance = nD;
}
}
}
else
{
aOne.Set( nCol, nRow, aIter.GetTab() );
nDistance = nC * nC + nR * nR;
nMax = Max( nMyCol + Abs( nC ), nMyRow + Abs( nR ) );
}
bFound = true;
}
}
}
}
if ( bFound )
{
ScAddress aAdr;
if ( bTwo )
{
if ( nMyCol >= (long)aOne.Col() && nMyRow >= (long)aOne.Row() )
aAdr = aOne; // upper left takes precedence
else
{
if ( nMyCol < (long)aOne.Col() )
{ // two to the right
if ( nMyRow >= (long)aTwo.Row() )
aAdr = aTwo; // directly right
else
aAdr = aOne;
}
else
{ // two below or below and right, take the nearest
long nC1 = nMyCol - aOne.Col();
long nR1 = nMyRow - aOne.Row();
long nC2 = nMyCol - aTwo.Col();
long nR2 = nMyRow - aTwo.Row();
if ( nC1 * nC1 + nR1 * nR1 <= nC2 * nC2 + nR2 * nR2 )
aAdr = aOne;
else
aAdr = aTwo;
}
}
}
else
aAdr = aOne;
aRef.InitAddress( aAdr );
if ( (aRef.nRow != MAXROW && pDoc->HasStringData(
aRef.nCol, aRef.nRow + 1, aRef.nTab ))
|| (aRef.nRow != 0 && pDoc->HasStringData(
aRef.nCol, aRef.nRow - 1, aRef.nTab )) )
aRef.SetRowRel( true ); // RowName
else
aRef.SetColRel( true ); // ColName
aRef.CalcRelFromAbs( aPos );
}
}
if ( bFound )
{
ScRawToken aToken;
aToken.SetSingleReference( aRef );
aToken.eOp = ocColRowName;
pRawToken = aToken.Clone();
return true;
}
else
return false;
}
bool ScCompiler::IsBoolean( const String& rName )
{
OpCodeHashMap::const_iterator iLook( mxSymbols->getHashMap()->find( rName ) );
if( iLook != mxSymbols->getHashMap()->end() &&
((*iLook).second == ocTrue ||
(*iLook).second == ocFalse) )
{
ScRawToken aToken;
aToken.SetOpCode( (*iLook).second );
pRawToken = aToken.Clone();
return true;
}
else
return false;
}
bool ScCompiler::IsErrorConstant( const String& rName )
{
sal_uInt16 nError = GetErrorConstant( rName);
if (nError)
{
ScRawToken aToken;
aToken.SetErrorConstant( nError);
pRawToken = aToken.Clone();
return true;
}
else
return false;
}
//---------------------------------------------------------------------------
void ScCompiler::AutoCorrectParsedSymbol()
{
xub_StrLen nPos = aCorrectedSymbol.Len();
if ( nPos )
{
nPos--;
const sal_Unicode cQuote = '\"';
const sal_Unicode cx = 'x';
const sal_Unicode cX = 'X';
sal_Unicode c1 = aCorrectedSymbol.GetChar( 0 );
sal_Unicode c2 = aCorrectedSymbol.GetChar( nPos );
sal_Unicode c2p = nPos > 0 ? aCorrectedSymbol.GetChar( nPos-1 ) : 0;
if ( c1 == cQuote && c2 != cQuote )
{ // "...
// What's not a word doesn't belong to it.
// Don't be pedantic: c < 128 should be sufficient here.
while ( nPos && ((aCorrectedSymbol.GetChar(nPos) < 128) &&
((GetCharTableFlags(aCorrectedSymbol.GetChar(nPos), aCorrectedSymbol.GetChar(nPos-1)) &
(SC_COMPILER_C_WORD | SC_COMPILER_C_CHAR_DONTCARE)) == 0)) )
nPos--;
if ( nPos == MAXSTRLEN - 2 )
aCorrectedSymbol.SetChar( nPos, cQuote ); // '"' the 255th character
else
aCorrectedSymbol.Insert( cQuote, nPos + 1 );
bCorrected = true;
}
else if ( c1 != cQuote && c2 == cQuote )
{ // ..."
aCorrectedSymbol.Insert( cQuote, 0 );
bCorrected = true;
}
else if ( nPos == 0 && (c1 == cx || c1 == cX) )
{ // x => *
aCorrectedSymbol = mxSymbols->getSymbol(ocMul);
bCorrected = true;
}
else if ( (GetCharTableFlags( c1, 0 ) & SC_COMPILER_C_CHAR_VALUE)
&& (GetCharTableFlags( c2, c2p ) & SC_COMPILER_C_CHAR_VALUE) )
{
xub_StrLen nXcount;
if ( (nXcount = aCorrectedSymbol.GetTokenCount( cx )) > 1 )
{ // x => *
xub_StrLen nIndex = 0;
sal_Unicode c = mxSymbols->getSymbol(ocMul).GetChar(0);
while ( (nIndex = aCorrectedSymbol.SearchAndReplace(
cx, c, nIndex )) != STRING_NOTFOUND )
nIndex++;
bCorrected = true;
}
if ( (nXcount = aCorrectedSymbol.GetTokenCount( cX )) > 1 )
{ // X => *
xub_StrLen nIndex = 0;
sal_Unicode c = mxSymbols->getSymbol(ocMul).GetChar(0);
while ( (nIndex = aCorrectedSymbol.SearchAndReplace(
cX, c, nIndex )) != STRING_NOTFOUND )
nIndex++;
bCorrected = true;
}
}
else
{
String aSymbol( aCorrectedSymbol );
String aDoc;
xub_StrLen nPosition;
if ( aSymbol.GetChar(0) == '\''
&& ((nPosition = aSymbol.SearchAscii( "'#" )) != STRING_NOTFOUND) )
{ // Split off 'Doc'#, may be d:\... or whatever
aDoc = aSymbol.Copy( 0, nPosition + 2 );
aSymbol.Erase( 0, nPosition + 2 );
}
xub_StrLen nRefs = aSymbol.GetTokenCount( ':' );
bool bColons;
if ( nRefs > 2 )
{ // duplicated or too many ':'? B:2::C10 => B2:C10
bColons = true;
xub_StrLen nIndex = 0;
String aTmp1( aSymbol.GetToken( 0, ':', nIndex ) );
xub_StrLen nLen1 = aTmp1.Len();
String aSym, aTmp2;
bool bLastAlp, bNextNum;
bLastAlp = bNextNum = true;
xub_StrLen nStrip = 0;
xub_StrLen nCount = nRefs;
for ( xub_StrLen j=1; j<nCount; j++ )
{
aTmp2 = aSymbol.GetToken( 0, ':', nIndex );
xub_StrLen nLen2 = aTmp2.Len();
if ( nLen1 || nLen2 )
{
if ( nLen1 )
{
aSym += aTmp1;
bLastAlp = CharClass::isAsciiAlpha( aTmp1 );
}
if ( nLen2 )
{
bNextNum = CharClass::isAsciiNumeric( aTmp2 );
if ( bLastAlp == bNextNum && nStrip < 1 )
{
// Must be alternating number/string, only
// strip within a reference.
nRefs--;
nStrip++;
}
else
{
xub_StrLen nSymLen = aSym.Len();
if ( nSymLen
&& (aSym.GetChar( nSymLen - 1 ) != ':') )
aSym += ':';
nStrip = 0;
}
bLastAlp = !bNextNum;
}
else
{ // ::
nRefs--;
if ( nLen1 )
{ // B10::C10 ? append ':' on next round
if ( !bLastAlp && !CharClass::isAsciiNumeric( aTmp1 ) )
nStrip++;
}
bNextNum = !bLastAlp;
}
aTmp1 = aTmp2;
nLen1 = nLen2;
}
else
nRefs--;
}
aSymbol = aSym;
aSymbol += aTmp1;
}
else
bColons = false;
if ( nRefs && nRefs <= 2 )
{ // reference twisted? 4A => A4 etc.
String aTab[2], aRef[2];
const ScAddress::Details aDetails( pConv->meConv, aPos );
if ( nRefs == 2 )
{
aRef[0] = aSymbol.GetToken( 0, ':' );
aRef[1] = aSymbol.GetToken( 1, ':' );
}
else
aRef[0] = aSymbol;
bool bChanged = false;
bool bOk = true;
sal_uInt16 nMask = SCA_VALID | SCA_VALID_COL | SCA_VALID_ROW;
for ( int j=0; j<nRefs; j++ )
{
xub_StrLen nTmp = 0;
xub_StrLen nDotPos = STRING_NOTFOUND;
while ( (nTmp = aRef[j].Search( '.', nTmp )) != STRING_NOTFOUND )
nDotPos = nTmp++; // the last one counts
if ( nDotPos != STRING_NOTFOUND )
{
aTab[j] = aRef[j].Copy( 0, nDotPos + 1 ); // with '.'
aRef[j].Erase( 0, nDotPos + 1 );
}
String aOld( aRef[j] );
String aStr2;
const sal_Unicode* p = aRef[j].GetBuffer();
while ( *p && CharClass::isAsciiNumeric( *p ) )
aStr2 += *p++;
aRef[j] = String( p );
aRef[j] += aStr2;
if ( bColons || aRef[j] != aOld )
{
bChanged = true;
ScAddress aAdr;
bOk &= ((aAdr.Parse( aRef[j], pDoc, aDetails ) & nMask) == nMask);
}
}
if ( bChanged && bOk )
{
aCorrectedSymbol = aDoc;
aCorrectedSymbol += aTab[0];
aCorrectedSymbol += aRef[0];
if ( nRefs == 2 )
{
aCorrectedSymbol += ':';
aCorrectedSymbol += aTab[1];
aCorrectedSymbol += aRef[1];
}
bCorrected = true;
}
}
}
}
}
inline bool lcl_UpperAsciiOrI18n( String& rUpper, const String& rOrg, FormulaGrammar::Grammar eGrammar )
{
if (FormulaGrammar::isODFF( eGrammar ))
{
// ODFF has a defined set of English function names, avoid i18n
// overhead.
rUpper = rOrg;
rUpper.ToUpperAscii();
return true;
}
else
{
rUpper = ScGlobal::pCharClass->upper( rOrg );
return false;
}
}
bool ScCompiler::NextNewToken( bool bInArray )
{
bool bAllowBooleans = bInArray;
xub_StrLen nSpaces = NextSymbol(bInArray);
if (!cSymbol[0])
return false;
if( nSpaces )
{
ScRawToken aToken;
aToken.SetOpCode( ocSpaces );
aToken.sbyte.cByte = (sal_uInt8) ( nSpaces > 255 ? 255 : nSpaces );
if( !static_cast<ScTokenArray*>(pArr)->AddRawToken( aToken ) )
{
SetError(errCodeOverflow);
return false;
}
}
// Short cut for references when reading ODF to speedup things.
if (mnPredetectedReference)
{
String aStr( cSymbol);
if (!IsPredetectedReference( aStr) && !IsExternalNamedRange( aStr))
{
/* TODO: it would be nice to generate a #REF! error here, which
* would need an ocBad token with additional error value.
* FormulaErrorToken wouldn't do because we want to preserve the
* original string containing partial valid address
* information if not ODFF (in that case it was already handled).
* */
ScRawToken aToken;
aToken.SetString( aStr.GetBuffer() );
aToken.NewOpCode( ocBad );
pRawToken = aToken.Clone();
}
return true;
}
if ( (cSymbol[0] == '#' || cSymbol[0] == '$') && cSymbol[1] == 0 &&
!bAutoCorrect )
{ // special case to speed up broken [$]#REF documents
/* FIXME: ISERROR(#REF!) would be valid and TRUE and the formula to
* be processed as usual. That would need some special treatment,
* also in NextSymbol() because of possible combinations of
* #REF!.#REF!#REF! parts. In case of reading ODF that is all
* handled by IsPredetectedReference(), this case here remains for
* manual/API input. */
String aBad( aFormula.Copy( nSrcPos-1 ) );
eLastOp = pArr->AddBad( aBad )->GetOpCode();
return false;
}
if( IsString() )
return true;
bool bMayBeFuncName;
bool bAsciiNonAlnum; // operators, separators, ...
if ( cSymbol[0] < 128 )
{
bMayBeFuncName = CharClass::isAsciiAlpha( cSymbol[0] );
bAsciiNonAlnum = !bMayBeFuncName && !CharClass::isAsciiDigit( cSymbol[0] );
}
else
{
String aTmpStr( cSymbol[0] );
bMayBeFuncName = ScGlobal::pCharClass->isLetter( aTmpStr, 0 );
bAsciiNonAlnum = false;
}
if ( bMayBeFuncName )
{
// a function name must be followed by a parenthesis
const sal_Unicode* p = aFormula.GetBuffer() + nSrcPos;
while( *p == ' ' )
p++;
bMayBeFuncName = ( *p == '(' );
}
// Italian ARCTAN.2 resulted in #REF! => IsOpcode() before
// IsReference().
String aUpper;
do
{
mbRewind = false;
const String aOrg( cSymbol );
if (bAsciiNonAlnum)
{
if (cSymbol[0] == '#')
{
// This can be only an error constant, if any.
lcl_UpperAsciiOrI18n( aUpper, aOrg, meGrammar);
if (IsErrorConstant( aUpper))
return true;
break; // do; create ocBad token or set error.
}
if (IsOpCode( aOrg, bInArray ))
return true;
}
aUpper.Erase();
bool bAsciiUpper = false;
if (bMayBeFuncName)
{
bAsciiUpper = lcl_UpperAsciiOrI18n( aUpper, aOrg, meGrammar);
if (IsOpCode( aUpper, bInArray ))
return true;
}
// Column 'DM' ("Deutsche Mark", German currency) couldn't be
// referred => IsReference() before IsValue().
// Preserve case of file names in external references.
if (IsReference( aOrg ))
{
if (mbRewind) // Range operator, but no direct reference.
continue; // do; up to range operator.
return true;
}
if (!aUpper.Len())
bAsciiUpper = lcl_UpperAsciiOrI18n( aUpper, aOrg, meGrammar);
// IsBoolean() before IsValue() to catch inline bools without the kludge
// for inline arrays.
if (bAllowBooleans && IsBoolean( aUpper ))
return true;
if (IsValue( aUpper ))
return true;
// User defined names and such do need i18n upper also in ODF.
if (bAsciiUpper)
aUpper = ScGlobal::pCharClass->upper( aOrg );
if (IsNamedRange( aUpper ))
return true;
// Preserve case of file names in external references.
if (IsExternalNamedRange( aOrg ))
return true;
if (IsDBRange( aUpper ))
return true;
if (IsColRowName( aUpper ))
return true;
if (bMayBeFuncName && IsMacro( aUpper ))
return true;
if (bMayBeFuncName && IsOpCode2( aUpper ))
return true;
} while (mbRewind);
if ( meExtendedErrorDetection != EXTENDED_ERROR_DETECTION_NONE )
{
// set an error
SetError( errNoName );
if (meExtendedErrorDetection == EXTENDED_ERROR_DETECTION_NAME_BREAK)
return false; // end compilation
}
// Provide single token information and continue. Do not set an error, that
// would prematurely end compilation. Simple unknown names are handled by
// the interpreter.
ScGlobal::pCharClass->toLower( aUpper );
ScRawToken aToken;
aToken.SetString( aUpper.GetBuffer() );
aToken.NewOpCode( ocBad );
pRawToken = aToken.Clone();
if ( bAutoCorrect )
AutoCorrectParsedSymbol();
return true;
}
void ScCompiler::CreateStringFromXMLTokenArray( String& rFormula, String& rFormulaNmsp )
{
bool bExternal = GetGrammar() == FormulaGrammar::GRAM_EXTERNAL;
sal_uInt16 nExpectedCount = bExternal ? 2 : 1;
OSL_ENSURE( pArr->GetLen() == nExpectedCount, "ScCompiler::CreateStringFromXMLTokenArray - wrong number of tokens" );
if( pArr->GetLen() == nExpectedCount )
{
FormulaToken** ppTokens = pArr->GetArray();
// string tokens expected, GetString() will assert if token type is wrong
rFormula = ppTokens[ 0 ]->GetString();
if( bExternal )
rFormulaNmsp = ppTokens[ 1 ]->GetString();
}
}
ScTokenArray* ScCompiler::CompileString( const String& rFormula )
{
OSL_ENSURE( meGrammar != FormulaGrammar::GRAM_EXTERNAL, "ScCompiler::CompileString - unexpected grammar GRAM_EXTERNAL" );
if( meGrammar == FormulaGrammar::GRAM_EXTERNAL )
SetGrammar( FormulaGrammar::GRAM_PODF );
ScTokenArray aArr;
pArr = &aArr;
aFormula = rFormula;
aFormula.EraseLeadingChars();
aFormula.EraseTrailingChars();
nSrcPos = 0;
bCorrected = false;
if ( bAutoCorrect )
{
aCorrectedFormula.Erase();
aCorrectedSymbol.Erase();
}
sal_uInt8 nForced = 0; // ==formula forces recalc even if cell is not visible
if( aFormula.GetChar(nSrcPos) == '=' )
{
nSrcPos++;
nForced++;
if ( bAutoCorrect )
aCorrectedFormula += '=';
}
if( aFormula.GetChar(nSrcPos) == '=' )
{
nSrcPos++;
nForced++;
if ( bAutoCorrect )
aCorrectedFormula += '=';
}
struct FunctionStack
{
OpCode eOp;
short nPar;
};
// FunctionStack only used if PODF!
bool bPODF = FormulaGrammar::isPODF( meGrammar);
const size_t nAlloc = 512;
FunctionStack aFuncs[ nAlloc ];
FunctionStack* pFunctionStack = (bPODF && rFormula.Len() > nAlloc ?
new FunctionStack[ rFormula.Len() ] : &aFuncs[0]);
pFunctionStack[0].eOp = ocNone;
pFunctionStack[0].nPar = 0;
size_t nFunction = 0;
short nBrackets = 0;
bool bInArray = false;
eLastOp = ocOpen;
while( NextNewToken( bInArray ) )
{
const OpCode eOp = pRawToken->GetOpCode();
if (eOp == ocSkip)
continue;
switch (eOp)
{
case ocOpen:
{
++nBrackets;
if (bPODF)
{
++nFunction;
pFunctionStack[ nFunction ].eOp = eLastOp;
pFunctionStack[ nFunction ].nPar = 0;
}
}
break;
case ocClose:
{
if( !nBrackets )
{
SetError( errPairExpected );
if ( bAutoCorrect )
{
bCorrected = true;
aCorrectedSymbol.Erase();
}
}
else
nBrackets--;
if (bPODF && nFunction)
--nFunction;
}
break;
case ocSep:
{
if (bPODF)
++pFunctionStack[ nFunction ].nPar;
}
break;
case ocArrayOpen:
{
if( bInArray )
SetError( errNestedArray );
else
bInArray = true;
// Don't count following column separator as parameter separator.
if (bPODF)
{
++nFunction;
pFunctionStack[ nFunction ].eOp = eOp;
pFunctionStack[ nFunction ].nPar = 0;
}
}
break;
case ocArrayClose:
{
if( bInArray )
{
bInArray = false;
}
else
{
SetError( errPairExpected );
if ( bAutoCorrect )
{
bCorrected = true;
aCorrectedSymbol.Erase();
}
}
if (bPODF && nFunction)
--nFunction;
}
default:
break;
}
if( (eLastOp == ocSep ||
eLastOp == ocArrayRowSep ||
eLastOp == ocArrayColSep ||
eLastOp == ocArrayOpen) &&
(eOp == ocSep ||
eOp == ocClose ||
eOp == ocArrayRowSep ||
eOp == ocArrayColSep ||
eOp == ocArrayClose) )
{
// FIXME: should we check for known functions with optional empty
// args so the correction dialog can do better?
if ( !static_cast<ScTokenArray*>(pArr)->Add( new FormulaMissingToken ) )
{
SetError(errCodeOverflow); break;
}
}
if (bPODF)
{
/* TODO: for now this is the only PODF adapter. If there were more,
* factor this out. */
// Insert ADDRESS() new empty parameter 4 if there is a 4th, now to be 5th.
if (eOp == ocSep &&
pFunctionStack[ nFunction ].eOp == ocAddress &&
pFunctionStack[ nFunction ].nPar == 3)
{
if (!static_cast<ScTokenArray*>(pArr)->Add( new FormulaToken( svSep,ocSep)) ||
!static_cast<ScTokenArray*>(pArr)->Add( new FormulaDoubleToken( 1.0)))
{
SetError(errCodeOverflow); break;
}
++pFunctionStack[ nFunction ].nPar;
}
}
FormulaToken* pNewToken = static_cast<ScTokenArray*>(pArr)->Add( pRawToken->CreateToken());
if (!pNewToken)
{
SetError(errCodeOverflow); break;
}
else if (eLastOp == ocRange && pNewToken->GetOpCode() == ocPush &&
pNewToken->GetType() == svSingleRef)
static_cast<ScTokenArray*>(pArr)->MergeRangeReference( aPos);
eLastOp = pRawToken->GetOpCode();
if ( bAutoCorrect )
aCorrectedFormula += aCorrectedSymbol;
}
if ( mbCloseBrackets )
{
if( bInArray )
{
FormulaByteToken aToken( ocArrayClose );
if( !pArr->AddToken( aToken ) )
{
SetError(errCodeOverflow);
}
else if ( bAutoCorrect )
aCorrectedFormula += mxSymbols->getSymbol(ocArrayClose);
}
FormulaByteToken aToken( ocClose );
while( nBrackets-- )
{
if( !pArr->AddToken( aToken ) )
{
SetError(errCodeOverflow); break;
}
if ( bAutoCorrect )
aCorrectedFormula += mxSymbols->getSymbol(ocClose);
}
}
if ( nForced >= 2 )
pArr->SetRecalcModeForced();
if (pFunctionStack != &aFuncs[0])
delete [] pFunctionStack;
// remember pArr, in case a subsequent CompileTokenArray() is executed.
ScTokenArray* pNew = new ScTokenArray( aArr );
pArr = pNew;
return pNew;
}
ScTokenArray* ScCompiler::CompileString( const String& rFormula, const String& rFormulaNmsp )
{
OSL_ENSURE( (GetGrammar() == FormulaGrammar::GRAM_EXTERNAL) || (rFormulaNmsp.Len() == 0),
"ScCompiler::CompileString - unexpected formula namespace for internal grammar" );
if( GetGrammar() == FormulaGrammar::GRAM_EXTERNAL ) try
{
ScFormulaParserPool& rParserPool = pDoc->GetFormulaParserPool();
uno::Reference< sheet::XFormulaParser > xParser( rParserPool.getFormulaParser( rFormulaNmsp ), uno::UNO_SET_THROW );
table::CellAddress aReferencePos;
ScUnoConversion::FillApiAddress( aReferencePos, aPos );
uno::Sequence< sheet::FormulaToken > aTokenSeq = xParser->parseFormula( rFormula, aReferencePos );
ScTokenArray aTokenArray;
if( ScTokenConversion::ConvertToTokenArray( *pDoc, aTokenArray, aTokenSeq ) )
{
// remember pArr, in case a subsequent CompileTokenArray() is executed.
ScTokenArray* pNew = new ScTokenArray( aTokenArray );
pArr = pNew;
return pNew;
}
}
catch( uno::Exception& )
{
}
// no success - fallback to some internal grammar and hope the best
return CompileString( rFormula );
}
ScRangeData* ScCompiler::GetRangeData( const FormulaToken& rToken ) const
{
ScRangeData* pRangeData = NULL;
bool bGlobal = rToken.IsGlobal();
if (bGlobal)
// global named range.
pRangeData = pDoc->GetRangeName()->findByIndex( rToken.GetIndex());
else
{
// sheet local named range.
const ScRangeName* pRN = pDoc->GetRangeName( aPos.Tab());
if (pRN)
pRangeData = pRN->findByIndex( rToken.GetIndex());
}
return pRangeData;
}
bool ScCompiler::HandleRange()
{
const ScRangeData* pRangeData = GetRangeData( *pToken);
if (pRangeData)
{
sal_uInt16 nErr = pRangeData->GetErrCode();
if( nErr )
SetError( errNoName );
else if ( !bCompileForFAP )
{
ScTokenArray* pNew;
// put named formula into parentheses.
// But only if there aren't any yet, parenthetical
// ocSep doesn't work, e.g. SUM((...;...))
// or if not directly between ocSep/parenthesis,
// e.g. SUM(...;(...;...)) no, SUM(...;(...)*3) yes,
// in short: if it isn't a self-contained expression.
FormulaToken* p1 = pArr->PeekPrevNoSpaces();
FormulaToken* p2 = pArr->PeekNextNoSpaces();
OpCode eOp1 = (p1 ? p1->GetOpCode() : static_cast<OpCode>( ocSep ) );
OpCode eOp2 = (p2 ? p2->GetOpCode() : static_cast<OpCode>( ocSep ) );
bool bBorder1 = (eOp1 == ocSep || eOp1 == ocOpen);
bool bBorder2 = (eOp2 == ocSep || eOp2 == ocClose);
bool bAddPair = !(bBorder1 && bBorder2);
if ( bAddPair )
{
pNew = new ScTokenArray();
pNew->AddOpCode( ocClose );
PushTokenArray( pNew, true );
pNew->Reset();
}
pNew = pRangeData->GetCode()->Clone();
PushTokenArray( pNew, true );
if( pRangeData->HasReferences() )
{
SetRelNameReference();
MoveRelWrap(pRangeData->GetMaxCol(), pRangeData->GetMaxRow());
}
pNew->Reset();
if ( bAddPair )
{
pNew = new ScTokenArray();
pNew->AddOpCode( ocOpen );
PushTokenArray( pNew, true );
pNew->Reset();
}
return GetToken();
}
}
else
SetError(errNoName);
return true;
}
// -----------------------------------------------------------------------------
bool ScCompiler::HandleExternalReference(const FormulaToken& _aToken)
{
// Handle external range names.
switch (_aToken.GetType())
{
case svExternalSingleRef:
case svExternalDoubleRef:
pArr->IncrementRefs();
break;
case svExternalName:
{
ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
const OUString* pFile = pRefMgr->getExternalFileName(_aToken.GetIndex());
if (!pFile)
{
SetError(errNoName);
return true;
}
const String& rName = _aToken.GetString();
ScExternalRefCache::TokenArrayRef xNew = pRefMgr->getRangeNameTokens(
_aToken.GetIndex(), rName, &aPos);
if (!xNew)
{
SetError(errNoName);
return true;
}
ScTokenArray* pNew = xNew->Clone();
PushTokenArray( pNew, true);
if (pNew->GetNextReference() != NULL)
{
SetRelNameReference();
MoveRelWrap(MAXCOL, MAXROW);
}
pNew->Reset();
return GetToken();
}
default:
OSL_FAIL("Wrong type for external reference!");
return false;
}
return true;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Append token to RPN code
//---------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//---------------------------------------------------------------------------
// RPN creation by recursion
//---------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool ScCompiler::HasModifiedRange()
{
pArr->Reset();
for ( FormulaToken* t = pArr->Next(); t; t = pArr->Next() )
{
OpCode eOpCode = t->GetOpCode();
if ( eOpCode == ocName )
{
const ScRangeData* pRangeData = GetRangeData( *t);
if (pRangeData && pRangeData->IsModified())
return true;
}
else if ( eOpCode == ocDBArea )
{
ScDBData* pDBData = pDoc->GetDBCollection()->getNamedDBs().findByIndex(t->GetIndex());
if (pDBData && pDBData->IsModified())
return true;
}
}
return false;
}
//---------------------------------------------------------------------------
template< typename T, typename S >
S lcl_adjval( S& n, T pos, T max, bool bRel )
{
max++;
if( bRel )
n = sal::static_int_cast<S>( n + pos );
if( n < 0 )
n = sal::static_int_cast<S>( n + max );
else if( n >= max )
n = sal::static_int_cast<S>( n - max );
if( bRel )
n = sal::static_int_cast<S>( n - pos );
return n;
}
// reference of named range with relative references
void ScCompiler::SetRelNameReference()
{
pArr->Reset();
for( ScToken* t = static_cast<ScToken*>(pArr->GetNextReference()); t;
t = static_cast<ScToken*>(pArr->GetNextReference()) )
{
ScSingleRefData& rRef1 = t->GetSingleRef();
if ( rRef1.IsColRel() || rRef1.IsRowRel() || rRef1.IsTabRel() )
rRef1.SetRelName( true );
if ( t->GetType() == svDoubleRef )
{
ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
if ( rRef2.IsColRel() || rRef2.IsRowRel() || rRef2.IsTabRel() )
rRef2.SetRelName( true );
}
}
}
// Wrap-adjust relative references of a RangeName to current position,
// don't call for other token arrays!
void ScCompiler::MoveRelWrap( SCCOL nMaxCol, SCROW nMaxRow )
{
pArr->Reset();
for( ScToken* t = static_cast<ScToken*>(pArr->GetNextReference()); t;
t = static_cast<ScToken*>(pArr->GetNextReference()) )
{
if ( t->GetType() == svSingleRef || t->GetType() == svExternalSingleRef )
ScRefUpdate::MoveRelWrap( pDoc, aPos, nMaxCol, nMaxRow, SingleDoubleRefModifier( t->GetSingleRef() ).Ref() );
else
ScRefUpdate::MoveRelWrap( pDoc, aPos, nMaxCol, nMaxRow, t->GetDoubleRef() );
}
}
// Wrap-adjust relative references of a RangeName to current position,
// don't call for other token arrays!
void ScCompiler::MoveRelWrap( ScTokenArray& rArr, ScDocument* pDoc, const ScAddress& rPos,
SCCOL nMaxCol, SCROW nMaxRow )
{
rArr.Reset();
for( ScToken* t = static_cast<ScToken*>(rArr.GetNextReference()); t;
t = static_cast<ScToken*>(rArr.GetNextReference()) )
{
if ( t->GetType() == svSingleRef || t->GetType() == svExternalSingleRef )
ScRefUpdate::MoveRelWrap( pDoc, rPos, nMaxCol, nMaxRow, SingleDoubleRefModifier( t->GetSingleRef() ).Ref() );
else
ScRefUpdate::MoveRelWrap( pDoc, rPos, nMaxCol, nMaxRow, t->GetDoubleRef() );
}
}
ScRangeData* ScCompiler::UpdateReference(UpdateRefMode eUpdateRefMode,
const ScAddress& rOldPos, const ScRange& r,
SCsCOL nDx, SCsROW nDy, SCsTAB nDz,
bool& rChanged, bool& rRefSizeChanged )
{
rChanged = rRefSizeChanged = false;
if ( eUpdateRefMode == URM_COPY )
{ // Normally nothing has to be done here since RelRefs are used, also
// SharedFormulas don't need any special handling, except if they
// wrapped around sheet borders.
// But ColRowName tokens pointing to a ColRow header which was
// copied along with this formula need to be updated to point to the
// copied header instead of the old position's new intersection.
ScToken* t;
pArr->Reset();
while( (t = static_cast<ScToken*>(pArr->GetNextColRowName())) != NULL )
{
ScSingleRefData& rRef = t->GetSingleRef();
rRef.CalcAbsIfRel( rOldPos );
ScAddress aNewRef( rRef.nCol + nDx, rRef.nRow + nDy, rRef.nTab + nDz );
if ( r.In( aNewRef ) )
{ // yes, this is URM_MOVE
if ( ScRefUpdate::Update( pDoc, URM_MOVE, aPos,
r, nDx, nDy, nDz,
SingleDoubleRefModifier( rRef ).Ref() )
!= UR_NOTHING
)
rChanged = true;
}
}
// Check for SharedFormulas.
ScRangeData* pRangeData = NULL;
pArr->Reset();
for( FormulaToken* j = pArr->GetNextName(); j && !pRangeData;
j = pArr->GetNextName() )
{
if( j->GetOpCode() == ocName )
{
ScRangeData* pName = GetRangeData( *j);
if (pName && pName->HasType(RT_SHARED))
pRangeData = pName;
}
}
// Check SharedFormulas for wraps.
if (pRangeData)
{
ScRangeData* pName = pRangeData;
pRangeData = NULL;
pArr->Reset();
for( t = static_cast<ScToken*>(pArr->GetNextReferenceRPN()); t && !pRangeData;
t = static_cast<ScToken*>(pArr->GetNextReferenceRPN()) )
{
bool bRelName = (t->GetType() == svSingleRef ?
t->GetSingleRef().IsRelName() :
(t->GetDoubleRef().Ref1.IsRelName() ||
t->GetDoubleRef().Ref2.IsRelName()));
if (bRelName)
{
t->CalcAbsIfRel( rOldPos);
bool bValid = (t->GetType() == svSingleRef ?
t->GetSingleRef().Valid() :
t->GetDoubleRef().Valid());
// If the reference isn't valid, copying the formula
// wrapped it. Replace SharedFormula.
if (!bValid)
{
pRangeData = pName;
rChanged = true;
}
}
}
}
return pRangeData;
}
else
{
/*
* Set SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE to 1 if we wanted to preserve as
* many shared formulas as possible instead of replacing them with direct code.
* Note that this may produce shared formula usage Excel doesn't understand,
* which would have to be adapted for in the export filter. Advisable as a long
* term goal, since it could decrease memory footprint.
*/
#define SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE 0
ScRangeData* pRangeData = NULL;
ScToken* t;
pArr->Reset();
while( (t = static_cast<ScToken*>(pArr->GetNextReferenceOrName())) != NULL )
{
if( t->GetOpCode() == ocName )
{
ScRangeData* pName = GetRangeData( *t);
if (pName && pName->HasType(RT_SHAREDMOD))
{
pRangeData = pName; // maybe need a replacement of shared with own code
#if ! SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
rChanged = true;
#endif
}
}
else if( t->GetType() != svIndex ) // it may be a DB area!!!
{
t->CalcAbsIfRel( rOldPos );
switch (t->GetType())
{
case svExternalSingleRef:
case svExternalDoubleRef:
// External references never change their positioning
// nor point to parts that will be removed or expanded.
// In fact, calling ScRefUpdate::Update() for URM_MOVE
// may have negative side effects. Simply adapt
// relative references to the new position.
t->CalcRelFromAbs( aPos);
break;
case svSingleRef:
{
if ( ScRefUpdate::Update( pDoc, eUpdateRefMode,
aPos, r, nDx, nDy, nDz,
SingleDoubleRefModifier(
t->GetSingleRef()).Ref())
!= UR_NOTHING)
rChanged = true;
}
break;
default:
{
ScComplexRefData& rRef = t->GetDoubleRef();
SCCOL nCols = rRef.Ref2.nCol - rRef.Ref1.nCol;
SCROW nRows = rRef.Ref2.nRow - rRef.Ref1.nRow;
SCTAB nTabs = rRef.Ref2.nTab - rRef.Ref1.nTab;
if ( ScRefUpdate::Update( pDoc, eUpdateRefMode,
aPos, r, nDx, nDy, nDz,
t->GetDoubleRef()) != UR_NOTHING)
{
rChanged = true;
if (rRef.Ref2.nCol - rRef.Ref1.nCol != nCols ||
rRef.Ref2.nRow - rRef.Ref1.nRow != nRows ||
rRef.Ref2.nTab - rRef.Ref1.nTab != nTabs)
rRefSizeChanged = true;
}
}
}
}
}
#if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
bool bEasyShared, bPosInRange;
if ( !pRangeData )
bEasyShared = bPosInRange = false;
else
{
bEasyShared = true;
bPosInRange = r.In( eUpdateRefMode == URM_MOVE ? aPos : rOldPos );
}
#endif
pArr->Reset();
while ( (t = static_cast<ScToken*>(pArr->GetNextReferenceRPN())) != NULL )
{
if ( t->GetRef() != 1 )
{
#if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
bEasyShared = false;
#endif
}
else
{ // if nRefCnt>1 it's already updated in token code
if ( t->GetType() == svSingleRef )
{
ScSingleRefData& rRef = t->GetSingleRef();
SingleDoubleRefModifier aMod( rRef );
if ( rRef.IsRelName() )
{
ScRefUpdate::MoveRelWrap( pDoc, aPos, MAXCOL, MAXROW, aMod.Ref() );
rChanged = true;
}
else
{
aMod.Ref().CalcAbsIfRel( rOldPos );
if ( ScRefUpdate::Update( pDoc, eUpdateRefMode, aPos,
r, nDx, nDy, nDz, aMod.Ref() )
!= UR_NOTHING
)
rChanged = true;
}
#if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
if ( bEasyShared )
{
const ScSingleRefData& rSRD = aMod.Ref().Ref1;
ScAddress aRef( rSRD.nCol, rSRD.nRow, rSRD.nTab );
if ( r.In( aRef ) != bPosInRange )
bEasyShared = false;
}
#endif
}
else
{
ScComplexRefData& rRef = t->GetDoubleRef();
SCCOL nCols = rRef.Ref2.nCol - rRef.Ref1.nCol;
SCROW nRows = rRef.Ref2.nRow - rRef.Ref1.nRow;
SCTAB nTabs = rRef.Ref2.nTab - rRef.Ref1.nTab;
if ( rRef.Ref1.IsRelName() || rRef.Ref2.IsRelName() )
{
ScRefUpdate::MoveRelWrap( pDoc, aPos, MAXCOL, MAXROW, rRef );
rChanged = true;
}
else
{
if ( ScRefUpdate::Update( pDoc, eUpdateRefMode, aPos,
r, nDx, nDy, nDz, rRef )
!= UR_NOTHING
)
{
rChanged = true;
if (rRef.Ref2.nCol - rRef.Ref1.nCol != nCols ||
rRef.Ref2.nRow - rRef.Ref1.nRow != nRows ||
rRef.Ref2.nTab - rRef.Ref1.nTab != nTabs)
{
rRefSizeChanged = true;
#if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
bEasyShared = false;
#endif
}
}
}
#if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
if ( bEasyShared )
{
ScRange aRef( rRef.Ref1.nCol, rRef.Ref1.nRow,
rRef.Ref1.nTab, rRef.Ref2.nCol, rRef.Ref2.nRow,
rRef.Ref2.nTab );
if ( r.In( aRef ) != bPosInRange )
bEasyShared = false;
}
#endif
}
}
}
#if SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
if ( pRangeData )
{
if ( bEasyShared )
pRangeData = 0;
else
rChanged = true;
}
#endif
#undef SC_PRESERVE_SHARED_FORMULAS_IF_POSSIBLE
return pRangeData;
}
}
bool ScCompiler::UpdateNameReference(UpdateRefMode eUpdateRefMode,
const ScRange& r,
SCsCOL nDx, SCsROW nDy, SCsTAB nDz,
bool& rChanged, bool bSharedFormula, bool bLocal)
{
bool bRelRef = false; // set if relative reference
rChanged = false;
pArr->Reset();
ScToken* t;
while ( (t = static_cast<ScToken*>(pArr->GetNextReference())) != NULL )
{
SingleDoubleRefModifier aMod( *t );
ScComplexRefData& rRef = aMod.Ref();
bRelRef = rRef.Ref1.IsColRel() || rRef.Ref1.IsRowRel() ||
rRef.Ref1.IsTabRel();
if (!bRelRef && t->GetType() == svDoubleRef)
bRelRef = rRef.Ref2.IsColRel() || rRef.Ref2.IsRowRel() ||
rRef.Ref2.IsTabRel();
bool bUpdate = !rRef.Ref1.IsColRel() || !rRef.Ref1.IsRowRel() ||
!rRef.Ref1.IsTabRel();
if (!bUpdate && t->GetType() == svDoubleRef)
bUpdate = !rRef.Ref2.IsColRel() || !rRef.Ref2.IsRowRel() ||
!rRef.Ref2.IsTabRel();
if (!bSharedFormula && !bLocal)
{
// We cannot update names with sheet-relative references, they may
// be used on other sheets as well and the resulting reference
// would be wrong. This is a dilemma if col/row would need to be
// updated for the current usage.
bUpdate = bUpdate && !rRef.Ref1.IsTabRel() && !rRef.Ref2.IsTabRel();
}
if (bUpdate)
{
rRef.CalcAbsIfRel( aPos);
if (ScRefUpdate::Update( pDoc, eUpdateRefMode, aPos, r,
nDx, nDy, nDz, rRef, ScRefUpdate::ABSOLUTE)
!= UR_NOTHING )
rChanged = true;
}
}
return bRelRef;
}
void ScCompiler::UpdateSharedFormulaReference( UpdateRefMode eUpdateRefMode,
const ScAddress& rOldPos, const ScRange& r,
SCsCOL nDx, SCsROW nDy, SCsTAB nDz )
{
if ( eUpdateRefMode == URM_COPY )
return ;
else
{
ScToken* t;
pArr->Reset();
while ( (t = static_cast<ScToken*>(pArr->GetNextReference())) != NULL )
{
if( t->GetType() != svIndex ) // it may be a DB area!!!
{
t->CalcAbsIfRel( rOldPos );
// Absolute references have been already adjusted in the named
// shared formula itself prior to breaking the shared formula
// and calling this function. Don't readjust them again.
SingleDoubleRefModifier aMod( *t );
ScComplexRefData& rRef = aMod.Ref();
ScComplexRefData aBkp = rRef;
ScRefUpdate::Update( pDoc, eUpdateRefMode, aPos,
r, nDx, nDy, nDz, rRef );
// restore absolute parts
if ( !aBkp.Ref1.IsColRel() )
{
rRef.Ref1.nCol = aBkp.Ref1.nCol;
rRef.Ref1.nRelCol = aBkp.Ref1.nRelCol;
rRef.Ref1.SetColDeleted( aBkp.Ref1.IsColDeleted() );
}
if ( !aBkp.Ref1.IsRowRel() )
{
rRef.Ref1.nRow = aBkp.Ref1.nRow;
rRef.Ref1.nRelRow = aBkp.Ref1.nRelRow;
rRef.Ref1.SetRowDeleted( aBkp.Ref1.IsRowDeleted() );
}
if ( !aBkp.Ref1.IsTabRel() )
{
rRef.Ref1.nTab = aBkp.Ref1.nTab;
rRef.Ref1.nRelTab = aBkp.Ref1.nRelTab;
rRef.Ref1.SetTabDeleted( aBkp.Ref1.IsTabDeleted() );
}
if ( t->GetType() == svDoubleRef )
{
if ( !aBkp.Ref2.IsColRel() )
{
rRef.Ref2.nCol = aBkp.Ref2.nCol;
rRef.Ref2.nRelCol = aBkp.Ref2.nRelCol;
rRef.Ref2.SetColDeleted( aBkp.Ref2.IsColDeleted() );
}
if ( !aBkp.Ref2.IsRowRel() )
{
rRef.Ref2.nRow = aBkp.Ref2.nRow;
rRef.Ref2.nRelRow = aBkp.Ref2.nRelRow;
rRef.Ref2.SetRowDeleted( aBkp.Ref2.IsRowDeleted() );
}
if ( !aBkp.Ref2.IsTabRel() )
{
rRef.Ref2.nTab = aBkp.Ref2.nTab;
rRef.Ref2.nRelTab = aBkp.Ref2.nRelTab;
rRef.Ref2.SetTabDeleted( aBkp.Ref2.IsTabDeleted() );
}
}
}
}
}
}
ScRangeData* ScCompiler::UpdateInsertTab( SCTAB nTable, bool bIsName , SCTAB nNewSheets)
{
ScRangeData* pRangeData = NULL;
SCTAB nPosTab = aPos.Tab(); // _after_ incremented!
SCTAB nOldPosTab = ((nPosTab > nTable) ? (nPosTab - nNewSheets) : nPosTab);
bool bIsRel = false;
ScToken* t;
pArr->Reset();
if (bIsName)
t = static_cast<ScToken*>(pArr->GetNextReference());
else
t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
while( t )
{
if( t->GetOpCode() == ocName )
{
if (!bIsName)
{
ScRangeData* pName = GetRangeData( *t);
if (pName && pName->HasType(RT_SHAREDMOD))
pRangeData = pName;
}
}
else if( t->GetType() != svIndex ) // it may be a DB area!!!
{
if ( !(bIsName && t->GetSingleRef().IsTabRel()) )
{ // of names only adjust absolute references
ScSingleRefData& rRef = t->GetSingleRef();
if ( rRef.IsTabRel() )
{
rRef.nTab = rRef.nRelTab + nOldPosTab;
if ( rRef.nTab < 0 )
rRef.nTab = sal::static_int_cast<SCsTAB>( rRef.nTab + pDoc->GetTableCount() ); // was a wrap
}
if (nTable <= rRef.nTab)
rRef.nTab += nNewSheets;
rRef.nRelTab = rRef.nTab - nPosTab;
}
else
bIsRel = true;
if ( t->GetType() == svDoubleRef )
{
if ( !(bIsName && t->GetDoubleRef().Ref2.IsTabRel()) )
{ // of names only adjust absolute references
ScSingleRefData& rRef = t->GetDoubleRef().Ref2;
if ( rRef.IsTabRel() )
{
rRef.nTab = rRef.nRelTab + nOldPosTab;
if ( rRef.nTab < 0 )
rRef.nTab = sal::static_int_cast<SCsTAB>( rRef.nTab + pDoc->GetTableCount() ); // was a wrap
}
if (nTable <= rRef.nTab)
rRef.nTab += nNewSheets;
rRef.nRelTab = rRef.nTab - nPosTab;
}
else
bIsRel = true;
}
if ( bIsName && bIsRel )
pRangeData = (ScRangeData*) this; // not dereferenced in rangenam
}
if (bIsName)
t = static_cast<ScToken*>(pArr->GetNextReference());
else
t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
}
if ( !bIsName )
{
pArr->Reset();
while ( (t = static_cast<ScToken*>(pArr->GetNextReferenceRPN())) != NULL )
{
if ( t->GetRef() == 1 )
{
ScSingleRefData& rRef1 = t->GetSingleRef();
if ( !(rRef1.IsRelName() && rRef1.IsTabRel()) )
{ // of names only adjust absolute references
if ( rRef1.IsTabRel() )
{
rRef1.nTab = rRef1.nRelTab + nOldPosTab;
if ( rRef1.nTab < 0 )
rRef1.nTab = sal::static_int_cast<SCsTAB>( rRef1.nTab + pDoc->GetTableCount() ); // was a wrap
}
if (nTable <= rRef1.nTab)
rRef1.nTab += nNewSheets;
rRef1.nRelTab = rRef1.nTab - nPosTab;
}
if ( t->GetType() == svDoubleRef )
{
ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
if ( !(rRef2.IsRelName() && rRef2.IsTabRel()) )
{ // of names only adjust absolute references
if ( rRef2.IsTabRel() )
{
rRef2.nTab = rRef2.nRelTab + nOldPosTab;
if ( rRef2.nTab < 0 )
rRef2.nTab = sal::static_int_cast<SCsTAB>( rRef2.nTab + pDoc->GetTableCount() ); // was a wrap
}
if (nTable <= rRef2.nTab)
rRef2.nTab += nNewSheets;
rRef2.nRelTab = rRef2.nTab - nPosTab;
}
}
}
}
}
return pRangeData;
}
ScRangeData* ScCompiler::UpdateDeleteTab(SCTAB nTable, bool /* bIsMove */, bool bIsName,
bool& rChanged, SCTAB nSheets)
{
ScRangeData* pRangeData = NULL;
SCTAB nTab, nTab2;
SCTAB nPosTab = aPos.Tab(); // _after_ decremented!
SCTAB nOldPosTab = ((nPosTab >= nTable) ? (nPosTab + nSheets) : nPosTab);
rChanged = false;
bool bIsRel = false;
ScToken* t;
pArr->Reset();
if (bIsName)
t = static_cast<ScToken*>(pArr->GetNextReference());
else
t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
while( t )
{
if( t->GetOpCode() == ocName )
{
if (!bIsName)
{
ScRangeData* pName = GetRangeData( *t);
if (pName && pName->HasType(RT_SHAREDMOD))
pRangeData = pName;
}
rChanged = true;
}
else if( t->GetType() != svIndex ) // it may be a DB area!!!
{
if ( !(bIsName && t->GetSingleRef().IsTabRel()) )
{ // of names only adjust absolute references
ScSingleRefData& rRef = t->GetSingleRef();
if ( rRef.IsTabRel() )
nTab = rRef.nTab = rRef.nRelTab + nOldPosTab;
else
nTab = rRef.nTab;
if ( nTable < nTab )
{
rRef.nTab = nTab - nSheets;
rChanged = true;
}
else if ( nTable == nTab )
{
if ( t->GetType() == svDoubleRef )
{
ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
if ( rRef2.IsTabRel() )
nTab2 = rRef2.nRelTab + nOldPosTab;
else
nTab2 = rRef2.nTab;
if ( nTab == nTab2
|| (nTab+nSheets) >= pDoc->GetTableCount() )
{
rRef.nTab = MAXTAB+1;
rRef.SetTabDeleted( true );
}
// else: nTab later points to what's nTable+1 now
// => area shrunk
}
else
{
rRef.nTab = MAXTAB+1;
rRef.SetTabDeleted( true );
}
rChanged = true;
}
rRef.nRelTab = rRef.nTab - nPosTab;
}
else
bIsRel = true;
if ( t->GetType() == svDoubleRef )
{
if ( !(bIsName && t->GetDoubleRef().Ref2.IsTabRel()) )
{ // of names only adjust absolute references
ScSingleRefData& rRef = t->GetDoubleRef().Ref2;
if ( rRef.IsTabRel() )
nTab = rRef.nTab = rRef.nRelTab + nOldPosTab;
else
nTab = rRef.nTab;
if ( nTable < nTab )
{
rRef.nTab = nTab - nSheets;
rChanged = true;
}
else if ( nTable == nTab )
{
if ( !t->GetDoubleRef().Ref1.IsTabDeleted() )
rRef.nTab = nTab - nSheets; // shrink area
else
{
rRef.nTab = MAXTAB+1;
rRef.SetTabDeleted( true );
}
rChanged = true;
}
rRef.nRelTab = rRef.nTab - nPosTab;
}
else
bIsRel = true;
}
if ( bIsName && bIsRel )
pRangeData = (ScRangeData*) this; // not dereferenced in rangenam
}
if (bIsName)
t = static_cast<ScToken*>(pArr->GetNextReference());
else
t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
}
if ( !bIsName )
{
pArr->Reset();
while ( (t = static_cast<ScToken*>(pArr->GetNextReferenceRPN())) != NULL )
{
if ( t->GetRef() == 1 )
{
ScSingleRefData& rRef1 = t->GetSingleRef();
if ( !(rRef1.IsRelName() && rRef1.IsTabRel()) )
{ // of names only adjust absolute references
if ( rRef1.IsTabRel() )
nTab = rRef1.nTab = rRef1.nRelTab + nOldPosTab;
else
nTab = rRef1.nTab;
if ( nTable < nTab )
{
rRef1.nTab = nTab - nSheets;
rChanged = true;
}
else if ( nTable == nTab )
{
if ( t->GetType() == svDoubleRef )
{
ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
if ( rRef2.IsTabRel() )
nTab2 = rRef2.nRelTab + nOldPosTab;
else
nTab2 = rRef2.nTab;
if ( nTab == nTab2
|| (nTab+1) >= pDoc->GetTableCount() )
{
rRef1.nTab = MAXTAB+1;
rRef1.SetTabDeleted( true );
}
// else: nTab later points to what's nTable+1 now
// => area shrunk
}
else
{
rRef1.nTab = MAXTAB+1;
rRef1.SetTabDeleted( true );
}
rChanged = true;
}
rRef1.nRelTab = rRef1.nTab - nPosTab;
}
if ( t->GetType() == svDoubleRef )
{
ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
if ( !(rRef2.IsRelName() && rRef2.IsTabRel()) )
{ // of names only adjust absolute references
if ( rRef2.IsTabRel() )
nTab = rRef2.nTab = rRef2.nRelTab + nOldPosTab;
else
nTab = rRef2.nTab;
if ( nTable < nTab )
{
rRef2.nTab = nTab - nSheets;
rChanged = true;
}
else if ( nTable == nTab )
{
if ( !rRef1.IsTabDeleted() )
rRef2.nTab = nTab - nSheets; // shrink area
else
{
rRef2.nTab = MAXTAB+1;
rRef2.SetTabDeleted( true );
}
rChanged = true;
}
rRef2.nRelTab = rRef2.nTab - nPosTab;
}
}
}
}
}
return pRangeData;
}
// aPos.Tab() must be already adjusted!
ScRangeData* ScCompiler::UpdateMoveTab( SCTAB nOldTab, SCTAB nNewTab,
bool bIsName )
{
ScRangeData* pRangeData = NULL;
SCsTAB nTab;
SCTAB nStart, nEnd;
short nDir; // direction in which others move
if ( nOldTab < nNewTab )
{
nDir = -1;
nStart = nOldTab;
nEnd = nNewTab;
}
else
{
nDir = 1;
nStart = nNewTab;
nEnd = nOldTab;
}
SCTAB nPosTab = aPos.Tab(); // current sheet
SCTAB nOldPosTab; // previously it was this one
if ( nPosTab == nNewTab )
nOldPosTab = nOldTab; // look, it's me!
else if ( nPosTab < nStart || nEnd < nPosTab )
nOldPosTab = nPosTab; // wasn't moved
else
nOldPosTab = nPosTab - nDir; // moved by one
bool bIsRel = false;
ScToken* t;
pArr->Reset();
if (bIsName)
t = static_cast<ScToken*>(pArr->GetNextReference());
else
t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
while( t )
{
if( t->GetOpCode() == ocName )
{
if (!bIsName)
{
ScRangeData* pName = GetRangeData( *t);
if (pName && pName->HasType(RT_SHAREDMOD))
pRangeData = pName;
}
}
else if( t->GetType() != svIndex ) // it may be a DB area!!!
{
ScSingleRefData& rRef1 = t->GetSingleRef();
if ( !(bIsName && rRef1.IsTabRel()) )
{ // of names only adjust absolute references
if ( rRef1.IsTabRel() )
nTab = rRef1.nRelTab + nOldPosTab;
else
nTab = rRef1.nTab;
if ( nTab == nOldTab )
rRef1.nTab = nNewTab;
else if ( nStart <= nTab && nTab <= nEnd )
rRef1.nTab = nTab + nDir;
rRef1.nRelTab = rRef1.nTab - nPosTab;
}
else
bIsRel = true;
if ( t->GetType() == svDoubleRef )
{
ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
if ( !(bIsName && rRef2.IsTabRel()) )
{ // of names only adjust absolute references
if ( rRef2.IsTabRel() )
nTab = rRef2.nRelTab + nOldPosTab;
else
nTab = rRef2.nTab;
if ( nTab == nOldTab )
rRef2.nTab = nNewTab;
else if ( nStart <= nTab && nTab <= nEnd )
rRef2.nTab = nTab + nDir;
rRef2.nRelTab = rRef2.nTab - nPosTab;
}
else
bIsRel = true;
SCsTAB nTab1, nTab2;
if ( rRef1.IsTabRel() )
nTab1 = rRef1.nRelTab + nPosTab;
else
nTab1 = rRef1.nTab;
if ( rRef2.IsTabRel() )
nTab2 = rRef2.nRelTab + nPosTab;
else
nTab2 = rRef1.nTab;
if ( nTab2 < nTab1 )
{ // PutInOrder
rRef1.nTab = nTab2;
rRef2.nTab = nTab1;
rRef1.nRelTab = rRef1.nTab - nPosTab;
rRef2.nRelTab = rRef2.nTab - nPosTab;
}
}
if ( bIsName && bIsRel )
pRangeData = (ScRangeData*) this; // not dereferenced in rangenam
}
if (bIsName)
t = static_cast<ScToken*>(pArr->GetNextReference());
else
t = static_cast<ScToken*>(pArr->GetNextReferenceOrName());
}
if ( !bIsName )
{
SCsTAB nMaxTabMod = (SCsTAB) pDoc->GetTableCount();
pArr->Reset();
while ( (t = static_cast<ScToken*>(pArr->GetNextReferenceRPN())) != NULL )
{
if ( t->GetRef() == 1 )
{
ScSingleRefData& rRef1 = t->GetSingleRef();
if ( rRef1.IsRelName() && rRef1.IsTabRel() )
{ // possibly wrap RelName, like lcl_MoveItWrap in refupdat.cxx
nTab = rRef1.nRelTab + nPosTab;
if ( nTab < 0 )
nTab = sal::static_int_cast<SCsTAB>( nTab + nMaxTabMod );
else if ( nTab > nMaxTab )
nTab = sal::static_int_cast<SCsTAB>( nTab - nMaxTabMod );
rRef1.nRelTab = nTab - nPosTab;
}
else
{
if ( rRef1.IsTabRel() )
nTab = rRef1.nRelTab + nOldPosTab;
else
nTab = rRef1.nTab;
if ( nTab == nOldTab )
rRef1.nTab = nNewTab;
else if ( nStart <= nTab && nTab <= nEnd )
rRef1.nTab = nTab + nDir;
rRef1.nRelTab = rRef1.nTab - nPosTab;
}
if( t->GetType() == svDoubleRef )
{
ScSingleRefData& rRef2 = t->GetDoubleRef().Ref2;
if ( rRef2.IsRelName() && rRef2.IsTabRel() )
{ // possibly wrap RelName, like lcl_MoveItWrap in refupdat.cxx
nTab = rRef2.nRelTab + nPosTab;
if ( nTab < 0 )
nTab = sal::static_int_cast<SCsTAB>( nTab + nMaxTabMod );
else if ( nTab > nMaxTab )
nTab = sal::static_int_cast<SCsTAB>( nTab - nMaxTabMod );
rRef2.nRelTab = nTab - nPosTab;
}
else
{
if ( rRef2.IsTabRel() )
nTab = rRef2.nRelTab + nOldPosTab;
else
nTab = rRef2.nTab;
if ( nTab == nOldTab )
rRef2.nTab = nNewTab;
else if ( nStart <= nTab && nTab <= nEnd )
rRef2.nTab = nTab + nDir;
rRef2.nRelTab = rRef2.nTab - nPosTab;
}
SCsTAB nTab1, nTab2;
if ( rRef1.IsTabRel() )
nTab1 = rRef1.nRelTab + nPosTab;
else
nTab1 = rRef1.nTab;
if ( rRef2.IsTabRel() )
nTab2 = rRef2.nRelTab + nPosTab;
else
nTab2 = rRef1.nTab;
if ( nTab2 < nTab1 )
{ // PutInOrder
rRef1.nTab = nTab2;
rRef2.nTab = nTab1;
rRef1.nRelTab = rRef1.nTab - nPosTab;
rRef2.nRelTab = rRef2.nTab - nPosTab;
}
}
}
}
}
return pRangeData;
}
void ScCompiler::CreateStringFromExternal(rtl::OUStringBuffer& rBuffer, FormulaToken* pTokenP)
{
FormulaToken* t = pTokenP;
ScExternalRefManager* pRefMgr = pDoc->GetExternalRefManager();
switch (t->GetType())
{
case svExternalName:
{
const OUString *pStr = pRefMgr->getExternalFileName(t->GetIndex());
OUString aFileName = pStr ? *pStr : OUString(ScGlobal::GetRscString(STR_NO_NAME_REF));
rBuffer.append(pConv->makeExternalNameStr( aFileName, t->GetString()));
}
break;
case svExternalSingleRef:
pConv->makeExternalRefStr(
rBuffer, *this, t->GetIndex(), t->GetString(), static_cast<ScToken*>(t)->GetSingleRef(), pRefMgr);
break;
case svExternalDoubleRef:
pConv->makeExternalRefStr(
rBuffer, *this, t->GetIndex(), t->GetString(), static_cast<ScToken*>(t)->GetDoubleRef(), pRefMgr);
break;
default:
// warning, not error, otherwise we may end up with a never
// ending message box loop if this was the cursor cell to be redrawn.
OSL_FAIL("ScCompiler::CreateStringFromToken: unknown type of ocExternalRef");
}
}
void ScCompiler::CreateStringFromMatrix( rtl::OUStringBuffer& rBuffer,
FormulaToken* pTokenP)
{
const ScMatrix* pMatrix = static_cast<ScToken*>(pTokenP)->GetMatrix();
SCSIZE nC, nMaxC, nR, nMaxR;
pMatrix->GetDimensions( nMaxC, nMaxR);
rBuffer.append( mxSymbols->getSymbol(ocArrayOpen) );
for( nR = 0 ; nR < nMaxR ; nR++)
{
if( nR > 0)
{
rBuffer.append( mxSymbols->getSymbol(ocArrayRowSep) );
}
for( nC = 0 ; nC < nMaxC ; nC++)
{
if( nC > 0)
{
rBuffer.append( mxSymbols->getSymbol(ocArrayColSep) );
}
if( pMatrix->IsValue( nC, nR ) )
{
if (pMatrix->IsBoolean(nC, nR))
AppendBoolean(rBuffer, pMatrix->GetDouble(nC, nR) != 0.0);
else
{
sal_uInt16 nErr = pMatrix->GetError(nC, nR);
if (nErr)
rBuffer.append(ScGlobal::GetErrorString(nErr));
else
AppendDouble(rBuffer, pMatrix->GetDouble(nC, nR));
}
}
else if( pMatrix->IsEmpty( nC, nR ) )
;
else if( pMatrix->IsString( nC, nR ) )
AppendString( rBuffer, pMatrix->GetString( nC, nR ) );
}
}
rBuffer.append( mxSymbols->getSymbol(ocArrayClose) );
}
void ScCompiler::CreateStringFromSingleRef(rtl::OUStringBuffer& rBuffer,FormulaToken* _pTokenP)
{
const OpCode eOp = _pTokenP->GetOpCode();
ScSingleRefData& rRef = static_cast<ScToken*>(_pTokenP)->GetSingleRef();
ScComplexRefData aRef;
aRef.Ref1 = aRef.Ref2 = rRef;
if ( eOp == ocColRowName )
{
rRef.CalcAbsIfRel( aPos );
if ( pDoc->HasStringData( rRef.nCol, rRef.nRow, rRef.nTab ) )
{
String aStr;
pDoc->GetString( rRef.nCol, rRef.nRow, rRef.nTab, aStr );
EnQuote( aStr );
rBuffer.append(aStr);
}
else
{
rBuffer.append(ScGlobal::GetRscString(STR_NO_NAME_REF));
pConv->MakeRefStr (rBuffer, *this, aRef, true );
}
}
else
pConv->MakeRefStr( rBuffer, *this, aRef, true );
}
// -----------------------------------------------------------------------------
void ScCompiler::CreateStringFromDoubleRef(rtl::OUStringBuffer& rBuffer,FormulaToken* _pTokenP)
{
pConv->MakeRefStr( rBuffer, *this, static_cast<ScToken*>(_pTokenP)->GetDoubleRef(), false );
}
// -----------------------------------------------------------------------------
void ScCompiler::CreateStringFromIndex(rtl::OUStringBuffer& rBuffer,FormulaToken* _pTokenP)
{
const OpCode eOp = _pTokenP->GetOpCode();
rtl::OUStringBuffer aBuffer;
switch ( eOp )
{
case ocName:
{
ScRangeData* pData = GetRangeData( *_pTokenP);
if (pData)
{
if (pData->HasType(RT_SHARED))
pData->UpdateSymbol( aBuffer, aPos, GetGrammar());
else
aBuffer.append(pData->GetName());
}
}
break;
case ocDBArea:
{
ScDBData* pDBData = pDoc->GetDBCollection()->getNamedDBs().findByIndex(_pTokenP->GetIndex());
if (pDBData)
aBuffer.append(pDBData->GetName());
}
break;
default:
; // nothing
}
if ( aBuffer.getLength() )
rBuffer.append(aBuffer.makeStringAndClear());
else
rBuffer.append(ScGlobal::GetRscString(STR_NO_NAME_REF));
}
// -----------------------------------------------------------------------------
void ScCompiler::LocalizeString( String& rName )
{
ScGlobal::GetAddInCollection()->LocalizeString( rName );
}
// -----------------------------------------------------------------------------
// Put quotes around string if non-alphanumeric characters are contained,
// quote characters contained within are escaped by '\\'.
bool ScCompiler::EnQuote( String& rStr )
{
sal_Int32 nType = ScGlobal::pCharClass->getStringType( rStr, 0, rStr.Len() );
if ( !CharClass::isNumericType( nType )
&& CharClass::isAlphaNumericType( nType ) )
return false;
xub_StrLen nPos = 0;
while ( (nPos = rStr.Search( '\'', nPos)) != STRING_NOTFOUND )
{
rStr.Insert( '\\', nPos );
nPos += 2;
}
rStr.Insert( '\'', 0 );
rStr += '\'';
return true;
}
sal_Unicode ScCompiler::GetNativeAddressSymbol( Convention::SpecialSymbolType eType ) const
{
return pConv->getSpecialSymbol(eType);
}
void ScCompiler::fillAddInToken(::std::vector< ::com::sun::star::sheet::FormulaOpCodeMapEntry >& _rVec,bool _bIsEnglish) const
{
// All known AddIn functions.
sheet::FormulaOpCodeMapEntry aEntry;
aEntry.Token.OpCode = ocExternal;
ScUnoAddInCollection* pColl = ScGlobal::GetAddInCollection();
const long nCount = pColl->GetFuncCount();
for (long i=0; i < nCount; ++i)
{
const ScUnoAddInFuncData* pFuncData = pColl->GetFuncData(i);
if (pFuncData)
{
if ( _bIsEnglish )
{
String aName;
if (pFuncData->GetExcelName( LANGUAGE_ENGLISH_US, aName))
aEntry.Name = aName;
else
aEntry.Name = pFuncData->GetUpperName();
}
else
aEntry.Name = pFuncData->GetUpperLocal();
aEntry.Token.Data <<= ::rtl::OUString( pFuncData->GetOriginalName());
_rVec.push_back( aEntry);
}
}
// FIXME: what about those old non-UNO AddIns?
}
// -----------------------------------------------------------------------------
bool ScCompiler::HandleSingleRef()
{
ScSingleRefData& rRef = static_cast<ScToken*>(pToken.get())->GetSingleRef();
rRef.CalcAbsIfRel( aPos );
if ( !rRef.Valid() )
{
SetError( errNoRef );
return true;
}
SCCOL nCol = rRef.nCol;
SCROW nRow = rRef.nRow;
SCTAB nTab = rRef.nTab;
ScAddress aLook( nCol, nRow, nTab );
bool bColName = rRef.IsColRel();
SCCOL nMyCol = aPos.Col();
SCROW nMyRow = aPos.Row();
bool bInList = false;
bool bValidName = false;
ScRangePairList* pRL = (bColName ?
pDoc->GetColNameRanges() : pDoc->GetRowNameRanges());
ScRange aRange;
for ( size_t i = 0, nPairs = pRL->size(); i < nPairs; ++i )
{
ScRangePair* pR = (*pRL)[i];
if ( pR->GetRange(0).In( aLook ) )
{
bInList = bValidName = true;
aRange = pR->GetRange(1);
if ( bColName )
{
aRange.aStart.SetCol( nCol );
aRange.aEnd.SetCol( nCol );
}
else
{
aRange.aStart.SetRow( nRow );
aRange.aEnd.SetRow( nRow );
}
break; // for
}
}
if ( !bInList && pDoc->GetDocOptions().IsLookUpColRowNames() )
{ // automagically or created by copying and NamePos isn't in list
bool bString = pDoc->HasStringData( nCol, nRow, nTab );
if ( !bString && !pDoc->GetCell( aLook ) )
bString = true; // empty cell is ok
if ( bString )
{ //! coresponds with ScInterpreter::ScColRowNameAuto()
bValidName = true;
if ( bColName )
{ // ColName
SCROW nStartRow = nRow + 1;
if ( nStartRow > MAXROW )
nStartRow = MAXROW;
SCROW nMaxRow = MAXROW;
if ( nMyCol == nCol )
{ // formula cell in same column
if ( nMyRow == nStartRow )
{ // take remainder under name cell
nStartRow++;
if ( nStartRow > MAXROW )
nStartRow = MAXROW;
}
else if ( nMyRow > nStartRow )
{ // from name cell down to formula cell
nMaxRow = nMyRow - 1;
}
}
for ( size_t i = 0, nPairs = pRL->size(); i < nPairs; ++i )
{ // next defined ColNameRange below limits row
ScRangePair* pR = (*pRL)[i];
const ScRange& rRange = pR->GetRange(1);
if ( rRange.aStart.Col() <= nCol && nCol <= rRange.aEnd.Col() )
{ // identical column range
SCROW nTmp = rRange.aStart.Row();
if ( nStartRow < nTmp && nTmp <= nMaxRow )
nMaxRow = nTmp - 1;
}
}
aRange.aStart.Set( nCol, nStartRow, nTab );
aRange.aEnd.Set( nCol, nMaxRow, nTab );
}
else
{ // RowName
SCCOL nStartCol = nCol + 1;
if ( nStartCol > MAXCOL )
nStartCol = MAXCOL;
SCCOL nMaxCol = MAXCOL;
if ( nMyRow == nRow )
{ // formula cell in same row
if ( nMyCol == nStartCol )
{ // take remainder right from name cell
nStartCol++;
if ( nStartCol > MAXCOL )
nStartCol = MAXCOL;
}
else if ( nMyCol > nStartCol )
{ // from name cell right to formula cell
nMaxCol = nMyCol - 1;
}
}
for ( size_t i = 0, nPairs = pRL->size(); i < nPairs; ++i )
{ // next defined RowNameRange to the right limits column
ScRangePair* pR = (*pRL)[i];
const ScRange& rRange = pR->GetRange(1);
if ( rRange.aStart.Row() <= nRow && nRow <= rRange.aEnd.Row() )
{ // identical row range
SCCOL nTmp = rRange.aStart.Col();
if ( nStartCol < nTmp && nTmp <= nMaxCol )
nMaxCol = nTmp - 1;
}
}
aRange.aStart.Set( nStartCol, nRow, nTab );
aRange.aEnd.Set( nMaxCol, nRow, nTab );
}
}
}
if ( bValidName )
{
// And now the magic to distinguish between a range and a single
// cell thereof, which is picked position-dependent of the formula
// cell. If a direct neighbor is a binary operator (ocAdd, ...) a
// SingleRef matching the column/row of the formula cell is
// generated. A ocColRowName or ocIntersect as a neighbor results
// in a range. Special case: if label is valid for a single cell, a
// position independent SingleRef is generated.
bool bSingle = (aRange.aStart == aRange.aEnd);
bool bFound;
if ( bSingle )
bFound = true;
else
{
FormulaToken* p1 = pArr->PeekPrevNoSpaces();
FormulaToken* p2 = pArr->PeekNextNoSpaces();
// begin/end of a formula => single
OpCode eOp1 = p1 ? p1->GetOpCode() : static_cast<OpCode>( ocAdd );
OpCode eOp2 = p2 ? p2->GetOpCode() : static_cast<OpCode>( ocAdd );
if ( eOp1 != ocColRowName && eOp1 != ocIntersect
&& eOp2 != ocColRowName && eOp2 != ocIntersect )
{
if ( (SC_OPCODE_START_BIN_OP <= eOp1 && eOp1 < SC_OPCODE_STOP_BIN_OP) ||
(SC_OPCODE_START_BIN_OP <= eOp2 && eOp2 < SC_OPCODE_STOP_BIN_OP))
bSingle = true;
}
if ( bSingle )
{ // column and/or row must match range
if ( bColName )
{
bFound = (aRange.aStart.Row() <= nMyRow
&& nMyRow <= aRange.aEnd.Row());
if ( bFound )
aRange.aStart.SetRow( nMyRow );
}
else
{
bFound = (aRange.aStart.Col() <= nMyCol
&& nMyCol <= aRange.aEnd.Col());
if ( bFound )
aRange.aStart.SetCol( nMyCol );
}
}
else
bFound = true;
}
if ( !bFound )
SetError(errNoRef);
else if ( !bCompileForFAP )
{
ScTokenArray* pNew = new ScTokenArray();
if ( bSingle )
{
ScSingleRefData aRefData;
aRefData.InitAddress( aRange.aStart );
if ( bColName )
aRefData.SetColRel( true );
else
aRefData.SetRowRel( true );
aRefData.CalcRelFromAbs( aPos );
pNew->AddSingleReference( aRefData );
}
else
{
ScComplexRefData aRefData;
aRefData.InitRange( aRange );
if ( bColName )
{
aRefData.Ref1.SetColRel( true );
aRefData.Ref2.SetColRel( true );
}
else
{
aRefData.Ref1.SetRowRel( true );
aRefData.Ref2.SetRowRel( true );
}
aRefData.CalcRelFromAbs( aPos );
if ( bInList )
pNew->AddDoubleReference( aRefData );
else
{ // automagically
pNew->Add( new ScDoubleRefToken( aRefData, ocColRowNameAuto ) );
}
}
PushTokenArray( pNew, true );
pNew->Reset();
return GetToken();
}
}
else
SetError(errNoName);
return true;
}
// -----------------------------------------------------------------------------
bool ScCompiler::HandleDbData()
{
ScDBData* pDBData = pDoc->GetDBCollection()->getNamedDBs().findByIndex(pToken->GetIndex());
if ( !pDBData )
SetError(errNoName);
else if ( !bCompileForFAP )
{
ScComplexRefData aRefData;
aRefData.InitFlags();
pDBData->GetArea( (SCTAB&) aRefData.Ref1.nTab,
(SCCOL&) aRefData.Ref1.nCol,
(SCROW&) aRefData.Ref1.nRow,
(SCCOL&) aRefData.Ref2.nCol,
(SCROW&) aRefData.Ref2.nRow);
aRefData.Ref2.nTab = aRefData.Ref1.nTab;
aRefData.CalcRelFromAbs( aPos );
ScTokenArray* pNew = new ScTokenArray();
pNew->AddDoubleReference( aRefData );
PushTokenArray( pNew, true );
pNew->Reset();
return GetToken();
}
return true;
}
// -----------------------------------------------------------------------------
FormulaTokenRef ScCompiler::ExtendRangeReference( FormulaToken & rTok1, FormulaToken & rTok2, bool bReuseDoubleRef )
{
return ScToken::ExtendRangeReference( rTok1, rTok2, aPos,bReuseDoubleRef );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|