summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJan-Arve Sæther <jan-arve.saether@nokia.com>2009-12-04 10:24:27 (GMT)
committerJan-Arve Sæther <jan-arve.saether@nokia.com>2009-12-04 14:23:11 (GMT)
commitac83e69ffbabff8a5e674d38f0bc90ff5f188f6e (patch)
tree5f232e09e0ba225789265c33ae142e953212e362 /src
parente112bc5d2e1eb567aef3077a014a021244ed2ece (diff)
downloadQt-ac83e69ffbabff8a5e674d38f0bc90ff5f188f6e.zip
Qt-ac83e69ffbabff8a5e674d38f0bc90ff5f188f6e.tar.gz
Qt-ac83e69ffbabff8a5e674d38f0bc90ff5f188f6e.tar.bz2
Made sure that we didn't reference dangling parallel anchors.
We cannot delete the parallel anchors before we do the actual vertex restoration, since the parallel anchors created by vertex simplification will always be connected to some of the AnchorVertexPair found in simplifiedVertices that we iterate over later. Thus, we must delete the parallel anchors created by vertex simplification after we have done the restoration of the vertices. (the parallel anchor will be properly dealt with (i.e. taken out of the graph as we do the restoration)), so not deleting it won't cause it to be revisited later if that is a worry. Reviewed-by: Eduardo M. Fleury
Diffstat (limited to 'src')
-rw-r--r--src/gui/graphicsview/qgraphicsanchorlayout_p.cpp4
1 files changed, 2 insertions, 2 deletions
diff --git a/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp b/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp
index b33e228..03ed63d 100644
--- a/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp
+++ b/src/gui/graphicsview/qgraphicsanchorlayout_p.cpp
@@ -1317,9 +1317,7 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Orientation orientation)
for (int i = parallelAnchors.count() - 1; i >= 0; --i) {
ParallelAnchorData *parallel = static_cast<ParallelAnchorData *>(parallelAnchors.at(i));
restoreSimplifiedConstraints(parallel);
- delete parallel;
}
- parallelAnchors.clear();
// Then, we will restore the vertices in the inverse order of creation, this way we ensure that
// the vertex being restored was not wrapped by another simplification.
@@ -1365,6 +1363,8 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Orientation orientation)
delete pair;
}
+ qDeleteAll(parallelAnchors);
+ parallelAnchors.clear();
toRestore.clear();
}
f='#n193'>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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the qmake application of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "project.h"
#include "property.h"
#include "option.h"
#include "cachekeys.h"

#include <qdatetime.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qdir.h>
#include <qregexp.h>
#include <qtextstream.h>
#include <qstack.h>
#include <qhash.h>
#include <qxmlstream.h>
#include <qsettings.h>
#include <qdebug.h>
#ifdef Q_OS_UNIX
#include <unistd.h>
#include <sys/utsname.h>
#elif defined(Q_OS_WIN32)
#include <Windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>

#ifdef Q_OS_WIN32
#if defined(Q_CC_MWERKS)
#include "qpopen.h"
#else
#define QT_POPEN _popen
#define QT_PCLOSE _pclose
#endif
#else
#define QT_POPEN popen
#define QT_PCLOSE pclose
#endif

QT_BEGIN_NAMESPACE

//expand fucntions
enum ExpandFunc { E_MEMBER=1, E_FIRST, E_LAST, E_CAT, E_FROMFILE, E_EVAL, E_LIST,
                  E_SPRINTF, E_JOIN, E_SPLIT, E_BASENAME, E_DIRNAME, E_SECTION,
                  E_FIND, E_SYSTEM, E_UNIQUE, E_QUOTE, E_ESCAPE_EXPAND,
                  E_UPPER, E_LOWER, E_FILES, E_PROMPT, E_RE_ESCAPE, E_REPLACE,
                  E_GENERATE_TEST_UID, E_SIZE };
QMap<QString, ExpandFunc> qmake_expandFunctions()
{
    static QMap<QString, ExpandFunc> *qmake_expand_functions = 0;
    if(!qmake_expand_functions) {
        qmake_expand_functions = new QMap<QString, ExpandFunc>;
        qmakeAddCacheClear(qmakeDeleteCacheClear_QMapStringInt, (void**)&qmake_expand_functions);
        qmake_expand_functions->insert("member", E_MEMBER);
        qmake_expand_functions->insert("first", E_FIRST);
        qmake_expand_functions->insert("last", E_LAST);
        qmake_expand_functions->insert("cat", E_CAT);
        qmake_expand_functions->insert("fromfile", E_FROMFILE);
        qmake_expand_functions->insert("eval", E_EVAL);
        qmake_expand_functions->insert("list", E_LIST);
        qmake_expand_functions->insert("sprintf", E_SPRINTF);
        qmake_expand_functions->insert("join", E_JOIN);
        qmake_expand_functions->insert("split", E_SPLIT);
        qmake_expand_functions->insert("basename", E_BASENAME);
        qmake_expand_functions->insert("dirname", E_DIRNAME);
        qmake_expand_functions->insert("section", E_SECTION);
        qmake_expand_functions->insert("find", E_FIND);
        qmake_expand_functions->insert("system", E_SYSTEM);
        qmake_expand_functions->insert("unique", E_UNIQUE);
        qmake_expand_functions->insert("quote", E_QUOTE);
        qmake_expand_functions->insert("escape_expand", E_ESCAPE_EXPAND);
        qmake_expand_functions->insert("upper", E_UPPER);
        qmake_expand_functions->insert("lower", E_LOWER);
        qmake_expand_functions->insert("re_escape", E_RE_ESCAPE);
        qmake_expand_functions->insert("files", E_FILES);
        qmake_expand_functions->insert("prompt", E_PROMPT);
        qmake_expand_functions->insert("replace", E_REPLACE);
        qmake_expand_functions->insert("generate_test_uid", E_GENERATE_TEST_UID);
        qmake_expand_functions->insert("size", E_SIZE);
    }
    return *qmake_expand_functions;
}
//replace functions
enum TestFunc { T_REQUIRES=1, T_GREATERTHAN, T_LESSTHAN, T_EQUALS,
                T_EXISTS, T_EXPORT, T_CLEAR, T_UNSET, T_EVAL, T_CONFIG, T_SYSTEM,
                T_RETURN, T_BREAK, T_NEXT, T_DEFINED, T_CONTAINS, T_INFILE,
                T_COUNT, T_ISEMPTY, T_INCLUDE, T_LOAD, T_DEBUG, T_ERROR,
                T_MESSAGE, T_WARNING, T_IF };
QMap<QString, TestFunc> qmake_testFunctions()
{
    static QMap<QString, TestFunc> *qmake_test_functions = 0;
    if(!qmake_test_functions) {
        qmake_test_functions = new QMap<QString, TestFunc>;
        qmake_test_functions->insert("requires", T_REQUIRES);
        qmake_test_functions->insert("greaterThan", T_GREATERTHAN);
        qmake_test_functions->insert("lessThan", T_LESSTHAN);
        qmake_test_functions->insert("equals", T_EQUALS);
        qmake_test_functions->insert("isEqual", T_EQUALS);
        qmake_test_functions->insert("exists", T_EXISTS);
        qmake_test_functions->insert("export", T_EXPORT);
        qmake_test_functions->insert("clear", T_CLEAR);
        qmake_test_functions->insert("unset", T_UNSET);
        qmake_test_functions->insert("eval", T_EVAL);
        qmake_test_functions->insert("CONFIG", T_CONFIG);
        qmake_test_functions->insert("if", T_IF);
        qmake_test_functions->insert("isActiveConfig", T_CONFIG);
        qmake_test_functions->insert("system", T_SYSTEM);
        qmake_test_functions->insert("return", T_RETURN);
        qmake_test_functions->insert("break", T_BREAK);
        qmake_test_functions->insert("next", T_NEXT);
        qmake_test_functions->insert("defined", T_DEFINED);
        qmake_test_functions->insert("contains", T_CONTAINS);
        qmake_test_functions->insert("infile", T_INFILE);
        qmake_test_functions->insert("count", T_COUNT);
        qmake_test_functions->insert("isEmpty", T_ISEMPTY);
        qmake_test_functions->insert("include", T_INCLUDE);
        qmake_test_functions->insert("load", T_LOAD);
        qmake_test_functions->insert("debug", T_DEBUG);
        qmake_test_functions->insert("error", T_ERROR);
        qmake_test_functions->insert("message", T_MESSAGE);
        qmake_test_functions->insert("warning", T_WARNING);
    }
    return *qmake_test_functions;
}

QT_END_NAMESPACE

#ifdef QTSCRIPT_SUPPORT
#include "qscriptvalue.h"
#include "qscriptengine.h"
#include "qscriptvalueiterator.h"

QT_BEGIN_NAMESPACE

static QScriptValue qscript_projectWrapper(QScriptEngine *eng, QMakeProject *project,
                                    const QMap<QString, QStringList> &place);

static bool qscript_createQMakeProjectMap(QMap<QString, QStringList> &vars, QScriptValue js)
{
    QScriptValueIterator it(js);
    while(it.hasNext()) {
        it.next();
        vars[it.name()] = qscriptvalue_cast<QStringList>(it.value());
    }
    return true;
}

static QScriptValue qscript_call_testfunction(QScriptContext *context, QScriptEngine *engine)
{
    QMakeProject *self = qscriptvalue_cast<QMakeProject*>(context->callee().property("qmakeProject"));
    QString func = context->callee().property("functionName").toString();
    QStringList args;
    for(int i = 0; i < context->argumentCount(); ++i)
        args += context->argument(i).toString();
    QMap<QString, QStringList> place = self->variables();
    qscript_createQMakeProjectMap(place, engine->globalObject().property("qmake"));
    QScriptValue ret(engine, self->doProjectTest(func, args, place));
    engine->globalObject().setProperty("qmake", qscript_projectWrapper(engine, self, place));
    return ret;
}

static QScriptValue qscript_call_expandfunction(QScriptContext *context, QScriptEngine *engine)
{
    QMakeProject *self = qscriptvalue_cast<QMakeProject*>(context->callee().property("qmakeProject"));
    QString func = context->callee().property("functionName").toString();
    QStringList args;
    for(int i = 0; i < context->argumentCount(); ++i)
        args += context->argument(i).toString();
    QMap<QString, QStringList> place = self->variables();
    qscript_createQMakeProjectMap(place, engine->globalObject().property("qmake"));
    QScriptValue ret = qScriptValueFromValue(engine, self->doProjectExpand(func, args, place));
    engine->globalObject().setProperty("qmake", qscript_projectWrapper(engine, self, place));
    return ret;
}

static QScriptValue qscript_projectWrapper(QScriptEngine *eng, QMakeProject *project,
                                           const QMap<QString, QStringList> &place)
{
    QScriptValue ret = eng->newObject();
    {
        QStringList testFuncs = qmake_testFunctions().keys() + project->userTestFunctions();
        for(int i = 0; i < testFuncs.size(); ++i) {
            QString funcName = testFuncs.at(i);
            QScriptValue fun = eng->newFunction(qscript_call_testfunction);
            fun.setProperty("qmakeProject", eng->newVariant(qVariantFromValue(project)));
            fun.setProperty("functionName", QScriptValue(eng, funcName));
            eng->globalObject().setProperty(funcName, fun);
        }
    }
    {
        QStringList testFuncs = qmake_expandFunctions().keys() + project->userExpandFunctions();
        for(int i = 0; i < testFuncs.size(); ++i) {
            QString funcName = testFuncs.at(i);
            QScriptValue fun = eng->newFunction(qscript_call_expandfunction);
            fun.setProperty("qmakeProject", eng->newVariant(qVariantFromValue(project)));
            fun.setProperty("functionName", QScriptValue(eng, funcName));
            eng->globalObject().setProperty(funcName, fun);
        }
    }
    for(QMap<QString, QStringList>::ConstIterator it = place.begin(); it != place.end(); ++it)
        ret.setProperty(it.key(), qScriptValueFromValue(eng, it.value()));
    return ret;
}

static QScriptValue qscript_toArray(QScriptEngine *eng, const QStringList &elts)
{
    QScriptValue a = eng->newArray();
    for (int i = 0; i < elts.count(); ++i)
        a.setProperty(i, QScriptValue(eng, elts.at(i)));
    return a;
}

QT_END_NAMESPACE

#endif

QT_BEGIN_NAMESPACE

struct parser_info {
    QString file;
    int line_no;
    bool from_file;
} parser;

static QString remove_quotes(const QString &arg)
{
    const ushort SINGLEQUOTE = '\'';
    const ushort DOUBLEQUOTE = '"';

    const QChar *arg_data = arg.data();
    const ushort first = arg_data->unicode();
    const int arg_len = arg.length();
    if(first == SINGLEQUOTE || first == DOUBLEQUOTE) {
        const ushort last = (arg_data+arg_len-1)->unicode();
        if(last == first)
            return arg.mid(1, arg_len-2);
    }
    return arg;
}

static QString varMap(const QString &x)
{
    QString ret(x);
    if(ret.startsWith("TMAKE")) //tmake no more!
        ret = "QMAKE" + ret.mid(5);
    else if(ret == "INTERFACES")
        ret = "FORMS";
    else if(ret == "QMAKE_POST_BUILD")
        ret = "QMAKE_POST_LINK";
    else if(ret == "TARGETDEPS")
        ret = "POST_TARGETDEPS";
    else if(ret == "LIBPATH")
        ret = "QMAKE_LIBDIR";
    else if(ret == "QMAKE_EXT_MOC")
        ret = "QMAKE_EXT_CPP_MOC";
    else if(ret == "QMAKE_MOD_MOC")
        ret = "QMAKE_H_MOD_MOC";
    else if(ret == "QMAKE_LFLAGS_SHAPP")
        ret = "QMAKE_LFLAGS_APP";
    else if(ret == "PRECOMPH")
        ret = "PRECOMPILED_HEADER";
    else if(ret == "PRECOMPCPP")
        ret = "PRECOMPILED_SOURCE";
    else if(ret == "INCPATH")
        ret = "INCLUDEPATH";
    else if(ret == "QMAKE_EXTRA_WIN_COMPILERS" || ret == "QMAKE_EXTRA_UNIX_COMPILERS")
        ret = "QMAKE_EXTRA_COMPILERS";
    else if(ret == "QMAKE_EXTRA_WIN_TARGETS" || ret == "QMAKE_EXTRA_UNIX_TARGETS")
        ret = "QMAKE_EXTRA_TARGETS";
    else if(ret == "QMAKE_EXTRA_UNIX_INCLUDES")
        ret = "QMAKE_EXTRA_INCLUDES";
    else if(ret == "QMAKE_EXTRA_UNIX_VARIABLES")
        ret = "QMAKE_EXTRA_VARIABLES";
    else if(ret == "QMAKE_RPATH")
        ret = "QMAKE_LFLAGS_RPATH";
    else if(ret == "QMAKE_FRAMEWORKDIR")
        ret = "QMAKE_FRAMEWORKPATH";
    else if(ret == "QMAKE_FRAMEWORKDIR_FLAGS")
        ret = "QMAKE_FRAMEWORKPATH_FLAGS";
    return ret;
}

static QStringList split_arg_list(QString params)
{
    int quote = 0;
    QStringList args;

    const ushort LPAREN = '(';
    const ushort RPAREN = ')';
    const ushort SINGLEQUOTE = '\'';
    const ushort DOUBLEQUOTE = '"';
    const ushort COMMA = ',';
    const ushort SPACE = ' ';
    //const ushort TAB = '\t';

    ushort unicode;
    const QChar *params_data = params.data();
    const int params_len = params.length();
    int last = 0;
    while(last < params_len && (params_data[last].unicode() == SPACE
                                /*|| params_data[last].unicode() == TAB*/))
        ++last;
    for(int x = last, parens = 0; x <= params_len; x++) {
        unicode = params_data[x].unicode();
        if(x == params_len) {
            while(x && params_data[x-1].unicode() == SPACE)
                --x;
            QString mid(params_data+last, x-last);
            if(quote) {
                if(mid[0] == quote && mid[(int)mid.length()-1] == quote)
                    mid = mid.mid(1, mid.length()-2);
                quote = 0;
            }
            args << mid;
            break;
        }
        if(unicode == LPAREN) {
            --parens;
        } else if(unicode == RPAREN) {
            ++parens;
        } else if(quote && unicode == quote) {
            quote = 0;
        } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
            quote = unicode;
        }
        if(!parens && !quote && unicode == COMMA) {
            QString mid = params.mid(last, x - last).trimmed();
            args << mid;
            last = x+1;
            while(last < params_len && (params_data[last].unicode() == SPACE
                                        /*|| params_data[last].unicode() == TAB*/))
                ++last;
        }
    }
    return args;
}

static QStringList split_value_list(const QString &vals, bool do_semicolon=false)
{
    QString build;
    QStringList ret;
    QStack<char> quote;

    const ushort LPAREN = '(';
    const ushort RPAREN = ')';
    const ushort SINGLEQUOTE = '\'';
    const ushort DOUBLEQUOTE = '"';
    const ushort BACKSLASH = '\\';
    const ushort SEMICOLON = ';';

    ushort unicode;
    const QChar *vals_data = vals.data();
    const int vals_len = vals.length();
    for(int x = 0, parens = 0; x < vals_len; x++) {
        unicode = vals_data[x].unicode();
        if(x != (int)vals_len-1 && unicode == BACKSLASH &&
            (vals_data[x+1].unicode() == SINGLEQUOTE || vals_data[x+1].unicode() == DOUBLEQUOTE)) {
            build += vals_data[x++]; //get that 'escape'
        } else if(!quote.isEmpty() && unicode == quote.top()) {
            quote.pop();
        } else if(unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE) {
            quote.push(unicode);
        } else if(unicode == RPAREN) {
            --parens;
        } else if(unicode == LPAREN) {
            ++parens;
        }

        if(!parens && quote.isEmpty() && ((do_semicolon && unicode == SEMICOLON) ||
                                           vals_data[x] == Option::field_sep)) {
            ret << build;
            build.clear();
        } else {
            build += vals_data[x];
        }
    }
    if(!build.isEmpty())
        ret << build;
    return ret;
}

//just a parsable entity
struct ParsableBlock
{
    ParsableBlock() : ref_cnt(1) { }
    virtual ~ParsableBlock() { }

    struct Parse {
        QString text;
        parser_info pi;
        Parse(const QString &t) : text(t){ pi = parser; }
    };
    QList<Parse> parselist;

    inline int ref() { return ++ref_cnt; }
    inline int deref() { return --ref_cnt; }

protected:
    int ref_cnt;
    virtual bool continueBlock() = 0;
    bool eval(QMakeProject *p, QMap<QString, QStringList> &place);
};

bool ParsableBlock::eval(QMakeProject *p, QMap<QString, QStringList> &place)
{
    //save state
    parser_info pi = parser;
    const int block_count = p->scope_blocks.count();

    //execute
    bool ret = true;
    for(int i = 0; i < parselist.count(); i++) {
        parser = parselist.at(i).pi;
        if(!(ret = p->parse(parselist.at(i).text, place)) || !continueBlock())
            break;
    }

    //restore state
    parser = pi;
    while(p->scope_blocks.count() > block_count)
        p->scope_blocks.pop();
    return ret;
}

//defined functions
struct FunctionBlock : public ParsableBlock
{
    FunctionBlock() : calling_place(0), scope_level(1), cause_return(false) { }

    QMap<QString, QStringList> vars;
    QMap<QString, QStringList> *calling_place;
    QStringList return_value;
    int scope_level;
    bool cause_return;

    bool exec(const QList<QStringList> &args,
              QMakeProject *p, QMap<QString, QStringList> &place, QStringList &functionReturn);
    virtual bool continueBlock() { return !cause_return; }
};

bool FunctionBlock::exec(const QList<QStringList> &args,
                         QMakeProject *proj, QMap<QString, QStringList> &place,
                         QStringList &functionReturn)
{
    //save state
#if 1
    calling_place = &place;
#else
    calling_place = &proj->variables();
#endif
    return_value.clear();
    cause_return = false;

    //execute
#if 0
    vars = proj->variables(); // should be place so that local variables can be inherited
#else
    vars = place;
#endif
    vars["ARGS"].clear();
    for(int i = 0; i < args.count(); i++) {
        vars["ARGS"] += args[i];
        vars[QString::number(i+1)] = args[i];
    }
    bool ret = ParsableBlock::eval(proj, vars);
    functionReturn = return_value;

    //restore state
    calling_place = 0;
    return_value.clear();
    vars.clear();
    return ret;
}

//loops
struct IteratorBlock : public ParsableBlock
{
    IteratorBlock() : scope_level(1), loop_forever(false), cause_break(false), cause_next(false) { }

    int scope_level;

    struct Test {
        QString func;
        QStringList args;
        bool invert;
        parser_info pi;
        Test(const QString &f, QStringList &a, bool i) : func(f), args(a), invert(i) { pi = parser; }
    };
    QList<Test> test;

    QString variable;

    bool loop_forever, cause_break, cause_next;
    QStringList list;

    bool exec(QMakeProject *p, QMap<QString, QStringList> &place);
    virtual bool continueBlock() { return !cause_next && !cause_break; }
};
bool IteratorBlock::exec(QMakeProject *p, QMap<QString, QStringList> &place)
{
    bool ret = true;
    QStringList::Iterator it;
    if(!loop_forever)
        it = list.begin();
    int iterate_count = 0;
    //save state
    IteratorBlock *saved_iterator = p->iterator;
    p->iterator = this;

    //do the loop
    while(loop_forever || it != list.end()) {
        cause_next = cause_break = false;
        if(!loop_forever && (*it).isEmpty()) { //ignore empty items
            ++it;
            continue;
        }

        //set up the loop variable
        QStringList va;
        if(!variable.isEmpty()) {
            va = place[variable];
            if(loop_forever)
                place[variable] = QStringList(QString::number(iterate_count));
            else
                place[variable] = QStringList(*it);
        }
        //do the iterations
        bool succeed = true;
        for(QList<Test>::Iterator test_it = test.begin(); test_it != test.end(); ++test_it) {
            parser = (*test_it).pi;
            succeed = p->doProjectTest((*test_it).func, (*test_it).args, place);
            if((*test_it).invert)
                succeed = !succeed;
            if(!succeed)
                break;
        }
        if(succeed)
            ret = ParsableBlock::eval(p, place);
        //restore the variable in the map
        if(!variable.isEmpty())
            place[variable] = va;
        //loop counters
        if(!loop_forever)
            ++it;
        iterate_count++;
        if(!ret || cause_break)
            break;
    }

    //restore state
    p->iterator = saved_iterator;
    return ret;
}

QMakeProject::ScopeBlock::~ScopeBlock()
{
#if 0
    if(iterate)
        delete iterate;
#endif
}

static void qmake_error_msg(const QString &msg)
{
    fprintf(stderr, "%s:%d: %s\n", parser.file.toLatin1().constData(), parser.line_no,
            msg.toLatin1().constData());
}

enum isForSymbian_enum
{
    isForSymbian_NOT_SET = -1,
    isForSymbian_FALSE = 0,
    isForSymbian_ABLD = 1,
    isForSymbian_SBSV2 = 2,
};

static isForSymbian_enum isForSymbian_value = isForSymbian_NOT_SET;

// Checking for symbian build is primarily determined from the qmake spec,
// but if that is not specified, detect if symbian is the default spec
// by checking the MAKEFILE_GENERATOR variable value.
static void init_isForSymbian(const QMap<QString, QStringList>& vars)
{
    if (isForSymbian_value != isForSymbian_NOT_SET)
        return;

    QString spec = QFileInfo(Option::mkfile::qmakespec).fileName();
    if (spec.startsWith("symbian-abld", Qt::CaseInsensitive)) {
        isForSymbian_value = isForSymbian_ABLD;
        return;
    }
    if (spec.startsWith("symbian-sbsv2", Qt::CaseInsensitive)) {
        isForSymbian_value = isForSymbian_SBSV2;
        return;
    }

    QStringList generatorList = vars["MAKEFILE_GENERATOR"];

    if (!generatorList.isEmpty()) {
        QString generator = generatorList.first();
        if (generator.startsWith("SYMBIAN_ABLD"))
            isForSymbian_value = isForSymbian_ABLD;
        else if (generator.startsWith("SYMBIAN_SBSV2"))
            isForSymbian_value = isForSymbian_SBSV2;
        else
            isForSymbian_value = isForSymbian_FALSE;
    } else {
        isForSymbian_value = isForSymbian_FALSE;
    }
}

bool isForSymbian()
{
    // If isForSymbian_value has not been initialized explicitly yet,
    // call initializer with dummy map to check qmake spec.
    if (isForSymbian_value == isForSymbian_NOT_SET)
        init_isForSymbian(QMap<QString, QStringList>());

    return (isForSymbian_value == isForSymbian_ABLD || isForSymbian_value == isForSymbian_SBSV2);
}

bool isForSymbianSbsv2()
{
    // If isForSymbian_value has not been initialized explicitly yet,
    // call initializer with dummy map to check qmake spec.
    if (isForSymbian_value == isForSymbian_NOT_SET)
        init_isForSymbian(QMap<QString, QStringList>());

    return (isForSymbian_value == isForSymbian_SBSV2);
}

/*
   1) environment variable QMAKEFEATURES (as separated by colons)
   2) property variable QMAKEFEATURES (as separated by colons)
   3) <project_root> (where .qmake.cache lives) + FEATURES_DIR
   4) environment variable QMAKEPATH (as separated by colons) + /mkspecs/FEATURES_DIR
   5) your QMAKESPEC/features dir
   6) your data_install/mkspecs/FEATURES_DIR
   7) your QMAKESPEC/../FEATURES_DIR dir

   FEATURES_DIR is defined as:

   1) features/(unix|win32|macx)/
   2) features/
*/
QStringList qmake_feature_paths(QMakeProperty *prop=0)
{
    QStringList concat;
    {
        const QString base_concat = QDir::separator() + QString("features");
        switch(Option::target_mode) {
        case Option::TARG_MACX_MODE:                     //also a unix
            concat << base_concat + QDir::separator() + "mac";
            concat << base_concat + QDir::separator() + "macx";
            concat << base_concat + QDir::separator() + "unix";
            break;
        case Option::TARG_UNIX_MODE:
            concat << base_concat + QDir::separator() + "unix";
            break;
        case Option::TARG_WIN_MODE:
            {
                if (isForSymbian())
                    concat << base_concat + QDir::separator() + "symbian";
                else
                    concat << base_concat + QDir::separator() + "win32";
                break;
            }
        case Option::TARG_MAC9_MODE:
            concat << base_concat + QDir::separator() + "mac";
            concat << base_concat + QDir::separator() + "mac9";
            break;
        case Option::TARG_QNX6_MODE: //also a unix
            concat << base_concat + QDir::separator() + "qnx6";
            concat << base_concat + QDir::separator() + "unix";
            break;
        }
        concat << base_concat;
    }
    const QString mkspecs_concat = QDir::separator() + QString("mkspecs");
    QStringList feature_roots;
    QByteArray mkspec_path = qgetenv("QMAKEFEATURES");
    if(!mkspec_path.isNull())
        feature_roots += splitPathList(QString::fromLocal8Bit(mkspec_path));
    if(prop)
        feature_roots += splitPathList(prop->value("QMAKEFEATURES"));
    if(!Option::mkfile::cachefile.isEmpty()) {
        QString path;
        int last_slash = Option::mkfile::cachefile.lastIndexOf(Option::dir_sep);
        if(last_slash != -1)
            path = Option::fixPathToLocalOS(Option::mkfile::cachefile.left(last_slash));
        for(QStringList::Iterator concat_it = concat.begin();
            concat_it != concat.end(); ++concat_it)
            feature_roots << (path + (*concat_it));
    }
    QByteArray qmakepath = qgetenv("QMAKEPATH");
    if (!qmakepath.isNull()) {
        const QStringList lst = splitPathList(QString::fromLocal8Bit(qmakepath));
        for(QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it) {
            for(QStringList::Iterator concat_it = concat.begin();
                concat_it != concat.end(); ++concat_it)
                    feature_roots << ((*it) + mkspecs_concat + (*concat_it));
        }
    }
    if(!Option::mkfile::qmakespec.isEmpty())
        feature_roots << Option::mkfile::qmakespec + QDir::separator() + "features";
    if(!Option::mkfile::qmakespec.isEmpty()) {
        QFileInfo specfi(Option::mkfile::qmakespec);
        QDir specdir(specfi.absoluteFilePath());
        while(!specdir.isRoot()) {
            if(!specdir.cdUp() || specdir.isRoot())
                break;
            if(QFile::exists(specdir.path() + QDir::separator() + "features")) {
                for(QStringList::Iterator concat_it = concat.begin();
                    concat_it != concat.end(); ++concat_it)
                    feature_roots << (specdir.path() + (*concat_it));
                break;
            }
        }
    }
    for(QStringList::Iterator concat_it = concat.begin();
        concat_it != concat.end(); ++concat_it)
        feature_roots << (QLibraryInfo::location(QLibraryInfo::PrefixPath) +
                          mkspecs_concat + (*concat_it));
    for(QStringList::Iterator concat_it = concat.begin();
        concat_it != concat.end(); ++concat_it)
        feature_roots << (QLibraryInfo::location(QLibraryInfo::DataPath) +
                          mkspecs_concat + (*concat_it));
    return feature_roots;
}

QStringList qmake_mkspec_paths()
{
    QStringList ret;
    const QString concat = QDir::separator() + QString("mkspecs");
    QByteArray qmakepath = qgetenv("QMAKEPATH");
    if (!qmakepath.isEmpty()) {
        const QStringList lst = splitPathList(QString::fromLocal8Bit(qmakepath));
        for(QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it)
            ret << ((*it) + concat);
    }
    ret << QLibraryInfo::location(QLibraryInfo::DataPath) + concat;

    return ret;
}

class QMakeProjectEnv
{
    QStringList envs;
public:
    QMakeProjectEnv() { }
    QMakeProjectEnv(QMakeProject *p) { execute(p->variables()); }
    QMakeProjectEnv(const QMap<QString, QStringList> &values) { execute(values); }

    void execute(QMakeProject *p) { execute(p->variables()); }
    void execute(const QMap<QString, QStringList> &values) {
#ifdef Q_OS_UNIX
        for(QMap<QString, QStringList>::ConstIterator it = values.begin(); it != values.end(); ++it) {
            const QString var = it.key(), val = it.value().join(" ");
            if(!var.startsWith(".")) {
                const QString env_var = Option::sysenv_mod + var;
                if(!putenv(strdup(QString(env_var + "=" + val).toAscii().data())))
                    envs.append(env_var);
            }
        }
#else
        Q_UNUSED(values);
#endif
    }
    ~QMakeProjectEnv() {
#ifdef Q_OS_UNIX
        for(QStringList::ConstIterator it = envs.begin();it != envs.end(); ++it) {
            putenv(strdup(QString(*it + "=").toAscii().data()));
        }
#endif
    }
};

QMakeProject::~QMakeProject()
{
    if(own_prop)
        delete prop;
    for(QMap<QString, FunctionBlock*>::iterator it = replaceFunctions.begin(); it != replaceFunctions.end(); ++it) {
        if(!it.value()->deref())
            delete it.value();
    }
    replaceFunctions.clear();
    for(QMap<QString, FunctionBlock*>::iterator it = testFunctions.begin(); it != testFunctions.end(); ++it) {
        if(!it.value()->deref())
            delete it.value();
    }
    testFunctions.clear();
}


void
QMakeProject::init(QMakeProperty *p, const QMap<QString, QStringList> *vars)
{
    if(vars)
        base_vars = *vars;
    if(!p) {
        prop = new QMakeProperty;
        own_prop = true;
    } else {
        prop = p;
        own_prop = false;
    }
    reset();
}

QMakeProject::QMakeProject(QMakeProject *p, const QMap<QString, QStringList> *vars)
{
    init(p->properties(), vars ? vars : &p->variables());
    for(QMap<QString, FunctionBlock*>::iterator it = p->replaceFunctions.begin(); it != p->replaceFunctions.end(); ++it) {
        it.value()->ref();
        replaceFunctions.insert(it.key(), it.value());
    }
    for(QMap<QString, FunctionBlock*>::iterator it = p->testFunctions.begin(); it != p->testFunctions.end(); ++it) {
        it.value()->ref();
        testFunctions.insert(it.key(), it.value());
    }
}

void
QMakeProject::reset()
{
    // scope_blocks starts with one non-ignoring entity
    scope_blocks.clear();
    scope_blocks.push(ScopeBlock());
    iterator = 0;
    function = 0;
}

bool
QMakeProject::parse(const QString &t, QMap<QString, QStringList> &place, int numLines)
{
    QString s = t.simplified();
    int hash_mark = s.indexOf("#");
    if(hash_mark != -1) //good bye comments
        s = s.left(hash_mark);
    if(s.isEmpty()) // blank_line
        return true;

    if(scope_blocks.top().ignore) {
        bool continue_parsing = false;
        // adjust scope for each block which appears on a single line
        for(int i = 0; i < s.length(); i++) {
            if(s[i] == '{') {
                scope_blocks.push(ScopeBlock(true));
            } else if(s[i] == '}') {
                if(scope_blocks.count() == 1) {
                    fprintf(stderr, "Braces mismatch %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
                    return false;
                }
                ScopeBlock sb = scope_blocks.pop();
                if(sb.iterate) {
                    sb.iterate->exec(this, place);
                    delete sb.iterate;
                    sb.iterate = 0;
                }
                if(!scope_blocks.top().ignore) {
                    debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
                              parser.line_no, scope_blocks.count()+1);
                    s = s.mid(i+1).trimmed();
                    continue_parsing = !s.isEmpty();
                    break;
                }
            }
        }
        if(!continue_parsing) {
            debug_msg(1, "Project Parser: %s:%d : Ignored due to block being false.",
                      parser.file.toLatin1().constData(), parser.line_no);
            return true;
        }
    }

    if(function) {
        QString append;
        int d_off = 0;
        const QChar *d = s.unicode();
        bool function_finished = false;
        while(d_off < s.length()) {
            if(*(d+d_off) == QLatin1Char('}')) {
                function->scope_level--;
                if(!function->scope_level) {
                    function_finished = true;
                    break;
                }
            } else if(*(d+d_off) == QLatin1Char('{')) {
                function->scope_level++;
            }
            append += *(d+d_off);
            ++d_off;
        }
        if(!append.isEmpty())
            function->parselist.append(IteratorBlock::Parse(append));
        if(function_finished) {
            function = 0;
            s = QString(d+d_off, s.length()-d_off);
        } else {
            return true;
        }
    } else if(IteratorBlock *it = scope_blocks.top().iterate) {
        QString append;
        int d_off = 0;
        const QChar *d = s.unicode();
        bool iterate_finished = false;
        while(d_off < s.length()) {
            if(*(d+d_off) == QLatin1Char('}')) {
                it->scope_level--;
                if(!it->scope_level) {
                    iterate_finished = true;
                    break;
                }
            } else if(*(d+d_off) == QLatin1Char('{')) {
                it->scope_level++;
            }
            append += *(d+d_off);
            ++d_off;
        }
        if(!append.isEmpty())
            scope_blocks.top().iterate->parselist.append(IteratorBlock::Parse(append));
        if(iterate_finished) {
            scope_blocks.top().iterate = 0;
            bool ret = it->exec(this, place);
            delete it;
            if(!ret)
                return false;
            s = s.mid(d_off);
        } else {
            return true;
        }
    }

    QString scope, var, op;
    QStringList val;
#define SKIP_WS(d, o, l) while(o < l && (*(d+o) == QLatin1Char(' ') || *(d+o) == QLatin1Char('\t'))) ++o
    const QChar *d = s.unicode();
    int d_off = 0;
    SKIP_WS(d, d_off, s.length());
    IteratorBlock *iterator = 0;
    bool scope_failed = false, else_line = false, or_op=false;
    QChar quote = 0;
    int parens = 0, scope_count=0, start_block = 0;
    while(d_off < s.length()) {
        if(!parens) {
            if(*(d+d_off) == QLatin1Char('='))
                break;
            if(*(d+d_off) == QLatin1Char('+') || *(d+d_off) == QLatin1Char('-') ||
               *(d+d_off) == QLatin1Char('*') || *(d+d_off) == QLatin1Char('~')) {
                if(*(d+d_off+1) == QLatin1Char('=')) {
                    break;
                } else if(*(d+d_off+1) == QLatin1Char(' ')) {
                    const QChar *k = d+d_off+1;
                    int k_off = 0;
                    SKIP_WS(k, k_off, s.length()-d_off);
                    if(*(k+k_off) == QLatin1Char('=')) {
                        QString msg;
                        qmake_error_msg(QString(d+d_off, 1) + "must be followed immediately by =");
                        return false;
                    }
                }
            }
        }

        if(!quote.isNull()) {
            if(*(d+d_off) == quote)
                quote = QChar();
        } else if(*(d+d_off) == '(') {
            ++parens;
        } else if(*(d+d_off) == ')') {
            --parens;
        } else if(*(d+d_off) == '"' /*|| *(d+d_off) == '\''*/) {
            quote = *(d+d_off);
        }

        if(!parens && quote.isNull() &&
           (*(d+d_off) == QLatin1Char(':') || *(d+d_off) == QLatin1Char('{') ||
            *(d+d_off) == QLatin1Char(')') || *(d+d_off) == QLatin1Char('|'))) {
            scope_count++;
            scope = var.trimmed();
            if(*(d+d_off) == QLatin1Char(')'))
                scope += *(d+d_off); // need this
            var = "";

            bool test = scope_failed;
            if(scope.isEmpty()) {
                test = true;
            } else if(scope.toLower() == "else") { //else is a builtin scope here as it modifies state
                if(scope_count != 1 || scope_blocks.top().else_status == ScopeBlock::TestNone) {
                    qmake_error_msg(("Unexpected " + scope + " ('" + s + "')").toLatin1());
                    return false;
                }
                else_line = true;
                test = (scope_blocks.top().else_status == ScopeBlock::TestSeek);
                debug_msg(1, "Project Parser: %s:%d : Else%s %s.", parser.file.toLatin1().constData(), parser.line_no,
                          scope == "else" ? "" : QString(" (" + scope + ")").toLatin1().constData(),
                          test ? "considered" : "excluded");
            } else {
                QString comp_scope = scope;
                bool invert_test = (comp_scope.at(0) == QLatin1Char('!'));
                if(invert_test)
                    comp_scope = comp_scope.mid(1);
                int lparen = comp_scope.indexOf('(');
                if(or_op == scope_failed) {
                    if(lparen != -1) { // if there is an lparen in the scope, it IS a function
                        int rparen = comp_scope.lastIndexOf(')');
                        if(rparen == -1) {
                            qmake_error_msg("Function missing right paren: " + comp_scope);
                            return false;
                        }
                        QString func = comp_scope.left(lparen);
                        QStringList args = split_arg_list(comp_scope.mid(lparen+1, rparen - lparen - 1));
                        if(function) {
                            fprintf(stderr, "%s:%d: No tests can come after a function definition!\n",
                                    parser.file.toLatin1().constData(), parser.line_no);
                            return false;
                        } else if(func == "for") { //for is a builtin function here, as it modifies state
                            if(args.count() > 2 || args.count() < 1) {
                                fprintf(stderr, "%s:%d: for(iterate, list) requires two arguments.\n",
                                        parser.file.toLatin1().constData(), parser.line_no);
                                return false;
                            } else if(iterator) {
                                fprintf(stderr, "%s:%d unexpected nested for()\n",
                                        parser.file.toLatin1().constData(), parser.line_no);
                                return false;
                            }

                            iterator = new IteratorBlock;
                            QString it_list;
                            if(args.count() == 1) {
                                doVariableReplace(args[0], place);
                                it_list = args[0];
                                if(args[0] != "ever") {
                                    delete iterator;
                                    iterator = 0;
                                    fprintf(stderr, "%s:%d: for(iterate, list) requires two arguments.\n",
                                            parser.file.toLatin1().constData(), parser.line_no);
                                    return false;
                                }
                                it_list = "forever";
                            } else if(args.count() == 2) {
                                iterator->variable = args[0];
                                doVariableReplace(args[1], place);
                                it_list = args[1];
                            }
                            QStringList list = place[it_list];
                            if(list.isEmpty()) {
                                if(it_list == "forever") {
                                    iterator->loop_forever = true;
                                } else {
                                    int dotdot = it_list.indexOf("..");
                                    if(dotdot != -1) {
                                        bool ok;
                                        int start = it_list.left(dotdot).toInt(&ok);
                                        if(ok) {
                                            int end = it_list.mid(dotdot+2).toInt(&ok);
                                            if(ok) {
                                                if(start < end) {
                                                    for(int i = start; i <= end; i++)
                                                        list << QString::number(i);
                                                } else {
                                                    for(int i = start; i >= end; i--)
                                                        list << QString::number(i);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            iterator->list = list;
                            test = !invert_test;
                        } else if(iterator) {
                            iterator->test.append(IteratorBlock::Test(func, args, invert_test));
                            test = !invert_test;
                        } else if(func == "defineTest" || func == "defineReplace") {
                            if(!function_blocks.isEmpty()) {
                                fprintf(stderr,
                                        "%s:%d: cannot define a function within another definition.\n",
                                        parser.file.toLatin1().constData(), parser.line_no);
                                return false;
                            }
                            if(args.count() != 1) {
                                fprintf(stderr, "%s:%d: %s(function_name) requires one argument.\n",
                                        parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
                                return false;
                            }
                            QMap<QString, FunctionBlock*> *map = 0;
                            if(func == "defineTest")
                                map = &testFunctions;
                            else
                                map = &replaceFunctions;
#if 0
                            if(!map || map->contains(args[0])) {
                                fprintf(stderr, "%s:%d: Function[%s] multiply defined.\n",
                                        parser.file.toLatin1().constData(), parser.line_no, args[0].toLatin1().constData());
                                return false;
                            }
#endif
                            function = new FunctionBlock;
                            map->insert(args[0], function);
                            test = true;
                        } else {
                            test = doProjectTest(func, args, place);
                            if(*(d+d_off) == QLatin1Char(')') && d_off == s.length()-1) {
                                if(invert_test)
                                    test = !test;
                                scope_blocks.top().else_status =
                                    (test ? ScopeBlock::TestFound : ScopeBlock::TestSeek);
                                return true;  // assume we are done
                            }
                        }
                    } else {
                        QString cscope = comp_scope.trimmed();
                        doVariableReplace(cscope, place);
                        test = isActiveConfig(cscope.trimmed(), true, &place);
                    }
                    if(invert_test)
                        test = !test;
                }
            }
            if(!test && !scope_failed)
                debug_msg(1, "Project Parser: %s:%d : Test (%s) failed.", parser.file.toLatin1().constData(),
                          parser.line_no, scope.toLatin1().constData());
            if(test == or_op)
                scope_failed = !test;
            or_op = (*(d+d_off) == QLatin1Char('|'));

            if(*(d+d_off) == QLatin1Char('{')) { // scoping block
                start_block++;
                if(iterator) {
                    for(int off = 0, braces = 0; true; ++off) {
                        if(*(d+d_off+off) == QLatin1Char('{'))
                            ++braces;
                        else if(*(d+d_off+off) == QLatin1Char('}') && braces)
                            --braces;
                        if(!braces || d_off+off == s.length()) {
                            iterator->parselist.append(s.mid(d_off, off-1));
                            if(braces > 1)
                                iterator->scope_level += braces-1;
                            d_off += off-1;
                            break;
                        }
                    }
                }
            }
    } else if(!parens && *(d+d_off) == QLatin1Char('}')) {
            if(start_block) {
                --start_block;
            } else if(!scope_blocks.count()) {
                warn_msg(WarnParser, "Possible braces mismatch %s:%d", parser.file.toLatin1().constData(), parser.line_no);
            } else {
                if(scope_blocks.count() == 1) {
                    fprintf(stderr, "Braces mismatch %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
                    return false;
                }
                debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
                          parser.line_no, scope_blocks.count());
                ScopeBlock sb = scope_blocks.pop();
                if(sb.iterate)
                    sb.iterate->exec(this, place);
            }
        } else {
            var += *(d+d_off);
        }
        ++d_off;
    }
    var = var.trimmed();

    if(!else_line || (else_line && !scope_failed))
        scope_blocks.top().else_status = (!scope_failed ? ScopeBlock::TestFound : ScopeBlock::TestSeek);
    if(start_block) {
        ScopeBlock next_block(scope_failed);
        next_block.iterate = iterator;
        if(iterator)
            next_block.else_status = ScopeBlock::TestNone;
        else if(scope_failed)
            next_block.else_status = ScopeBlock::TestSeek;
        else
            next_block.else_status = ScopeBlock::TestFound;
        scope_blocks.push(next_block);
        debug_msg(1, "Project Parser: %s:%d : Entering block %d (%d). [%s]", parser.file.toLatin1().constData(),
                  parser.line_no, scope_blocks.count(), scope_failed, s.toLatin1().constData());
    } else if(iterator) {
        iterator->parselist.append(var+s.mid(d_off));
        bool ret = iterator->exec(this, place);
        delete iterator;
        return ret;
    }

    if((!scope_count && !var.isEmpty()) || (scope_count == 1 && else_line))
        scope_blocks.top().else_status = ScopeBlock::TestNone;
    if(d_off == s.length()) {
        if(!var.trimmed().isEmpty())
            qmake_error_msg(("Parse Error ('" + s + "')").toLatin1());
        return var.isEmpty(); // allow just a scope
    }

    SKIP_WS(d, d_off, s.length());
    for(; d_off < s.length() && op.indexOf('=') == -1; op += *(d+(d_off++)))
        ;
    op.replace(QRegExp("\\s"), "");

    SKIP_WS(d, d_off, s.length());
    QString vals = s.mid(d_off); // vals now contains the space separated list of values
    int rbraces = vals.count('}'), lbraces = vals.count('{');
    if(scope_blocks.count() > 1 && rbraces - lbraces == 1) {
        debug_msg(1, "Project Parser: %s:%d : Leaving block %d", parser.file.toLatin1().constData(),
                  parser.line_no, scope_blocks.count());
        ScopeBlock sb = scope_blocks.pop();
        if(sb.iterate)
            sb.iterate->exec(this, place);
        vals.truncate(vals.length()-1);
    } else if(rbraces != lbraces) {
        warn_msg(WarnParser, "Possible braces mismatch {%s} %s:%d",
                 vals.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
    }
    if(scope_failed)
        return true; // oh well
#undef SKIP_WS

    doVariableReplace(var, place);
    var = varMap(var); //backwards compatability
    if(!var.isEmpty() && Option::mkfile::do_preprocess) {
        static QString last_file("*none*");
        if(parser.file != last_file) {
            fprintf(stdout, "#file %s:%d\n", parser.file.toLatin1().constData(), parser.line_no);
            last_file = parser.file;
        }
        fprintf(stdout, "%s %s %s\n", var.toLatin1().constData(), op.toLatin1().constData(), vals.toLatin1().constData());
    }

    if(vals.contains('=') && numLines > 1)
        warn_msg(WarnParser, "Detected possible line continuation: {%s} %s:%d",
                 var.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);

    QStringList &varlist = place[var]; // varlist is the list in the symbol table

    if(Option::debug_level >= 1) {
        QString tmp_vals = vals;
        doVariableReplace(tmp_vals, place);
        debug_msg(1, "Project Parser: %s:%d :%s: :%s: (%s)", parser.file.toLatin1().constData(), parser.line_no,
                  var.toLatin1().constData(), op.toLatin1().constData(), tmp_vals.toLatin1().constData());
    }

    // now do the operation
    if(op == "~=") {
        doVariableReplace(vals, place);
        if(vals.length() < 4 || vals.at(0) != 's') {
            qmake_error_msg(("~= operator only can handle s/// function ('" +
                            s + "')").toLatin1());
            return false;
        }
        QChar sep = vals.at(1);
        QStringList func = vals.split(sep);
        if(func.count() < 3 || func.count() > 4) {
            qmake_error_msg(("~= operator only can handle s/// function ('" +
                s + "')").toLatin1());
            return false;
        }
        bool global = false, case_sense = true, quote = false;
        if(func.count() == 4) {
            global = func[3].indexOf('g') != -1;
            case_sense = func[3].indexOf('i') == -1;
            quote = func[3].indexOf('q') != -1;
        }
        QString from = func[1], to = func[2];
        if(quote)
            from = QRegExp::escape(from);
        QRegExp regexp(from, case_sense ? Qt::CaseSensitive : Qt::CaseInsensitive);
        for(QStringList::Iterator varit = varlist.begin(); varit != varlist.end();) {
            if((*varit).contains(regexp)) {
                (*varit) = (*varit).replace(regexp, to);
                if ((*varit).isEmpty())
                    varit = varlist.erase(varit);
                else
                    ++varit;
                if(!global)
                    break;
            } else
                ++varit;
        }
    } else {
        QStringList vallist;
        {
            //doVariableReplace(vals, place);
            QStringList tmp = split_value_list(vals, (var == "DEPENDPATH" || var == "INCLUDEPATH"));
            for(int i = 0; i < tmp.size(); ++i)
                vallist += doVariableReplaceExpand(tmp[i], place);
        }

        if(op == "=") {
            if(!varlist.isEmpty()) {
                bool send_warning = false;
                if(var != "TEMPLATE" && var != "TARGET") {
                    QSet<QString> incoming_vals = vallist.toSet();
                    for(int i = 0; i < varlist.size(); ++i) {
                        const QString var = varlist.at(i).trimmed();
                        if(!var.isEmpty() && !incoming_vals.contains(var)) {
                            send_warning = true;
                            break;
                        }
                    }
                }
                if(send_warning)
                    warn_msg(WarnParser, "Operator=(%s) clears variables previously set: %s:%d",
                             var.toLatin1().constData(), parser.file.toLatin1().constData(), parser.line_no);
            }
            varlist.clear();
        }
        for(QStringList::ConstIterator valit = vallist.begin();
            valit != vallist.end(); ++valit) {
            if((*valit).isEmpty())
                continue;
            if((op == "*=" && !varlist.contains((*valit))) ||
               op == "=" || op == "+=")
                varlist.append((*valit));
            else if(op == "-=")
                varlist.removeAll((*valit));
        }
        if(var == "REQUIRES") // special case to get communicated to backends!
            doProjectCheckReqs(vallist, place);
    }
    return true;
}

bool
QMakeProject::read(QTextStream &file, QMap<QString, QStringList> &place)
{
    int numLines = 0;
    bool ret = true;
    QString s;
    while(!file.atEnd()) {
        parser.line_no++;
        QString line = file.readLine().trimmed();
        int prelen = line.length();

        int hash_mark = line.indexOf("#");
        if(hash_mark != -1) //good bye comments
            line = line.left(hash_mark).trimmed();
        if(!line.isEmpty() && line.right(1) == "\\") {
            if(!line.startsWith("#")) {
                line.truncate(line.length() - 1);
                s += line + Option::field_sep;
                ++numLines;
            }
        } else if(!line.isEmpty() || (line.isEmpty() && !prelen)) {
            if(s.isEmpty() && line.isEmpty())
                continue;
            if(!line.isEmpty()) {
                s += line;
                ++numLines;
            }
            if(!s.isEmpty()) {
                if(!(ret = parse(s, place, numLines))) {
                    s = "";
                    numLines = 0;
                    break;
                }
                s = "";
                numLines = 0;
            }
        }
    }
    if (!s.isEmpty())
        ret = parse(s, place, numLines);
    return ret;
}

bool
QMakeProject::read(const QString &file, QMap<QString, QStringList> &place)
{
    parser_info pi = parser;
    reset();

    const QString oldpwd = qmake_getpwd();
    QString filename = Option::fixPathToLocalOS(file);
    doVariableReplace(filename, place);
    bool ret = false, using_stdin = false;
    QFile qfile;
    if(!strcmp(filename.toLatin1(), "-")) {
        qfile.setFileName("");
        ret = qfile.open(stdin, QIODevice::ReadOnly);
        using_stdin = true;
    } else if(QFileInfo(file).isDir()) {
        return false;
    } else {
        qfile.setFileName(filename);
        ret = qfile.open(QIODevice::ReadOnly);
        qmake_setpwd(QFileInfo(filename).absolutePath());
    }
    if(ret) {
        parser_info pi = parser;
        parser.from_file = true;
        parser.file = filename;
        parser.line_no = 0;
        QTextStream t(&qfile);
        ret = read(t, place);
        if(!using_stdin)
            qfile.close();
    }
    if(scope_blocks.count() != 1) {
        qmake_error_msg("Unterminated conditional block at end of file");
        ret = false;
    }
    parser = pi;
    qmake_setpwd(oldpwd);
    return ret;
}

bool
QMakeProject::read(const QString &project, uchar cmd)
{
    pfile = QFileInfo(project).absoluteFilePath();
    return read(cmd);
}

bool
QMakeProject::read(uchar cmd)
{
    if(cfile.isEmpty()) {
        //find out where qmake (myself) lives
        if (!base_vars.contains("QMAKE_QMAKE")) {
            if (!Option::qmake_abslocation.isNull())
                base_vars["QMAKE_QMAKE"] = QStringList(Option::qmake_abslocation);
            else
                base_vars["QMAKE_QMAKE"] = QStringList("qmake");
        }

        // hack to get the Option stuff in there
        base_vars["QMAKE_EXT_OBJ"] = QStringList(Option::obj_ext);
        base_vars["QMAKE_EXT_CPP"] = Option::cpp_ext;
        base_vars["QMAKE_EXT_C"] = Option::c_ext;
        base_vars["QMAKE_EXT_H"] = Option::h_ext;
        base_vars["QMAKE_SH"] = Option::shellPath;
        if(!Option::user_template_prefix.isEmpty())
            base_vars["TEMPLATE_PREFIX"] = QStringList(Option::user_template_prefix);

        if(cmd & ReadCache && Option::mkfile::do_cache) {        // parse the cache
            int cache_depth = -1;
            QString qmake_cache = Option::mkfile::cachefile;
            if(qmake_cache.isEmpty())  { //find it as it has not been specified
                QString dir = QDir::toNativeSeparators(Option::output_dir);
                while(!QFile::exists((qmake_cache = dir + QDir::separator() + ".qmake.cache"))) {
                    dir = dir.left(dir.lastIndexOf(QDir::separator()));
                    if(dir.isEmpty() || dir.indexOf(QDir::separator()) == -1) {
                        qmake_cache = "";
                        break;
                    }
                    if(cache_depth == -1)
                        cache_depth = 1;
                    else
                        cache_depth++;
                }
            } else {
                QString abs_cache = QFileInfo(Option::mkfile::cachefile).absoluteDir().path();
                if(Option::output_dir.startsWith(abs_cache))
                    cache_depth = Option::output_dir.mid(abs_cache.length()).count('/');
            }
            if(!qmake_cache.isEmpty()) {
                if(read(qmake_cache, cache)) {
                    Option::mkfile::cachefile_depth = cache_depth;
                    Option::mkfile::cachefile = qmake_cache;
                    if(Option::mkfile::qmakespec.isEmpty() && !cache["QMAKESPEC"].isEmpty())
                        Option::mkfile::qmakespec = cache["QMAKESPEC"].first();
                }
            }
        }
        if(cmd & ReadConf) {             // parse mkspec
            QString qmakespec = fixEnvVariables(Option::mkfile::qmakespec);
            QStringList mkspec_roots = qmake_mkspec_paths();
            debug_msg(2, "Looking for mkspec %s in (%s)", qmakespec.toLatin1().constData(),
                      mkspec_roots.join("::").toLatin1().constData());
            if(qmakespec.isEmpty()) {
                for(QStringList::ConstIterator it = mkspec_roots.begin(); it != mkspec_roots.end(); ++it) {
                    QString mkspec = (*it) + QDir::separator() + "default";
                    QFileInfo default_info(mkspec);
                    if(default_info.exists() && default_info.isDir()) {
                        qmakespec = mkspec;
                        break;
                    }
                }
                if(qmakespec.isEmpty()) {
                    fprintf(stderr, "QMAKESPEC has not been set, so configuration cannot be deduced.\n");
                    return false;
                }
                Option::mkfile::qmakespec = qmakespec;
            }

            if(QDir::isRelativePath(qmakespec)) {
                if (QFile::exists(qmakespec+"/qmake.conf")) {
                    Option::mkfile::qmakespec = QFileInfo(Option::mkfile::qmakespec).absoluteFilePath();
                } else if (QFile::exists(Option::output_dir+"/"+qmakespec+"/qmake.conf")) {
                    qmakespec = Option::mkfile::qmakespec = QFileInfo(Option::output_dir+"/"+qmakespec).absoluteFilePath();
                } else {
                    bool found_mkspec = false;
                    for(QStringList::ConstIterator it = mkspec_roots.begin(); it != mkspec_roots.end(); ++it) {
                        QString mkspec = (*it) + QDir::separator() + qmakespec;
                        if(QFile::exists(mkspec)) {
                            found_mkspec = true;
                            Option::mkfile::qmakespec = qmakespec = mkspec;
                            break;
                        }
                    }
                    if(!found_mkspec) {
                        fprintf(stderr, "Could not find mkspecs for your QMAKESPEC(%s) after trying:\n\t%s\n",
                                qmakespec.toLatin1().constData(), mkspec_roots.join("\n\t").toLatin1().constData());
                        return false;
                    }
                }
            }

            // parse qmake configuration
            while(qmakespec.endsWith(QString(QChar(QDir::separator()))))
                qmakespec.truncate(qmakespec.length()-1);
            QString spec = qmakespec + QDir::separator() + "qmake.conf";
            if(!QFile::exists(spec) &&
               QFile::exists(qmakespec + QDir::separator() + "tmake.conf"))
                spec = qmakespec + QDir::separator() + "tmake.conf";
            debug_msg(1, "QMAKESPEC conf: reading %s", spec.toLatin1().constData());
            if(!read(spec, base_vars)) {
                fprintf(stderr, "Failure to read QMAKESPEC conf file %s.\n", spec.toLatin1().constData());
                return false;
            }

            init_isForSymbian(base_vars);

            if(Option::mkfile::do_cache && !Option::mkfile::cachefile.isEmpty()) {
                debug_msg(1, "QMAKECACHE file: reading %s", Option::mkfile::cachefile.toLatin1().constData());
                read(Option::mkfile::cachefile, base_vars);
            }
        }

        if(cmd & ReadFeatures) {
            debug_msg(1, "Processing default_pre: %s", vars["CONFIG"].join("::").toLatin1().constData());
            if(doProjectInclude("default_pre", IncludeFlagFeature, base_vars) == IncludeNoExist)
                doProjectInclude("default", IncludeFlagFeature, base_vars);
        }
    }

    vars = base_vars; // start with the base

    //get a default
    if(pfile != "-" && vars["TARGET"].isEmpty())
        vars["TARGET"].append(QFileInfo(pfile).baseName());

    //before commandline
    if(cmd & ReadCmdLine) {
        cfile = pfile;
        parser.file = "(internal)";
        parser.from_file = false;
        parser.line_no = 1; //really arg count now.. duh
        reset();
        for(QStringList::ConstIterator it = Option::before_user_vars.begin();
            it != Option::before_user_vars.end(); ++it) {
            if(!parse((*it), vars)) {
                fprintf(stderr, "Argument failed to parse: %s\n", (*it).toLatin1().constData());
                return false;
            }
            parser.line_no++;
        }
    }

    //commandline configs
    if(cmd & ReadConfigs && !Option::user_configs.isEmpty()) {
        parser.file = "(configs)";
        parser.from_file = false;
        parser.line_no = 1; //really arg count now.. duh
        parse("CONFIG += " + Option::user_configs.join(" "), vars);
    }

    if(cmd & ReadProFile) { // parse project file
        debug_msg(1, "Project file: reading %s", pfile.toLatin1().constData());
        if(pfile != "-" && !QFile::exists(pfile) && !pfile.endsWith(".pro"))
            pfile += ".pro";
        if(!read(pfile, vars))
            return false;
    }

    if(cmd & ReadPostFiles) { // parse post files
        const QStringList l = vars["QMAKE_POST_INCLUDE_FILES"];
        for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
            if(read((*it), vars)) {
                if(vars["QMAKE_INTERNAL_INCLUDED_FILES"].indexOf((*it)) == -1)
                    vars["QMAKE_INTERNAL_INCLUDED_FILES"].append((*it));
            }
        }
    }

    if(cmd & ReadCmdLine) {
        parser.file = "(internal)";
        parser.from_file = false;
        parser.line_no = 1; //really arg count now.. duh
        reset();
        for(QStringList::ConstIterator it = Option::after_user_vars.begin();
            it != Option::after_user_vars.end(); ++it) {
            if(!parse((*it), vars)) {
                fprintf(stderr, "Argument failed to parse: %s\n", (*it).toLatin1().constData());
                return false;
            }
            parser.line_no++;
        }
    }

    //after configs (set in BUILDS)
    if(cmd & ReadConfigs && !Option::after_user_configs.isEmpty()) {
        parser.file = "(configs)";
        parser.from_file = false;
        parser.line_no = 1; //really arg count now.. duh
        parse("CONFIG += " + Option::after_user_configs.join(" "), vars);
    }

    if(pfile != "-" && vars["TARGET"].isEmpty())
        vars["TARGET"].append(QFileInfo(pfile).baseName());

    if(cmd & ReadConfigs && !Option::user_configs.isEmpty()) {
        parser.file = "(configs)";
        parser.from_file = false;
        parser.line_no = 1; //really arg count now.. duh
        parse("CONFIG += " + Option::user_configs.join(" "), base_vars);
    }

    if(cmd & ReadFeatures) {
        debug_msg(1, "Processing default_post: %s", vars["CONFIG"].join("::").toLatin1().constData());
        doProjectInclude("default_post", IncludeFlagFeature, vars);

        QHash<QString, bool> processed;
        const QStringList &configs = vars["CONFIG"];
        debug_msg(1, "Processing CONFIG features: %s", configs.join("::").toLatin1().constData());
        while(1) {
            bool finished = true;
            for(int i = configs.size()-1; i >= 0; --i) {
		const QString config = configs[i].toLower();
                if(!processed.contains(config)) {
                    processed.insert(config, true);
                    if(doProjectInclude(config, IncludeFlagFeature, vars) == IncludeSuccess) {
                        finished = false;
                        break;
                    }
                }
            }
            if(finished)
                break;
        }
    }
    Option::postProcessProject(this);   // let Option post-process
    return true;
}

bool
QMakeProject::isActiveConfig(const QString &x, bool regex, QMap<QString, QStringList> *place)
{
    if(x.isEmpty())
        return true;

    //magic types for easy flipping
    if(x == "true")
        return true;
    else if(x == "false")
        return false;

    static QString spec;
    if(spec.isEmpty())
        spec = QFileInfo(Option::mkfile::qmakespec).fileName();

    // Symbian is an exception to how scopes are resolved. Since we do not
    // have a separate target mode for Symbian, but we expect the scope to resolve
    // on other platforms we base it entirely on the mkspec. This means that
    // using a mkspec starting with 'symbian*' will resolve both the 'symbian'
    // and the 'unix' (because of Open C) scopes to true.
    if(isForSymbian() && (x == "symbian" || x == "unix"))
        return true;

    //mkspecs
    if((Option::target_mode == Option::TARG_MACX_MODE || Option::target_mode == Option::TARG_QNX6_MODE ||
        Option::target_mode == Option::TARG_UNIX_MODE) && x == "unix")
        return !isForSymbian();
    else if(Option::target_mode == Option::TARG_MACX_MODE && x == "macx")
        return !isForSymbian();
    else if(Option::target_mode == Option::TARG_QNX6_MODE && x == "qnx6")
        return !isForSymbian();
    else if(Option::target_mode == Option::TARG_MAC9_MODE && x == "mac9")
        return !isForSymbian();
    else if((Option::target_mode == Option::TARG_MAC9_MODE || Option::target_mode == Option::TARG_MACX_MODE) &&
            x == "mac")
        return !isForSymbian();
    else if(Option::target_mode == Option::TARG_WIN_MODE && x == "win32")
        return !isForSymbian();
    QRegExp re(x, Qt::CaseSensitive, QRegExp::Wildcard);
    if((regex && re.exactMatch(spec)) || (!regex && spec == x))
        return true;
#ifdef Q_OS_UNIX
    else if(spec == "default") {
        static char *buffer = NULL;
        if(!buffer) {
            buffer = (char *)malloc(1024);
            qmakeAddCacheClear(qmakeFreeCacheClear, (void**)&buffer);
        }
        int l = readlink(Option::mkfile::qmakespec.toLatin1(), buffer, 1024);
        if(l != -1) {
            buffer[l] = '\0';
            QString r = buffer;
            if(r.lastIndexOf('/') != -1)
                r = r.mid(r.lastIndexOf('/') + 1);
            if((regex && re.exactMatch(r)) || (!regex && r == x))
                return true;
        }
    }
#elif defined(Q_OS_WIN)
    else if(spec == "default") {
        // We can't resolve symlinks as they do on Unix, so configure.exe puts the source of the
        // qmake.conf at the end of the default/qmake.conf in the QMAKESPEC_ORG variable.
        const QStringList &spec_org = (place ? (*place)["QMAKESPEC_ORIGINAL"]
                                             : vars["QMAKESPEC_ORIGINAL"]);
        if (!spec_org.isEmpty()) {
            spec = spec_org.at(0);
            int lastSlash = spec.lastIndexOf('/');
            if(lastSlash != -1)
                spec = spec.mid(lastSlash + 1);
            if((regex && re.exactMatch(spec)) || (!regex && spec == x))
                return true;
        }
    }
#endif

    //simple matching
    const QStringList &configs = (place ? (*place)["CONFIG"] : vars["CONFIG"]);
    for(QStringList::ConstIterator it = configs.begin(); it != configs.end(); ++it) {
        if(((regex && re.exactMatch((*it))) || (!regex && (*it) == x)) && re.exactMatch((*it)))
            return true;
    }
    return false;
}

bool
QMakeProject::doProjectTest(QString str, QMap<QString, QStringList> &place)
{
    QString chk = remove_quotes(str);
    if(chk.isEmpty())
        return true;
    bool invert_test = (chk.left(1) == "!");
    if(invert_test)
        chk = chk.mid(1);

    bool test=false;
    int lparen = chk.indexOf('(');
    if(lparen != -1) { // if there is an lparen in the chk, it IS a function
        int rparen = chk.indexOf(')', lparen);
        if(rparen == -1) {
            qmake_error_msg("Function missing right paren: " + chk);
        } else {
            QString func = chk.left(lparen);
            test = doProjectTest(func, chk.mid(lparen+1, rparen - lparen - 1), place);
        }
    } else {
        test = isActiveConfig(chk, true, &place);
    }
    if(invert_test)
        return !test;
    return test;
}

bool
QMakeProject::doProjectTest(QString func, const QString &params,
                            QMap<QString, QStringList> &place)
{
    return doProjectTest(func, split_arg_list(params), place);
}

QMakeProject::IncludeStatus
QMakeProject::doProjectInclude(QString file, uchar flags, QMap<QString, QStringList> &place)
{
    enum { UnknownFormat, ProFormat, JSFormat } format = UnknownFormat;
    if(flags & IncludeFlagFeature) {
        if(!file.endsWith(Option::prf_ext))
            file += Option::prf_ext;
        if(file.indexOf(Option::dir_sep) == -1 || !QFile::exists(file)) {
            static QStringList *feature_roots = 0;
            if(!feature_roots) {
                init_isForSymbian(base_vars);
                feature_roots = new QStringList(qmake_feature_paths(prop));
                qmakeAddCacheClear(qmakeDeleteCacheClear_QStringList, (void**)&feature_roots);
            }
            debug_msg(2, "Looking for feature '%s' in (%s)", file.toLatin1().constData(),
			feature_roots->join("::").toLatin1().constData());
            int start_root = 0;
            if(parser.from_file) {
                QFileInfo currFile(parser.file), prfFile(file);
                if(currFile.fileName() == prfFile.fileName()) {
                    currFile = QFileInfo(currFile.canonicalFilePath());
                    for(int root = 0; root < feature_roots->size(); ++root) {
                        prfFile = QFileInfo(feature_roots->at(root) +
                                            QDir::separator() + file).canonicalFilePath();
                        if(prfFile == currFile) {
                            start_root = root+1;
                            break;
                        }
                    }
                }
            }
            for(int root = start_root; root < feature_roots->size(); ++root) {
                QString prf(feature_roots->at(root) + QDir::separator() + file);
                if(QFile::exists(prf + Option::js_ext)) {
                    format = JSFormat;
                    file = prf + Option::js_ext;
                    break;
                } else if(QFile::exists(prf)) {
                    format = ProFormat;
                    file = prf;
                    break;
                }
            }
            if(format == UnknownFormat)
                return IncludeNoExist;
            if(place["QMAKE_INTERNAL_INCLUDED_FEATURES"].indexOf(file) != -1)
                return IncludeFeatureAlreadyLoaded;
            place["QMAKE_INTERNAL_INCLUDED_FEATURES"].append(file);
        }
    }
    if(QDir::isRelativePath(file)) {
        QStringList include_roots;
        if(Option::output_dir != qmake_getpwd())
            include_roots << qmake_getpwd();
        include_roots << Option::output_dir;
        for(int root = 0; root < include_roots.size(); ++root) {
            QString testName = QDir::toNativeSeparators(include_roots[root]);
            if (!testName.endsWith(QString(QDir::separator())))
                testName += QDir::separator();
            testName += file;
            if(QFile::exists(testName)) {
                file = testName;
                break;
            }
        }
    }
    if(format == UnknownFormat) {
        if(QFile::exists(file)) {
            if(file.endsWith(Option::js_ext))
                format = JSFormat;
            else
                format = ProFormat;
        } else {
            return IncludeNoExist;
        }
    }
    if(Option::mkfile::do_preprocess) //nice to see this first..
        fprintf(stderr, "#switching file %s(%s) - %s:%d\n", (flags & IncludeFlagFeature) ? "load" : "include",
                file.toLatin1().constData(),
                parser.file.toLatin1().constData(), parser.line_no);
    debug_msg(1, "Project Parser: %s'ing file %s.", (flags & IncludeFlagFeature) ? "load" : "include",
              file.toLatin1().constData());

    QString orig_file = file;
    int di = file.lastIndexOf(QDir::separator());
    QString oldpwd = qmake_getpwd();
    if(di != -1) {
        if(!qmake_setpwd(file.left(file.lastIndexOf(QDir::separator())))) {
            fprintf(stderr, "Cannot find directory: %s\n", file.left(di).toLatin1().constData());
            return IncludeFailure;
        }
        file = file.right(file.length() - di - 1);
    }
    bool parsed = false;
    parser_info pi = parser;
    if(format == JSFormat) {
#ifdef QTSCRIPT_SUPPORT
        eng.globalObject().setProperty("qmake", qscript_projectWrapper(&eng, this, place));
        QFile f(file);
        if (f.open(QFile::ReadOnly)) {
            QString code = f.readAll();
            QScriptValue r = eng.evaluate(code);
            if(eng.hasUncaughtException()) {
                const int lineNo = eng.uncaughtExceptionLineNumber();
                fprintf(stderr, "%s:%d: %s\n", file.toLatin1().constData(), lineNo,
                        r.toString().toLatin1().constData());
            } else {
                parsed = true;
                QScriptValue variables = eng.globalObject().property("qmake");
                if (variables.isValid() && variables.isObject())
                    qscript_createQMakeProjectMap(place, variables);
            }
        }
#else
        warn_msg(WarnParser, "%s:%d: QtScript support disabled for %s.",
                 pi.file.toLatin1().constData(), pi.line_no, orig_file.toLatin1().constData());
#endif
    } else {
        QStack<ScopeBlock> sc = scope_blocks;
        IteratorBlock *it = iterator;
        FunctionBlock *fu = function;
        if(flags & (IncludeFlagNewProject|IncludeFlagNewParser)) {
            // The "project's variables" are used in other places (eg. export()) so it's not
            // possible to use "place" everywhere. Instead just set variables and grab them later
            QMakeProject proj(this, &place);
            if(flags & IncludeFlagNewParser) {
#if 1
                if(proj.doProjectInclude("default_pre", IncludeFlagFeature, proj.variables()) == IncludeNoExist)
                    proj.doProjectInclude("default", IncludeFlagFeature, proj.variables());
#endif
                parsed = proj.read(file, proj.variables());
            } else {
                parsed = proj.read(file);
            }
            place = proj.variables();
        } else {
            parsed = read(file, place);
        }
        iterator = it;
        function = fu;
        scope_blocks = sc;
    }
    if(parsed) {
        if(place["QMAKE_INTERNAL_INCLUDED_FILES"].indexOf(orig_file) == -1)
            place["QMAKE_INTERNAL_INCLUDED_FILES"].append(orig_file);
    } else {
        warn_msg(WarnParser, "%s:%d: Failure to include file %s.",
                 pi.file.toLatin1().constData(), pi.line_no, orig_file.toLatin1().constData());
    }
    parser = pi;
    qmake_setpwd(oldpwd);
    if(!parsed)
        return IncludeParseFailure;
    return IncludeSuccess;
}

QStringList
QMakeProject::doProjectExpand(QString func, const QString &params,
                              QMap<QString, QStringList> &place)
{
    return doProjectExpand(func, split_arg_list(params), place);
}

QStringList
QMakeProject::doProjectExpand(QString func, QStringList args,
                              QMap<QString, QStringList> &place)
{
    QList<QStringList> args_list;
    for(int i = 0; i < args.size(); ++i) {
        QStringList arg = split_value_list(args[i]), tmp;
        for(int i = 0; i < arg.size(); ++i)
            tmp += doVariableReplaceExpand(arg[i], place);;
        args_list += tmp;
    }
    return doProjectExpand(func, args_list, place);
}

QStringList
QMakeProject::doProjectExpand(QString func, QList<QStringList> args_list,
                              QMap<QString, QStringList> &place)
{
    func = func.trimmed();
    if(replaceFunctions.contains(func)) {
        FunctionBlock *defined = replaceFunctions[func];
        function_blocks.push(defined);
        QStringList ret;
        defined->exec(args_list, this, place, ret);
        Q_ASSERT(function_blocks.pop() == defined);
        return ret;
    }

    QStringList args; //why don't the builtin functions just use args_list? --Sam
    for(int i = 0; i < args_list.size(); ++i)
        args += args_list[i].join(QString(Option::field_sep));

    ExpandFunc func_t = qmake_expandFunctions().value(func.toLower());
    debug_msg(1, "Running project expand: %s(%s) [%d]",
              func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);

    QStringList ret;
    switch(func_t) {
    case E_MEMBER: {
        if(args.count() < 1 || args.count() > 3) {
            fprintf(stderr, "%s:%d: member(var, start, end) requires three arguments.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            bool ok = true;
            const QStringList &var = values(args.first(), place);
            int start = 0, end = 0;
            if(args.count() >= 2) {
                QString start_str = args[1];
                start = start_str.toInt(&ok);
                if(!ok) {
                    if(args.count() == 2) {
                        int dotdot = start_str.indexOf("..");
                        if(dotdot != -1) {
                            start = start_str.left(dotdot).toInt(&ok);
                            if(ok)
                                end = start_str.mid(dotdot+2).toInt(&ok);
                        }
                    }
                    if(!ok)
                        fprintf(stderr, "%s:%d: member() argument 2 (start) '%s' invalid.\n",
                                parser.file.toLatin1().constData(), parser.line_no,
                                start_str.toLatin1().constData());
                } else {
                    end = start;
                    if(args.count() == 3)
                        end = args[2].toInt(&ok);
                    if(!ok)
                        fprintf(stderr, "%s:%d: member() argument 3 (end) '%s' invalid.\n",
                                parser.file.toLatin1().constData(), parser.line_no,
                                args[2].toLatin1().constData());
                }
            }
            if(ok) {
                if(start < 0)
                    start += var.count();
                if(end < 0)
                    end += var.count();
                if(start < 0 || start >= var.count() || end < 0 || end >= var.count()) {
                    //nothing
                } else if(start < end) {
                    for(int i = start; i <= end && (int)var.count() >= i; i++)
                        ret += var[i];
                } else {
                    for(int i = start; i >= end && (int)var.count() >= i && i >= 0; i--)
                        ret += var[i];
                }
            }
        }
        break; }
    case E_FIRST:
    case E_LAST: {
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: %s(var) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
        } else {
            const QStringList &var = values(args.first(), place);
            if(!var.isEmpty()) {
                if(func_t == E_FIRST)
                    ret = QStringList(var[0]);
                else
                    ret = QStringList(var[var.size()-1]);
            }
        }
        break; }
    case E_CAT: {
        if(args.count() < 1 || args.count() > 2) {
            fprintf(stderr, "%s:%d: cat(file) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            QString file = args[0];
            file = Option::fixPathToLocalOS(file);

            bool singleLine = true;
            if(args.count() > 1)
                singleLine = (args[1].toLower() == "true");

            QFile qfile(file);
            if(qfile.open(QIODevice::ReadOnly)) {
                QTextStream stream(&qfile);
                while(!stream.atEnd()) {
                    ret += split_value_list(stream.readLine().trimmed());
                    if(!singleLine)
                        ret += "\n";
                }
                qfile.close();
            }
        }
        break; }
    case E_FROMFILE: {
        if(args.count() != 2) {
            fprintf(stderr, "%s:%d: fromfile(file, variable) requires two arguments.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            QString file = args[0], seek_var = args[1];
            file = Option::fixPathToLocalOS(file);

            QMap<QString, QStringList> tmp;
            if(doProjectInclude(file, IncludeFlagNewParser, tmp) == IncludeSuccess) {
                if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
                    QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
                    const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
                    for(int i = 0; i < in.size(); ++i) {
                        if(out.indexOf(in[i]) == -1)
                            out += in[i];
                    }
                }
                ret = tmp[seek_var];
            }
        }
        break; }
    case E_EVAL: {
        if(args.count() < 1 || args.count() > 2) {
            fprintf(stderr, "%s:%d: eval(variable) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);

        } else {
            const QMap<QString, QStringList> *source = &place;
            if(args.count() == 2) {
                if(args.at(1) == "Global") {
                    source = &vars;
                } else if(args.at(1) == "Local") {
                    source = &place;
                } else {
                    fprintf(stderr, "%s:%d: unexpected source to eval.\n", parser.file.toLatin1().constData(),
                            parser.line_no);
                }
            }
            ret += source->value(args.at(0));
        }
        break; }
    case E_LIST: {
        static int x = 0;
        QString tmp;
        tmp.sprintf(".QMAKE_INTERNAL_TMP_VAR_%d", x++);
        ret = QStringList(tmp);
        QStringList &lst = (*((QMap<QString, QStringList>*)&place))[tmp];
        lst.clear();
        for(QStringList::ConstIterator arg_it = args.begin();
            arg_it != args.end(); ++arg_it)
            lst += split_value_list((*arg_it));
        break; }
    case E_SPRINTF: {
        if(args.count() < 1) {
            fprintf(stderr, "%s:%d: sprintf(format, ...) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            QString tmp = args.at(0);
            for(int i = 1; i < args.count(); ++i)
                tmp = tmp.arg(args.at(i));
            ret = split_value_list(tmp);
        }
        break; }
    case E_JOIN: {
        if(args.count() < 1 || args.count() > 4) {
            fprintf(stderr, "%s:%d: join(var, glue, before, after) requires four"
                    "arguments.\n", parser.file.toLatin1().constData(), parser.line_no);
        } else {
            QString glue, before, after;
            if(args.count() >= 2)
                glue = args[1];
            if(args.count() >= 3)
                before = args[2];
            if(args.count() == 4)
                after = args[3];
            const QStringList &var = values(args.first(), place);
            if(!var.isEmpty())
                ret = split_value_list(before + var.join(glue) + after);
        }
        break; }
    case E_SPLIT: {
        if(args.count() < 1 || args.count() > 2) {
            fprintf(stderr, "%s:%d split(var, sep) requires one or two arguments\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            QString sep = QString(Option::field_sep);
            if(args.count() >= 2)
                sep = args[1];
            QStringList var = values(args.first(), place);
            for(QStringList::ConstIterator vit = var.begin(); vit != var.end(); ++vit) {
                QStringList lst = (*vit).split(sep);
                for(QStringList::ConstIterator spltit = lst.begin(); spltit != lst.end(); ++spltit)
                    ret += (*spltit);
            }
        }
        break; }
    case E_BASENAME:
    case E_DIRNAME:
    case E_SECTION: {
        bool regexp = false;
        QString sep, var;
        int beg=0, end=-1;
        if(func_t == E_SECTION) {
            if(args.count() != 3 && args.count() != 4) {
                fprintf(stderr, "%s:%d section(var, sep, begin, end) requires three argument\n",
                        parser.file.toLatin1().constData(), parser.line_no);
            } else {
                var = args[0];
                sep = args[1];
                beg = args[2].toInt();
                if(args.count() == 4)
                    end = args[3].toInt();
            }
        } else {
            if(args.count() != 1) {
                fprintf(stderr, "%s:%d %s(var) requires one argument.\n",
                        parser.file.toLatin1().constData(), parser.line_no, func.toLatin1().constData());
            } else {
                var = args[0];
                regexp = true;
                sep = "[" + QRegExp::escape(Option::dir_sep) + "/]";
                if(func_t == E_DIRNAME)
                    end = -2;
                else
                    beg = -1;
            }
        }
        if(!var.isNull()) {
            const QStringList &l = values(var, place);
            for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
                QString separator = sep;
                if(regexp)
                    ret += (*it).section(QRegExp(separator), beg, end);
                else
                    ret += (*it).section(separator, beg, end);
            }
        }
        break; }
    case E_FIND: {
        if(args.count() != 2) {
            fprintf(stderr, "%s:%d find(var, str) requires two arguments\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            QRegExp regx(args[1]);
            const QStringList &var = values(args.first(), place);
            for(QStringList::ConstIterator vit = var.begin();
                vit != var.end(); ++vit) {
                if(regx.indexIn(*vit) != -1)
                    ret += (*vit);
            }
        }
        break;  }
    case E_SYSTEM: {
        if(args.count() < 1 || args.count() > 2) {
            fprintf(stderr, "%s:%d system(execut) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            QMakeProjectEnv env(place);
            char buff[256];
            bool singleLine = true;
            if(args.count() > 1)
                singleLine = (args[1].toLower() == "true");
            QString output;
#if defined(Q_CC_MWERKS) && defined(Q_OS_WIN32)
            QPopen procPipe;
            if( !procPipe.init(args[0].toLatin1(), "r") ) {
                fprintf(stderr, "%s:%d system(%s) failed.\n",
                        parser.file.toLatin1().constData(),
                        parser.line_no,
                        qPrintable(args[0]));
            }

            while(true) {
                int read_in = procPipe.fread(buff, 255);
                if ( !read_in )
                    break;
                for(int i = 0; i < read_in; ++i) {
                    if((singleLine && buff[i] == '\n') || buff[i] == '\t')
                        buff[i] = ' ';
                }
                buff[read_in] = '\0';
                output += buff;
            }
            ret += split_value_list(output);
#else
            FILE *proc = QT_POPEN(args[0].toLatin1(), "r");
            while(proc && !feof(proc)) {
                int read_in = int(fread(buff, 1, 255, proc));
                if(!read_in)
                    break;
                for(int i = 0; i < read_in; i++) {
                    if((singleLine && buff[i] == '\n') || buff[i] == '\t')
                        buff[i] = ' ';
                }
                buff[read_in] = '\0';
                output += buff;
            }
            ret += split_value_list(output);
            if(proc)
                QT_PCLOSE(proc);
#endif
        }
        break; }
    case E_UNIQUE: {
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d unique(var) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            const QStringList &var = values(args.first(), place);
            for(int i = 0; i < var.count(); i++) {
                if(!ret.contains(var[i]))
                    ret.append(var[i]);
            }
        }
        break; }
    case E_QUOTE:
        ret = args;
        break;
    case E_ESCAPE_EXPAND: {
        for(int i = 0; i < args.size(); ++i) {
            QChar *i_data = args[i].data();
            int i_len = args[i].length();
            for(int x = 0; x < i_len; ++x) {
                if(*(i_data+x) == '\\' && x < i_len-1) {
                    if(*(i_data+x+1) == '\\') {
                        ++x;
                    } else {
                        struct {
                            char in, out;
                        } mapped_quotes[] = {
                            { 'n', '\n' },
                            { 't', '\t' },
                            { 'r', '\r' },
                            { 0, 0 }
                        };
                        for(int i = 0; mapped_quotes[i].in; ++i) {
                            if(*(i_data+x+1) == mapped_quotes[i].in) {
                                *(i_data+x) = mapped_quotes[i].out;
                                if(x < i_len-2)
                                    memmove(i_data+x+1, i_data+x+2, (i_len-x-2)*sizeof(QChar));
                                --i_len;
                                break;
                            }
                        }
                    }
                }
            }
            ret.append(QString(i_data, i_len));
        }
        break; }
    case E_RE_ESCAPE: {
        for(int i = 0; i < args.size(); ++i)
            ret += QRegExp::escape(args[i]);
        break; }
    case E_UPPER:
    case E_LOWER: {
        for(int i = 0; i < args.size(); ++i) {
            if(func_t == E_UPPER)
                ret += args[i].toUpper();
            else
                ret += args[i].toLower();
        }
        break; }
    case E_FILES: {
        if(args.count() != 1 && args.count() != 2) {
            fprintf(stderr, "%s:%d files(pattern) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            bool recursive = false;
            if(args.count() == 2)
                recursive = (args[1].toLower() == "true" || args[1].toInt());
            QStringList dirs;
            QString r = Option::fixPathToLocalOS(args[0]);
            int slash = r.lastIndexOf(QDir::separator());
            if(slash != -1) {
                dirs.append(r.left(slash));
                r = r.mid(slash+1);
            } else {
                dirs.append("");
            }

            const QRegExp regex(r, Qt::CaseSensitive, QRegExp::Wildcard);
            for(int d = 0; d < dirs.count(); d++) {
                QString dir = dirs[d];
                if(!dir.isEmpty() && !dir.endsWith(Option::dir_sep))
                    dir += "/";

                QDir qdir(dir);
                for(int i = 0; i < (int)qdir.count(); ++i) {
                    if(qdir[i] == "." || qdir[i] == "..")
                        continue;
                    QString fname = dir + qdir[i];
                    if(QFileInfo(fname).isDir()) {
                        if(recursive)
                            dirs.append(fname);
                    }
                    if(regex.exactMatch(qdir[i]))
                        ret += fname;
                }
            }
        }
        break; }
    case E_PROMPT: {
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d prompt(question) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else if(projectFile() == "-") {
            fprintf(stderr, "%s:%d prompt(question) cannot be used when '-o -' is used.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            QString msg = fixEnvVariables(args.first());
            if(!msg.endsWith("?"))
                msg += "?";
            fprintf(stderr, "Project %s: %s ", func.toUpper().toLatin1().constData(),
                    msg.toLatin1().constData());

            QFile qfile;
            if(qfile.open(stdin, QIODevice::ReadOnly)) {
                QTextStream t(&qfile);
                ret = split_value_list(t.readLine());
            }
        }
        break; }
    case E_REPLACE: {
        if(args.count() != 3 ) {
            fprintf(stderr, "%s:%d replace(var, before, after) requires three arguments\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            const QRegExp before( args[1] );
            const QString after( args[2] );
            QStringList var = values(args.first(), place);
            for(QStringList::Iterator it = var.begin(); it != var.end(); ++it)
                ret += it->replace(before, after);
        }
        break; }
    case E_GENERATE_TEST_UID: {
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: generate_test_uid(targetname) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            QString target = args[0];

            QString currPath = qmake_getpwd();
            target.prepend("/").prepend(currPath);


            QString tmp = generate_test_uid(target);

            ret += tmp;
        }
        break; }
    case E_SIZE: {
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: size(var) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            //QString target = args[0];
            int size = values(args[0]).size();
            ret += QString::number(size);
        }
        break; }
    default: {
#ifdef QTSCRIPT_SUPPORT
        {
            QScriptValue jsFunc = eng.globalObject().property(func);
            if(jsFunc.isFunction()) {
                QScriptValueList jsArgs;
                for(int i = 0; i < args.size(); ++i)
                    jsArgs += QScriptValue(&eng, args.at(i));
                QScriptValue jsRet = jsFunc.call(eng.globalObject(), jsArgs);
                ret = qscriptvalue_cast<QStringList>(jsRet);
                break;
            }
        }
#endif
        fprintf(stderr, "%s:%d: Unknown replace function: %s\n",
                parser.file.toLatin1().constData(), parser.line_no,
                func.toLatin1().constData());
        break; }
    }
    return ret;
}

bool
QMakeProject::doProjectTest(QString func, QStringList args, QMap<QString, QStringList> &place)
{
    QList<QStringList> args_list;
    for(int i = 0; i < args.size(); ++i) {
        QStringList arg = split_value_list(args[i]), tmp;
        for(int i = 0; i < arg.size(); ++i)
            tmp += doVariableReplaceExpand(arg[i], place);
        args_list += tmp;
    }
    return doProjectTest(func, args_list, place);
}

bool
QMakeProject::doProjectTest(QString func, QList<QStringList> args_list, QMap<QString, QStringList> &place)
{
    func = func.trimmed();

    if(testFunctions.contains(func)) {
        FunctionBlock *defined = testFunctions[func];
        QStringList ret;
        function_blocks.push(defined);
        defined->exec(args_list, this, place, ret);
        Q_ASSERT(function_blocks.pop() == defined);

        if(ret.isEmpty()) {
            return true;
        } else {
            if(ret.first() == "true") {
                return true;
            } else if(ret.first() == "false") {
                return false;
            } else {
                bool ok;
                int val = ret.first().toInt(&ok);
                if(ok)
                    return val;
                fprintf(stderr, "%s:%d Unexpected return value from test %s [%s].\n",
                        parser.file.toLatin1().constData(),
                        parser.line_no, func.toLatin1().constData(),
                        ret.join("::").toLatin1().constData());
            }
            return false;
        }
        return false;
    }

    QStringList args; //why don't the builtin functions just use args_list? --Sam
    for(int i = 0; i < args_list.size(); ++i)
        args += args_list[i].join(QString(Option::field_sep));

    TestFunc func_t = qmake_testFunctions().value(func);
    debug_msg(1, "Running project test: %s(%s) [%d]",
              func.toLatin1().constData(), args.join("::").toLatin1().constData(), func_t);

    switch(func_t) {
    case T_REQUIRES:
        return doProjectCheckReqs(args, place);
    case T_LESSTHAN:
    case T_GREATERTHAN: {
        if(args.count() != 2) {
            fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
                    parser.line_no, func.toLatin1().constData());
            return false;
        }
        QString rhs(args[1]), lhs(values(args[0], place).join(QString(Option::field_sep)));
        bool ok;
        int rhs_int = rhs.toInt(&ok);
        if(ok) { // do integer compare
            int lhs_int = lhs.toInt(&ok);
            if(ok) {
                if(func == "greaterThan")
                    return lhs_int > rhs_int;
                return lhs_int < rhs_int;
            }
        }
        if(func_t == T_GREATERTHAN)
            return lhs > rhs;
        return lhs < rhs; }
    case T_IF: {
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: if(condition) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        const QString cond = args.first();
        const QChar *d = cond.unicode();
        QChar quote = 0;
        bool ret = true, or_op = false;
        QString test;
        for(int d_off = 0, parens = 0, d_len = cond.size(); d_off < d_len; ++d_off) {
            if(!quote.isNull()) {
                if(*(d+d_off) == quote)
                    quote = QChar();
            } else if(*(d+d_off) == '(') {
                ++parens;
            } else if(*(d+d_off) == ')') {
                --parens;
            } else if(*(d+d_off) == '"' /*|| *(d+d_off) == '\''*/) {
                quote = *(d+d_off);
            }
            if(!parens && quote.isNull() && (*(d+d_off) == QLatin1Char(':') || *(d+d_off) == QLatin1Char('|') || d_off == d_len-1)) {
                if(d_off == d_len-1)
                    test += *(d+d_off);
                if(!test.isEmpty()) {
                    const bool success = doProjectTest(test, place);
                    test = "";
                    if(or_op)
                        ret = ret || success;
                    else
                        ret = ret && success;
                }
                if(*(d+d_off) == QLatin1Char(':')) {
                    or_op = false;
                } else if(*(d+d_off) == QLatin1Char('|')) {
                    or_op = true;
                }
            } else {
                test += *(d+d_off);
            }
        }
        return ret; }
    case T_EQUALS:
        if(args.count() != 2) {
            fprintf(stderr, "%s:%d: %s(variable, value) requires two arguments.\n", parser.file.toLatin1().constData(),
                    parser.line_no, func.toLatin1().constData());
            return false;
        }
        return values(args[0], place).join(QString(Option::field_sep)) == args[1];
    case T_EXISTS: {
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: exists(file) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        QString file = args.first();
        file = Option::fixPathToLocalOS(file);

        if(QFile::exists(file))
            return true;
        //regular expression I guess
        QString dirstr = qmake_getpwd();
        int slsh = file.lastIndexOf(Option::dir_sep);
        if(slsh != -1) {
            dirstr = file.left(slsh+1);
            file = file.right(file.length() - slsh - 1);
        }
        return QDir(dirstr).entryList(QStringList(file)).count(); }
    case T_EXPORT:
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: export(variable) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        for(int i = 0; i < function_blocks.size(); ++i) {
            FunctionBlock *f = function_blocks.at(i);
            f->vars[args[0]] = values(args[0], place);
            if(!i && f->calling_place)
                (*f->calling_place)[args[0]] = values(args[0], place);
        }
        return true;
    case T_CLEAR:
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: clear(variable) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        if(!place.contains(args[0]))
            return false;
        place[args[0]].clear();
        return true;
    case T_UNSET:
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: unset(variable) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        if(!place.contains(args[0]))
            return false;
        place.remove(args[0]);
        return true;
    case T_EVAL: {
        if(args.count() < 1 && 0) {
            fprintf(stderr, "%s:%d: eval(project) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        QString project = args.join(" ");
        parser_info pi = parser;
        parser.from_file = false;
        parser.file = "(eval)";
        parser.line_no = 0;
        QTextStream t(&project, QIODevice::ReadOnly);
        bool ret = read(t, place);
        parser = pi;
        return ret; }
    case T_CONFIG: {
        if(args.count() < 1 || args.count() > 2) {
            fprintf(stderr, "%s:%d: CONFIG(config) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        if(args.count() == 1)
            return isActiveConfig(args[0]);
        const QStringList mutuals = args[1].split('|');
        const QStringList &configs = values("CONFIG", place);
        for(int i = configs.size()-1; i >= 0; i--) {
            for(int mut = 0; mut < mutuals.count(); mut++) {
                if(configs[i] == mutuals[mut].trimmed())
                    return (configs[i] == args[0]);
            }
        }
        return false; }
    case T_SYSTEM: {
        bool setup_env = true;
        if(args.count() < 1 || args.count() > 2) {
            fprintf(stderr, "%s:%d: system(exec) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        if(args.count() == 2) {
            const QString sarg = args[1];
            setup_env = (sarg.toLower() == "true" || sarg.toInt());
        }
        QMakeProjectEnv env;
        if(setup_env)
            env.execute(place);
        bool ret = system(args[0].toLatin1().constData()) == 0;
        return ret; }
    case T_RETURN:
        if(function_blocks.isEmpty()) {
            fprintf(stderr, "%s:%d unexpected return()\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
            FunctionBlock *f = function_blocks.top();
            f->cause_return = true;
            if(args_list.count() >= 1)
                f->return_value += args_list[0];
        }
        return true;
    case T_BREAK:
        if(iterator)
            iterator->cause_break = true;
        else if(!scope_blocks.isEmpty())
            scope_blocks.top().ignore = true;
        else
            fprintf(stderr, "%s:%d unexpected break()\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        return true;
    case T_NEXT:
        if(iterator)
            iterator->cause_next = true;
        else
            fprintf(stderr, "%s:%d unexpected next()\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        return true;
    case T_DEFINED:
        if(args.count() < 1 || args.count() > 2) {
            fprintf(stderr, "%s:%d: defined(function) requires one argument.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
        } else {
           if(args.count() > 1) {
               if(args[1] == "test")
                   return testFunctions.contains(args[0]);
               else if(args[1] == "replace")
                   return replaceFunctions.contains(args[0]);
               fprintf(stderr, "%s:%d: defined(function, type): unexpected type [%s].\n",
                       parser.file.toLatin1().constData(), parser.line_no,
                       args[1].toLatin1().constData());
            } else {
                if(replaceFunctions.contains(args[0]) || testFunctions.contains(args[0]))
                    return true;
            }
        }
        return false;
    case T_CONTAINS: {
        if(args.count() < 2 || args.count() > 3) {
            fprintf(stderr, "%s:%d: contains(var, val) requires at lesat 2 arguments.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
            return false;
        }
        QRegExp regx(args[1]);
        const QStringList &l = values(args[0], place);
        if(args.count() == 2) {
            for(int i = 0; i < l.size(); ++i) {
                const QString val = l[i];
                if(regx.exactMatch(val) || val == args[1])
                    return true;
            }
        } else {
            const QStringList mutuals = args[2].split('|');
            for(int i = l.size()-1; i >= 0; i--) {
                const QString val = l[i];
                for(int mut = 0; mut < mutuals.count(); mut++) {
                    if(val == mutuals[mut].trimmed())
                        return (regx.exactMatch(val) || val == args[1]);
                }
            }
        }
        return false; }
    case T_INFILE: {
        if(args.count() < 2 || args.count() > 3) {
            fprintf(stderr, "%s:%d: infile(file, var, val) requires at least 2 arguments.\n",
                    parser.file.toLatin1().constData(), parser.line_no);
            return false;
        }

        bool ret = false;
        QMap<QString, QStringList> tmp;
        if(doProjectInclude(Option::fixPathToLocalOS(args[0]), IncludeFlagNewParser, tmp) == IncludeSuccess) {
            if(tmp.contains("QMAKE_INTERNAL_INCLUDED_FILES")) {
                QStringList &out = place["QMAKE_INTERNAL_INCLUDED_FILES"];
                const QStringList &in = tmp["QMAKE_INTERNAL_INCLUDED_FILES"];
                for(int i = 0; i < in.size(); ++i) {
                    if(out.indexOf(in[i]) == -1)
                        out += in[i];
                }
            }
            if(args.count() == 2) {
                ret = tmp.contains(args[1]);
            } else {
                QRegExp regx(args[2]);
                const QStringList &l = tmp[args[1]];
                for(QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
                    if(regx.exactMatch((*it)) || (*it) == args[2]) {
                        ret = true;
                        break;
                    }
                }
            }
        }
        return ret; }
    case T_COUNT:
        if(args.count() != 2 && args.count() != 3) {
            fprintf(stderr, "%s:%d: count(var, count) requires two arguments.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        if(args.count() == 3) {
            QString comp = args[2];
            if(comp == ">" || comp == "greaterThan")
                return values(args[0], place).count() > args[1].toInt();
            if(comp == ">=")
                return values(args[0], place).count() >= args[1].toInt();
            if(comp == "<" || comp == "lessThan")
                return values(args[0], place).count() < args[1].toInt();
            if(comp == "<=")
                return values(args[0], place).count() <= args[1].toInt();
            if(comp == "equals" || comp == "isEqual" || comp == "=" || comp == "==")
                return values(args[0], place).count() == args[1].toInt();
            fprintf(stderr, "%s:%d: unexpected modifier to count(%s)\n", parser.file.toLatin1().constData(),
                    parser.line_no, comp.toLatin1().constData());
            return false;
        }
        return values(args[0], place).count() == args[1].toInt();
    case T_ISEMPTY:
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: isEmpty(var) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        return values(args[0], place).isEmpty();
    case T_INCLUDE:
    case T_LOAD: {
        QString parseInto;
        const bool include_statement = (func_t == T_INCLUDE);
        bool ignore_error = include_statement;
        if(args.count() == 2) {
            if(func_t == T_INCLUDE) {
                parseInto = args[1];
            } else {
                QString sarg = args[1];
                ignore_error = (sarg.toLower() == "true" || sarg.toInt());
            }
        } else if(args.count() != 1) {
            QString func_desc = "load(feature)";
            if(include_statement)
                func_desc = "include(file)";
            fprintf(stderr, "%s:%d: %s requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no, func_desc.toLatin1().constData());
            return false;
        }
        QString file = args.first();
        file = Option::fixPathToLocalOS(file);
        uchar flags = IncludeFlagNone;
        if(!include_statement)
            flags |= IncludeFlagFeature;
        IncludeStatus stat = IncludeFailure;
        if(!parseInto.isEmpty()) {
            QMap<QString, QStringList> symbols;
            stat = doProjectInclude(file, flags|IncludeFlagNewProject, symbols);
            if(stat == IncludeSuccess) {
                QMap<QString, QStringList> out_place;
                for(QMap<QString, QStringList>::ConstIterator it = place.begin(); it != place.end(); ++it) {
                    const QString var = it.key();
                    if(var != parseInto && !var.startsWith(parseInto + "."))
                        out_place.insert(var, it.value());
                }
                for(QMap<QString, QStringList>::ConstIterator it = symbols.begin(); it != symbols.end(); ++it) {
                    const QString var = it.key();
                    if(!var.startsWith("."))
                        out_place.insert(parseInto + "." + it.key(), it.value());
                }
                place = out_place;
            }
        } else {
            stat = doProjectInclude(file, flags, place);
        }
        if(stat == IncludeFeatureAlreadyLoaded) {
            warn_msg(WarnParser, "%s:%d: Duplicate of loaded feature %s",
                     parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
        } else if(stat == IncludeNoExist && include_statement) {
            warn_msg(WarnParser, "%s:%d: Unable to find file for inclusion %s",
                     parser.file.toLatin1().constData(), parser.line_no, file.toLatin1().constData());
            return false;
        } else if(stat >= IncludeFailure) {
            if(!ignore_error) {
                printf("Project LOAD(): Feature %s cannot be found.\n", file.toLatin1().constData());
                if (!ignore_error)
#if defined(QT_BUILD_QMAKE_LIBRARY)
                    return false;
#else
                    exit(3);
#endif
            }
            return false;
        }
        return true; }
    case T_DEBUG: {
        if(args.count() != 2) {
            fprintf(stderr, "%s:%d: debug(level, message) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no);
            return false;
        }
        QString msg = fixEnvVariables(args[1]);
        debug_msg(args[0].toInt(), "Project DEBUG: %s", msg.toLatin1().constData());
        return true; }
    case T_ERROR:
    case T_MESSAGE:
    case T_WARNING: {
        if(args.count() != 1) {
            fprintf(stderr, "%s:%d: %s(message) requires one argument.\n", parser.file.toLatin1().constData(),
                    parser.line_no, func.toLatin1().constData());
            return false;
        }
        QString msg = fixEnvVariables(args.first());
        fprintf(stderr, "Project %s: %s\n", func.toUpper().toLatin1().constData(), msg.toLatin1().constData());
        if(func == "error")
#if defined(QT_BUILD_QMAKE_LIBRARY)
            return false;
#else
            exit(2);
#endif
        return true; }
    default:
#ifdef QTSCRIPT_SUPPORT
        {
            QScriptValue jsFunc = eng.globalObject().property(func);
            if(jsFunc.isFunction()) {
                QScriptValueList jsArgs;
                for(int i = 0; i < args.size(); ++i)
                    jsArgs += QScriptValue(&eng, args.at(i));
                QScriptValue jsRet = jsFunc.call(eng.globalObject(), jsArgs);
                if(eng.hasUncaughtException())
                    return false;
                return qscriptvalue_cast<bool>(jsRet);
            }
        }
#endif
        fprintf(stderr, "%s:%d: Unknown test function: %s\n", parser.file.toLatin1().constData(), parser.line_no,
                func.toLatin1().constData());
    }
    return false;
}

bool
QMakeProject::doProjectCheckReqs(const QStringList &deps, QMap<QString, QStringList> &place)
{
    bool ret = false;
    for(QStringList::ConstIterator it = deps.begin(); it != deps.end(); ++it) {
        bool test = doProjectTest((*it), place);
        if(!test) {
            debug_msg(1, "Project Parser: %s:%d Failed test: REQUIRES = %s",
                      parser.file.toLatin1().constData(), parser.line_no,
                      (*it).toLatin1().constData());
            place["QMAKE_FAILED_REQUIREMENTS"].append((*it));
            ret = false;
        }
    }
    return ret;
}

bool
QMakeProject::test(const QString &v)
{
    QMap<QString, QStringList> tmp = vars;
    return doProjectTest(v, tmp);
}

bool
QMakeProject::test(const QString &func, const QList<QStringList> &args)
{
    QMap<QString, QStringList> tmp = vars;
    return doProjectTest(func, args, tmp);
}

QStringList
QMakeProject::expand(const QString &str)
{
    bool ok;
    QMap<QString, QStringList> tmp = vars;
    const QStringList ret = doVariableReplaceExpand(str, tmp, &ok);
    if(ok)
        return ret;
    return QStringList();
}

QStringList
QMakeProject::expand(const QString &func, const QList<QStringList> &args)
{
    QMap<QString, QStringList> tmp = vars;
    return doProjectExpand(func, args, tmp);
}

bool
QMakeProject::doVariableReplace(QString &str, QMap<QString, QStringList> &place)
{
    bool ret;
    str = doVariableReplaceExpand(str, place, &ret).join(QString(Option::field_sep));
    return ret;
}

QStringList
QMakeProject::doVariableReplaceExpand(const QString &str, QMap<QString, QStringList> &place, bool *ok)
{
    QStringList ret;
    if(ok)
        *ok = true;
    if(str.isEmpty())
        return ret;

    const ushort LSQUARE = '[';
    const ushort RSQUARE = ']';
    const ushort LCURLY = '{';
    const ushort RCURLY = '}';
    const ushort LPAREN = '(';
    const ushort RPAREN = ')';
    const ushort DOLLAR = '$';
    const ushort SLASH = '\\';
    const ushort UNDERSCORE = '_';
    const ushort DOT = '.';
    const ushort SPACE = ' ';
    const ushort TAB = '\t';
    const ushort SINGLEQUOTE = '\'';
    const ushort DOUBLEQUOTE = '"';

    ushort unicode, quote = 0;
    const QChar *str_data = str.data();
    const int str_len = str.length();

    ushort term;
    QString var, args;

    int replaced = 0;
    QString current;
    for(int i = 0; i < str_len; ++i) {
        unicode = str_data[i].unicode();
        const int start_var = i;
        if(unicode == DOLLAR && str_len > i+2) {
            unicode = str_data[++i].unicode();
            if(unicode == DOLLAR) {
                term = 0;
                var.clear();
                args.clear();
                enum { VAR, ENVIRON, FUNCTION, PROPERTY } var_type = VAR;
                unicode = str_data[++i].unicode();
                if(unicode == LSQUARE) {
                    unicode = str_data[++i].unicode();
                    term = RSQUARE;
                    var_type = PROPERTY;
                } else if(unicode == LCURLY) {
                    unicode = str_data[++i].unicode();
                    var_type = VAR;
                    term = RCURLY;
                } else if(unicode == LPAREN) {
                    unicode = str_data[++i].unicode();
                    var_type = ENVIRON;
                    term = RPAREN;
                }
                while(1) {
                    if(!(unicode & (0xFF<<8)) &&
                       unicode != DOT && unicode != UNDERSCORE &&
                       //unicode != SINGLEQUOTE && unicode != DOUBLEQUOTE &&
                       (unicode < 'a' || unicode > 'z') && (unicode < 'A' || unicode > 'Z') &&
                       (unicode < '0' || unicode > '9'))
                        break;
                    var.append(QChar(unicode));
                    if(++i == str_len)
                        break;
                    unicode = str_data[i].unicode();
                    // at this point, i points to either the 'term' or 'next' character (which is in unicode)
                }
                if(var_type == VAR && unicode == LPAREN) {
                    var_type = FUNCTION;
                    int depth = 0;
                    while(1) {
                        if(++i == str_len)
                            break;
                        unicode = str_data[i].unicode();
                        if(unicode == LPAREN) {
                            depth++;
                        } else if(unicode == RPAREN) {
                            if(!depth)
                                break;
                            --depth;
                        }
                        args.append(QChar(unicode));
                    }
                    if(++i < str_len)
                        unicode = str_data[i].unicode();
                    else
                        unicode = 0;
                    // at this point i is pointing to the 'next' character (which is in unicode)
                    // this might actually be a term character since you can do $${func()}
                }
                if(term) {
                    if(unicode != term) {
                        qmake_error_msg("Missing " + QString(term) + " terminator [found " + (unicode?QString(unicode):QString("end-of-line")) + "]");
                        if(ok)
                            *ok = false;
                        return QStringList();
                    }
                } else {
                    // move the 'cursor' back to the last char of the thing we were looking at
                    --i;
                }
                // since i never points to the 'next' character, there is no reason for this to be set
                unicode = 0;

                QStringList replacement;
                if(var_type == ENVIRON) {
                    replacement = split_value_list(QString::fromLocal8Bit(qgetenv(var.toLatin1().constData())));
                } else if(var_type == PROPERTY) {
                    if(prop)
                        replacement = split_value_list(prop->value(var));
                } else if(var_type == FUNCTION) {
                    replacement = doProjectExpand(var, args, place);
                } else if(var_type == VAR) {
                    replacement = values(var, place);
                }
                if(!(replaced++) && start_var)
                    current = str.left(start_var);
                if(!replacement.isEmpty()) {
                    if(quote) {
                        current += replacement.join(QString(Option::field_sep));
                    } else {
                        current += replacement.takeFirst();
                        if(!replacement.isEmpty()) {
                            if(!current.isEmpty())
                                ret.append(current);
                            current = replacement.takeLast();
                            if(!replacement.isEmpty())
                                ret += replacement;
                        }
                    }
                }
                debug_msg(2, "Project Parser [var replace]: %s -> %s",
                          str.toLatin1().constData(), var.toLatin1().constData(),
                          replacement.join("::").toLatin1().constData());
            } else {
                if(replaced)
                    current.append("$");
            }
        }
        if(quote && unicode == quote) {
            unicode = 0;
            quote = 0;
        } else if(unicode == SLASH) {
            bool escape = false;
            const char *symbols = "[]{}()$\\'\"";
            for(const char *s = symbols; *s; ++s) {
                if(str_data[i+1].unicode() == (ushort)*s) {
                    i++;
                    escape = true;
                    if(!(replaced++))
                        current = str.left(start_var);
                    current.append(str.at(i));
                    break;
                }
            }
            if(escape || !replaced)
                unicode =0;
        } else if(!quote && (unicode == SINGLEQUOTE || unicode == DOUBLEQUOTE)) {
            quote = unicode;
            unicode = 0;
            if(!(replaced++) && i)
                current = str.left(i);
        } else if(!quote && (unicode == SPACE || unicode == TAB)) {
            unicode = 0;
            if(!current.isEmpty()) {
                ret.append(current);
                current.clear();
            }
        }
        if(replaced && unicode)
            current.append(QChar(unicode));
    }
    if(!replaced)
        ret = QStringList(str);
    else if(!current.isEmpty())
        ret.append(current);
    //qDebug() << "REPLACE" << str << ret;
    return ret;
}

QStringList &QMakeProject::values(const QString &_var, QMap<QString, QStringList> &place)
{
    QString var = varMap(_var);
    if(var == QLatin1String("LITERAL_WHITESPACE")) { //a real space in a token)
        var = ".BUILTIN." + var;
        place[var] = QStringList(QLatin1String("\t"));
    } else if(var == QLatin1String("LITERAL_DOLLAR")) { //a real $
        var = ".BUILTIN." + var;
        place[var] = QStringList(QLatin1String("$"));
    } else if(var == QLatin1String("LITERAL_HASH")) { //a real #
        var = ".BUILTIN." + var;
        place[var] = QStringList("#");
    } else if(var == QLatin1String("OUT_PWD")) { //the out going dir
        var = ".BUILTIN." + var;
        place[var] =  QStringList(Option::output_dir);
    } else if(var == QLatin1String("PWD") ||  //current working dir (of _FILE_)
              var == QLatin1String("IN_PWD")) {
        var = ".BUILTIN." + var;
        place[var] = QStringList(qmake_getpwd());
    } else if(var == QLatin1String("DIR_SEPARATOR")) {
        var = ".BUILTIN." + var;
        place[var] =  QStringList(Option::dir_sep);
    } else if(var == QLatin1String("DIRLIST_SEPARATOR")) {
        var = ".BUILTIN." + var;
        place[var] = QStringList(Option::dirlist_sep);
    } else if(var == QLatin1String("_LINE_")) { //parser line number
        var = ".BUILTIN." + var;
        place[var] = QStringList(QString::number(parser.line_no));
    } else if(var == QLatin1String("_FILE_")) { //parser file
        var = ".BUILTIN." + var;
        place[var] = QStringList(parser.file);
    } else if(var == QLatin1String("_DATE_")) { //current date/time
        var = ".BUILTIN." + var;
        place[var] = QStringList(QDateTime::currentDateTime().toString());
    } else if(var == QLatin1String("_PRO_FILE_")) {
        var = ".BUILTIN." + var;
        place[var] = QStringList(pfile);
    } else if(var == QLatin1String("_PRO_FILE_PWD_")) {
        var = ".BUILTIN." + var;
        place[var] =  QStringList(QFileInfo(pfile).absolutePath());
    } else if(var == QLatin1String("_QMAKE_CACHE_")) {
        var = ".BUILTIN." + var;
        if(Option::mkfile::do_cache)
            place[var] = QStringList(Option::mkfile::cachefile);
    } else if(var == QLatin1String("TEMPLATE")) {
        if(!Option::user_template.isEmpty()) {
            var = ".BUILTIN.USER." + var;
            place[var] =  QStringList(Option::user_template);
        } else if(!place[var].isEmpty()) {
            QString orig_template = place["TEMPLATE"].first(), real_template;
            if(!Option::user_template_prefix.isEmpty() && !orig_template.startsWith(Option::user_template_prefix))
                real_template = Option::user_template_prefix + orig_template;
            if(real_template.endsWith(".t"))
                real_template = real_template.left(real_template.length()-2);
            if(!real_template.isEmpty()) {
                var = ".BUILTIN." + var;
                place[var] = QStringList(real_template);
            }
        } else {
            var = ".BUILTIN." + var;
            place[var] =  QStringList("app");
        }
    } else if(var.startsWith(QLatin1String("QMAKE_HOST."))) {
        QString ret, type = var.mid(11);
#if defined(Q_OS_WIN32)
        if(type == "os") {
            ret = "Windows";
        } else if(type == "name") {
            DWORD name_length = 1024;
            TCHAR name[1024];
            if(GetComputerName(name, &name_length))
                ret = QString::fromUtf16((ushort*)name, name_length);
        } else if(type == "version" || type == "version_string") {
            QSysInfo::WinVersion ver = QSysInfo::WindowsVersion;
            if(type == "version")
                ret = QString::number(ver);
            else if(ver == QSysInfo::WV_Me)
                ret = "WinMe";
            else if(ver == QSysInfo::WV_95)
                ret = "Win95";
            else if(ver == QSysInfo::WV_98)
                ret = "Win98";
            else if(ver == QSysInfo::WV_NT)
                ret = "WinNT";
            else if(ver == QSysInfo::WV_2000)
                ret = "Win2000";
            else if(ver == QSysInfo::WV_2000)
                ret = "Win2003";
            else if(ver == QSysInfo::WV_XP)
                ret = "WinXP";
            else if(ver == QSysInfo::WV_VISTA)
                ret = "WinVista";
            else
                ret = "Unknown";
        } else if(type == "arch") {
            SYSTEM_INFO info;
            GetSystemInfo(&info);
            switch(info.wProcessorArchitecture) {
#ifdef PROCESSOR_ARCHITECTURE_AMD64
            case PROCESSOR_ARCHITECTURE_AMD64:
                ret = "x86_64";
                break;
#endif
            case PROCESSOR_ARCHITECTURE_INTEL:
                ret = "x86";
                break;
            case PROCESSOR_ARCHITECTURE_IA64:
#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
            case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
#endif
                ret = "IA64";
                break;
            default:
                ret = "Unknown";
                break;
            }
        }
#elif defined(Q_OS_UNIX)
        struct utsname name;
        if(!uname(&name)) {
            if(type == "os")
                ret = name.sysname;
            else if(type == "name")
                ret = name.nodename;
            else if(type == "version")
                ret = name.release;
            else if(type == "version_string")
                ret = name.version;
            else if(type == "arch")
                ret = name.machine;
        }
#endif
        var = ".BUILTIN.HOST." + type;
        place[var] = QStringList(ret);
    } else if (var == QLatin1String("QMAKE_DIR_SEP")) {
        if (place[var].isEmpty())
            return values("DIR_SEPARATOR", place);
    } else if (var == QLatin1String("EPOCROOT")) {
        if (place[var].isEmpty())
            place[var] = QStringList(epocRoot());
    }
    //qDebug("REPLACE [%s]->[%s]", qPrintable(var), qPrintable(place[var].join("::")));
    return place[var];
}


// UIDs starting with 0xE are test UIDs in symbian
QString generate_test_uid(const QString& target) {
    QString tmp = generate_uid(target);
    tmp.replace(0,1,"E");
    tmp.prepend("0x");

    // printf("generate_test_uid for %s is %s \n", qPrintable(target), qPrintable(tmp));

    return tmp;
}


// UIDs starting with 0xE are test UIDs in symbian
QString generate_uid(const QString& target) {

    static QMap<QString, QString> targetToUid;

    QString tmp = targetToUid[target];

    if(!tmp.isEmpty()) {
        // printf("generate_uid for %s is %s \n", qPrintable(target), qPrintable(tmp));
        return tmp;
    }

    unsigned long hash = 5381;
    int c;

    for(int i = 0; i < target.size(); ++i) {
        c = target.at(i).toAscii();
        hash ^= c + ((c-i) << i%20) + ((c+i) << (i+5)%20) + ((c-2*i) << (i+10)%20) + ((c+2*i) << (i+15)%20);
    }

    tmp.setNum(hash, 16);
    for(int i = tmp.size(); i < 8; ++i)
        tmp.prepend("0");

#if 0
    static QMap<QString, QString> uidConflictCheckList;
    QString testStr = tmp;
    testStr.replace(0,1,"E"); // Simulate actual UID generation
    if (uidConflictCheckList.contains(testStr)) {
        printf("\n\n!!!! generated duplicate uid for %s is %s <-> %s !!!!\n\n\n",
            qPrintable(target),
            qPrintable(testStr),
            qPrintable(uidConflictCheckList.value(testStr)));
        }
    uidConflictCheckList.insert(testStr, target);
    printf("generate_uid for %s is %s \n", qPrintable(target), qPrintable(tmp));
#endif

    targetToUid[target] = tmp;

    return tmp;
}

static void fixEpocRootStr(QString& path)
{
    path.replace("\\","/");

    if (path.size() > 1 && path[1] == QChar(':')) {
        path = path.mid(2);
    }

    if (!path.size() || path[path.size()-1] != QChar('/')) {
        path += QChar('/');
    }
}

#define SYMBIAN_SDKS_KEY "HKEY_LOCAL_MACHINE\\Software\\Symbian\\EPOC SDKs"

static QString epocRootStr;

QString epocRoot()
{
    if (!epocRootStr.isEmpty())
    {
        return epocRootStr;
    }

    // First, check the env variable
    epocRootStr = qgetenv("EPOCROOT");

    if (epocRootStr.isEmpty()) {
        // No EPOCROOT set, check the default device
        // First check EPOCDEVICE env variable
        QString defaultDevice = qgetenv("EPOCDEVICE");

        // Check the windows registry via QSettings for devices.xml path
        QSettings settings(SYMBIAN_SDKS_KEY, QSettings::NativeFormat);
        QString devicesXmlPath = settings.value("CommonPath").toString();

        if (!devicesXmlPath.isEmpty()) {
            // Parse xml for correct device
            devicesXmlPath += "/devices.xml";
            QFile devicesFile(devicesXmlPath);
            if (devicesFile.open(QIODevice::ReadOnly)) {
                QXmlStreamReader xml(&devicesFile);
                while (!xml.atEnd()) {
                    xml.readNext();
                    if (xml.isStartElement() && xml.name() == "devices") {
                        if (xml.attributes().value("version") == "1.0") {
                            // Look for correct device
                            while (!(xml.isEndElement() && xml.name() == "devices") && !xml.atEnd()) {
                                xml.readNext();
                                if (xml.isStartElement() && xml.name() == "device") {
                                    if ((defaultDevice.isEmpty() && xml.attributes().value("default") == "yes") ||
                                        (!defaultDevice.isEmpty() && (xml.attributes().value("id").toString() + QString(":") + xml.attributes().value("name").toString()) == defaultDevice)) {
                                        // Found the correct device
                                        while (!(xml.isEndElement() && xml.name() == "device") && !xml.atEnd()) {
                                            xml.readNext();
                                            if (xml.isStartElement() && xml.name() == "epocroot") {
                                                epocRootStr = xml.readElementText();
                                                fixEpocRootStr(epocRootStr);
                                                return epocRootStr;
                                            }
                                        }
                                        xml.raiseError("No epocroot element found");
                                    }
                                }
                            }
                        } else {
                            xml.raiseError("Invalid 'devices' element version");
                        }
                    }
                }
                if (xml.hasError()) {
                    fprintf(stderr, "ERROR: \"%s\" when parsing devices.xml\n", qPrintable(xml.errorString()));
                }
            } else {
                fprintf(stderr, "Could not open devices.xml (%s)\n", qPrintable(devicesXmlPath));
            }
        } else {
            fprintf(stderr, "Could not retrieve " SYMBIAN_SDKS_KEY " setting\n");
        }

        fprintf(stderr, "Failed to determine epoc root.\n");
        if (!defaultDevice.isEmpty())
            fprintf(stderr, "The device indicated by EPOCDEVICE environment variable (%s) could not be found.\n", qPrintable(defaultDevice));
        fprintf(stderr, "Either set EPOCROOT or EPOCDEVICE environment variable to a valid value, or provide a default Symbian device.\n");

        // No valid device found; set epocroot to "/"
        epocRootStr = QLatin1String("/");
    }

    fixEpocRootStr(epocRootStr);
    return epocRootStr;
}

QT_END_NAMESPACE