aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/language/loader.cpp
blob: 2c6eec7af3cb56178bf1f8fa92adaac9c72243e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "loader.h"

#include "identifiersearch.h"
#include "language.h"
#include "scriptengine.h"

#include <jsextensions/file.h>
#include <jsextensions/process.h>
#include <jsextensions/textfile.h>
#include <logging/logger.h>
#include <logging/translator.h>
#include <parser/qmljsengine_p.h>
#include <parser/qmljsnodepool_p.h>
#include <parser/qmljslexer_p.h>
#include <parser/qmljsparser_p.h>
#include <tools/codelocation.h>
#include <tools/error.h>
#include <tools/fileinfo.h>
#include <tools/hostosinfo.h>
#include <tools/progressobserver.h>
#include <tools/scripttools.h>
#include <tools/settings.h>

#include <QCoreApplication>
#include <QDirIterator>
#include <QMultiMap>
#include <QScriptClass>
#include <QScriptProgram>
#include <QScriptValueIterator>
#include <QSettings>
#include <QVariant>

#include <set>

QT_BEGIN_NAMESPACE
static uint qHash(const QStringList &list)
{
    uint hash = 0;
    foreach (const QString &n, list)
        hash ^= qHash(n);
    return hash;
}
QT_END_NAMESPACE

const char QBS_LANGUAGE_VERSION[] = "1.0";

using namespace QbsQmlJS::AST;

namespace qbs {
namespace Internal {

class Function
{
public:
    QString name;
    QScriptProgram source;
};

class Binding
{
public:
    QStringList name;
    QScriptProgram valueSource;
    bool valueSourceUsesBase;
    bool valueSourceUsesOuter;

    bool isValid() const { return !name.isEmpty(); }
    CodeLocation codeLocation() const;
};

class PropertyDeclaration
{
public:
    enum Type
    {
        UnknownType,
        Boolean,
        Path,
        PathList,
        String,
        Variant,
        Verbatim
    };

    enum Flag
    {
        DefaultFlags = 0,
        ListProperty = 0x1,
        PropertyNotAvailableInConfig = 0x2     // Is this property part of a project, product or file configuration?
    };
    Q_DECLARE_FLAGS(Flags, Flag)

    PropertyDeclaration();
    PropertyDeclaration(const QString &name, Type type, Flags flags = DefaultFlags);
    ~PropertyDeclaration();

    bool isValid() const;

    QString name;
    Type type;
    Flags flags;
    QScriptValue allowedValues;
    QString description;
    QString initialValueSource;
};

class ProjectFile;

class LanguageObject
{
public:
    LanguageObject(ProjectFile *owner);
    LanguageObject(const LanguageObject &other);
    ~LanguageObject();

    QString id;

    QStringList prototype;
    QString prototypeFileName;
    CodeLocation prototypeLocation;
    ProjectFile *file;

    QList<LanguageObject *> children;
    QHash<QStringList, Binding> bindings;
    QHash<QString, Function> functions;
    QHash<QString, PropertyDeclaration> propertyDeclarations;
};

class EvaluationObject;
class Scope;

/**
  * Represents a qbs project file.
  * Owns all the language objects.
  */
class ProjectFile
{
public:
    typedef QSharedPointer<ProjectFile> Ptr;

    ProjectFile();
    ~ProjectFile();

    JsImports jsImports;
    LanguageObject *root;
    QString fileName;

    bool isValid() const { return !root->prototype.isEmpty(); }
    bool isDestructing() const { return m_destructing; }

    void registerScope(QSharedPointer<Scope> scope) { m_scopes += scope; }
    void registerEvaluationObject(EvaluationObject *eo) { m_evaluationObjects += eo; }
    void unregisterEvaluationObject(EvaluationObject *eo) { m_evaluationObjects.removeOne(eo); }
    void registerLanguageObject(LanguageObject *eo) { m_languageObjects += eo; }
    void unregisterLanguageObject(LanguageObject *eo) { m_languageObjects.removeOne(eo); }

private:
    bool m_destructing;
    QList<QSharedPointer<Scope> > m_scopes;
    QList<EvaluationObject *> m_evaluationObjects;
    QList<LanguageObject *> m_languageObjects;
};


// evaluation objects

class ScopeChain;
class Scope;

class Property
{
public:
    explicit Property(LanguageObject *sourceObject = 0);
    explicit Property(QSharedPointer<Scope> scope);
    explicit Property(EvaluationObject *object);
    explicit Property(const QScriptValue &scriptValue);

    // ids, project. etc, JS imports and
    // where properties get resolved to
    QSharedPointer<ScopeChain> scopeChain;
    QScriptProgram valueSource;
    bool valueSourceUsesBase;
    bool valueSourceUsesOuter;
    QList<Property> baseProperties;

    // value once it's been evaluated
    QScriptValue value;

    // if value is a scope
    QSharedPointer<Scope> scope;

    // where this property is set
    LanguageObject *sourceObject;

    bool isValid() const { return scopeChain || scope || value.isValid(); }
};

class ScopeChain : public QScriptClass
{
    Q_DISABLE_COPY(ScopeChain)
public:
    typedef QSharedPointer<ScopeChain> Ptr;

    ScopeChain(QScriptEngine *engine, const QSharedPointer<Scope> &root = QSharedPointer<Scope>());
    ~ScopeChain();

    ScopeChain *clone() const;
    QScriptValue value();
    QSharedPointer<Scope> first() const;
    QSharedPointer<Scope> last() const;
    // returns this
    ScopeChain *prepend(const QSharedPointer<Scope> &newTop);

    QSharedPointer<Scope> findNonEmpty(const QString &name) const;
    QSharedPointer<Scope> find(const QString &name) const;

    Property lookupProperty(const QString &name) const;

protected:
    // QScriptClass interface
    QueryFlags queryProperty(const QScriptValue &object, const QScriptString &name,
                             QueryFlags flags, uint *id);
    QScriptValue property(const QScriptValue &object, const QScriptString &name, uint id);
    void setProperty(QScriptValue &object, const QScriptString &name, uint id, const QScriptValue &m_value);

private:
    QList<QWeakPointer<Scope> > m_scopes;
    QScriptValue m_value;
};

class Scope;
typedef std::set<Scope *> ScopesCache;
typedef QSharedPointer<ScopesCache> ScopesCachePtr;

class Scope : public QScriptClass
{
    Q_DISABLE_COPY(Scope)
    Scope(QScriptEngine *engine, ScopesCachePtr cache, const QString &name);

    ScopesCachePtr m_scopesCache;

public:
    typedef QSharedPointer<Scope> Ptr;
    typedef QSharedPointer<const Scope> ConstPtr;

    static Ptr create(QScriptEngine *engine, ScopesCachePtr cache, const QString &name,
                      ProjectFile *owner);
    ~Scope();

    QString name() const;

protected:
    // QScriptClass interface
    QueryFlags queryProperty(const QScriptValue &object, const QScriptString &name,
                             QueryFlags flags, uint *id);
    QScriptValue property(const QScriptValue &object, const QScriptString &name, uint id);

public:
    QScriptValue property(const QString &name) const;
    bool boolValue(const QString &name, bool defaultValue = false) const;
    QString stringValue(const QString &name) const;
    QStringList stringListValue(const QString &name) const;
    QString verbatimValue(const QString &name) const;
    void dump(const QByteArray &indent) const;
    void insertAndDeclareProperty(const QString &propertyName, const Property &property,
                                  PropertyDeclaration::Type propertyType = PropertyDeclaration::Variant);

    QHash<QString, Property> properties;
    QHash<QString, PropertyDeclaration> declarations;

    QString m_name;
    QWeakPointer<Scope> fallbackScope;
    QScriptValue value;
};

class ProbeScope : public QScriptClass
{
    Q_DISABLE_COPY(ProbeScope)
    ProbeScope(QScriptEngine *engine, const Scope::Ptr &scope);
public:
    typedef QSharedPointer<ProbeScope> Ptr;

    static Ptr create(QScriptEngine *engine, const Scope::Ptr &scope);
    ~ProbeScope();

    QScriptValue value();

protected:
    // QScriptClass interface
    QueryFlags queryProperty(const QScriptValue &object, const QScriptString &name,
                             QueryFlags flags, uint *id);
    QScriptValue property(const QScriptValue &object, const QScriptString &name, uint id);
    void setProperty(QScriptValue &object, const QScriptString &name, uint id, const QScriptValue &value);

private:
    Scope::Ptr m_scope;
    QSharedPointer<QScriptClass> m_scopeChain;
    QScriptValue m_value;
};

class ModuleBase
{
public:
    typedef QSharedPointer<ModuleBase> Ptr;

    virtual ~ModuleBase() {}
    QString name;
    QScriptProgram condition;
    ScopeChain::Ptr conditionScopeChain;
    CodeLocation dependsLocation;
};

class UnknownModule : public ModuleBase
{
public:
    typedef QSharedPointer<UnknownModule> Ptr;

    bool required;
    QString failureMessage;
};

class EvaluationObject;

class Module : public ModuleBase
{
    Q_DISABLE_COPY(Module)
public:
    typedef QSharedPointer<Module> Ptr;

    Module();
    ~Module();

    ProjectFile *file() const;
    void dump(QByteArray &indent);

    QStringList id;
    Scope::Ptr context;
    EvaluationObject *object;
    uint dependsCount;
};

class EvaluationObject
{
    Q_DISABLE_COPY(EvaluationObject)
public:
    EvaluationObject(LanguageObject *instantiatingObject);
    ~EvaluationObject();

    LanguageObject *instantiatingObject() const;
    void dump(QByteArray &indent);

    QString prototype;

    Scope::Ptr scope;
    QList<EvaluationObject *> children;
    QHash<QString, Module::Ptr> modules;
    QList<UnknownModule::Ptr> unknownModules;

    // the source objects that generated this object
    // the object that triggered the instantiation is first, followed by prototypes
    QList<LanguageObject *> objects;
};

class Loader::LoaderPrivate
{
public:
    LoaderPrivate(ScriptEngine *engine);

    void loadProject(const QString &fileName);
    ResolvedProjectPtr resolveProject(const QString &buildRoot,
                                        const QVariantMap &userProperties);
    ProjectFile::Ptr parseFile(const QString &fileName);

    void checkCancelation() const;
    void clearScopesCache();
    Scope::Ptr buildFileContext(ProjectFile *file);
    bool existsModuleInSearchPath(const QString &moduleName);
    Module::Ptr searchAndLoadModule(const QStringList &moduleId, const QString &moduleName, ScopeChain::Ptr moduleScope,
                                    const QVariantMap &userProperties, const CodeLocation &dependsLocation,
                                    const QStringList &extraSearchPaths = QStringList());
    Module::Ptr loadModule(ProjectFile *file, const QStringList &moduleId, const QString &moduleName, ScopeChain::Ptr moduleBaseScope,
                           const QVariantMap &userProperties, const CodeLocation &dependsLocation);
    void insertModulePropertyIntoScope(Scope::Ptr targetScope, const Module::Ptr &module, Scope::Ptr moduleInstance = Scope::Ptr());
    QList<Module::Ptr> evaluateDependency(LanguageObject *depends, ScopeChain::Ptr conditionScopeChain,
                                          ScopeChain::Ptr moduleScope, const QStringList &extraSearchPaths,
                                          QList<UnknownModule::Ptr> *unknownModules, const QVariantMap &userProperties);
    void evaluateDependencies(LanguageObject *object, EvaluationObject *evaluationObject, const ScopeChain::Ptr &localScope,
                              ScopeChain::Ptr moduleScope, const QVariantMap &userProperties, bool loadBaseModule = true);
    void evaluateDependencyConditions(EvaluationObject *evaluationObject);
    void evaluateImports(Scope::Ptr target, const JsImports &jsImports);
    void evaluatePropertyOptions(LanguageObject *object);
    QVariantMap evaluateAll(const ResolvedProductConstPtr &rproduct,
                            const Scope::Ptr &properties);
    QVariantMap evaluateModuleValues(const ResolvedProductConstPtr &rproduct,
                                     EvaluationObject *moduleContainer, Scope::Ptr objectScope);
    void resolveInheritance(LanguageObject *object, EvaluationObject *evaluationObject,
                            ScopeChain::Ptr moduleScope = ScopeChain::Ptr(), const QVariantMap &userProperties = QVariantMap());
    void fillEvaluationObject(const ScopeChain::Ptr &scope, LanguageObject *object, Scope::Ptr ids, EvaluationObject *evaluationObject, const QVariantMap &userProperties);
    void fillEvaluationObjectBasics(const ScopeChain::Ptr &scope, LanguageObject *object, EvaluationObject *evaluationObject);
    void setupBuiltinDeclarations();
    void setupInternalPrototype(LanguageObject *object, EvaluationObject *evaluationObject);
    void resolveModule(ResolvedProductPtr rproduct, const QString &moduleName, EvaluationObject *module);
    void resolveGroup(ResolvedProductPtr rproduct, EvaluationObject *product, EvaluationObject *group);
    void resolveProductModule(const ResolvedProductConstPtr &rproduct, EvaluationObject *group);
    void resolveTransformer(ResolvedProductPtr rproduct, EvaluationObject *trafo, ResolvedModuleConstPtr module);
    void resolveProbe(EvaluationObject *node);
    QList<EvaluationObject *> resolveCommonItems(const QList<EvaluationObject *> &objects,
                                                    ResolvedProductPtr rproduct, const ResolvedModuleConstPtr &module);
    RulePtr resolveRule(EvaluationObject *object, ResolvedModuleConstPtr module);
    FileTagger::ConstPtr resolveFileTagger(EvaluationObject *evaluationObject);
    void buildModulesProperty(EvaluationObject *evaluationObject);
    void checkModuleDependencies(const Module::Ptr &module);

    class ProductData
    {
    public:
        QString originalProductName;
        EvaluationObject *product;
        QList<UnknownModule::Ptr> usedProducts;
        QList<UnknownModule::Ptr> usedProductsFromProductModule;

        void addUsedProducts(const QList<UnknownModule::Ptr> &additionalUsedProducts, bool *productsAdded);
    };

    struct ProjectData
    {
        QHash<ResolvedProductPtr, ProductData> products;
        QList<ProductData> removedProducts;
    };

    void resolveTopLevel(const ResolvedProjectPtr &rproject,
                         LanguageObject *object,
                         const QString &projectFileName,
                         ProjectData *projectData,
                         QList<RulePtr> *globalRules,
                         QList<FileTagger::ConstPtr> *globalFileTaggers,
                         const QVariantMap &userProperties,
                         const ScopeChain::Ptr &scope,
                         const ResolvedModuleConstPtr &dummyModule);

    void checkUserProperties(const ProjectData &projectData, const QVariantMap &userProperties);
    typedef QMultiMap<QString, ResolvedProductPtr> ProductMap;
    void resolveProduct(const ResolvedProductPtr &product, const ResolvedProjectPtr &project,
                        ProductData &data, ProductMap &products,
                        const QList<RulePtr> &globalRules,
                        const QList<FileTagger::ConstPtr> &globalFileTaggers,
                        const ResolvedModuleConstPtr &dummyModule);
    void resolveProductDependencies(const ResolvedProjectPtr &project, ProjectData &projectData,
                                    const ProductMap &resolvedProducts);

    static LoaderPrivate *get(QScriptEngine *engine);
    static QScriptValue js_getHostOS(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_getHostDefaultArchitecture(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_getenv(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue js_configurationValue(QScriptContext *context, QScriptEngine *engine);

    ProgressObserver *m_progressObserver;
    QStringList m_searchPaths;
    QStringList m_moduleSearchPaths;
    ScriptEngine * const m_engine;
    ScopesCachePtr m_scopesWithEvaluatedProperties;
    QScriptValue m_jsFunction_getHostOS;
    QScriptValue m_jsFunction_getHostDefaultArchitecture;
    QScriptValue m_jsFunction_getenv;
    QScriptValue m_jsFunction_configurationValue;
    QScriptValue m_probeScriptScope;
    Settings m_settings;
    ProjectFile::Ptr m_project;
    QHash<QString, ProjectFile::Ptr> m_parsedFiles;
    QHash<QString, PropertyDeclaration> m_dependsPropertyDeclarations;
    QHash<QString, PropertyDeclaration> m_groupPropertyDeclarations;
    QHash<QString, QList<PropertyDeclaration> > m_builtinDeclarations;
    QHash<QString, QVariantMap> m_productModules;
    QHash<QString, QStringList> m_moduleDirListCache;
    QHash<Scope::ConstPtr, QVariantMap> m_convertedScopesCache;
    QHash<QString, ProjectFile::Ptr> m_projectFiles;
};

const QString dumpIndent("  ");
const QString moduleSearchSubDir = QLatin1String("modules");

CodeLocation Binding::codeLocation() const
{
    return CodeLocation(valueSource.fileName(), valueSource.firstLineNumber());
}

PropertyDeclaration::PropertyDeclaration()
    : type(UnknownType)
    , flags(DefaultFlags)
{
}

PropertyDeclaration::PropertyDeclaration(const QString &name, Type type, Flags flags)
    : name(name)
    , type(type)
    , flags(flags)
{
}

PropertyDeclaration::~PropertyDeclaration()
{
}

bool PropertyDeclaration::isValid() const
{
    return type != UnknownType;
}

LanguageObject::LanguageObject(ProjectFile *owner)
    : file(owner)
{
    file->registerLanguageObject(this);
}

LanguageObject::LanguageObject(const LanguageObject &other)
    : id(other.id)
    , prototype(other.prototype)
    , prototypeFileName(other.prototypeFileName)
    , prototypeLocation(other.prototypeLocation)
    , file(other.file)
    , bindings(other.bindings)
    , functions(other.functions)
    , propertyDeclarations(other.propertyDeclarations)
{
    file->registerLanguageObject(this);
    children.reserve(other.children.size());
    for (int i = 0; i < other.children.size(); ++i)
        children.append(new LanguageObject(*other.children.at(i)));
}

LanguageObject::~LanguageObject()
{
    if (!file->isDestructing())
        file->unregisterLanguageObject(this);
}

Property::Property(LanguageObject *sourceObject)
    : valueSourceUsesBase(false)
    , valueSourceUsesOuter(false)
    , sourceObject(sourceObject)
{}

Property::Property(QSharedPointer<Scope> scope)
    : valueSourceUsesBase(false)
    , valueSourceUsesOuter(false)
    , scope(scope)
    , sourceObject(0)
{}

Property::Property(EvaluationObject *object)
    : valueSourceUsesBase(false)
    , valueSourceUsesOuter(false)
    , scope(object->scope)
    , sourceObject(0)
{
}

Property::Property(const QScriptValue &scriptValue)
    : valueSourceUsesBase(false)
    , valueSourceUsesOuter(false)
    , value(scriptValue)
    , sourceObject(0)
{
}

ScopeChain::ScopeChain(QScriptEngine *engine, const QSharedPointer<Scope> &root)
    : QScriptClass(engine)
{
    m_value = engine->newObject(this);
    if (root)
        m_scopes.append(root);
}

ScopeChain::~ScopeChain()
{
}

ScopeChain *ScopeChain::clone() const
{
    ScopeChain *s = new ScopeChain(engine());
    s->m_scopes = m_scopes;
    return s;
}

QScriptValue ScopeChain::value()
{
    return m_value;
}

Scope::Ptr ScopeChain::first() const
{
    return m_scopes.first();
}

Scope::Ptr ScopeChain::last() const
{
    return m_scopes.last();
}

ScopeChain *ScopeChain::prepend(const QSharedPointer<Scope> &newTop)
{
    if (!newTop)
        return this;
    m_scopes.prepend(newTop);
    return this;
}

QSharedPointer<Scope> ScopeChain::findNonEmpty(const QString &name) const
{
    foreach (const Scope::Ptr &scope, m_scopes) {
        if (scope->name() == name && !scope->properties.isEmpty())
            return scope;
    }
    return Scope::Ptr();
}

QSharedPointer<Scope> ScopeChain::find(const QString &name) const
{
    foreach (const Scope::Ptr &scope, m_scopes) {
        if (scope->name() == name)
            return scope;
    }
    return Scope::Ptr();
}

Property ScopeChain::lookupProperty(const QString &name) const
{
    foreach (const Scope::Ptr &scope, m_scopes) {
        Property p = scope->properties.value(name);
        if (p.isValid())
            return p;
    }
    return Property();
}

ScopeChain::QueryFlags ScopeChain::queryProperty(const QScriptValue &object, const QScriptString &name,
                                       QueryFlags flags, uint *id)
{
    Q_UNUSED(object);
    Q_UNUSED(name);
    Q_UNUSED(id);
    return (HandlesReadAccess | HandlesWriteAccess) & flags;
}

QScriptValue ScopeChain::property(const QScriptValue &object, const QScriptString &name, uint id)
{
    Q_UNUSED(object);
    Q_UNUSED(id);
    QScriptValue value;
    foreach (const Scope::Ptr &scope, m_scopes) {
        value = scope->value.property(name);
        if (value.isError()) {
            engine()->clearExceptions();
        } else if (value.isValid()) {
            return value;
        }
    }
    value = engine()->globalObject().property(name);
    if (!value.isValid() || (value.isUndefined() && name.toString() != QLatin1String("undefined"))) {
        QString msg = Tr::tr("Undefined property '%1'");
        value = engine()->currentContext()->throwError(msg.arg(name.toString()));
    }
    return value;
}

void ScopeChain::setProperty(QScriptValue &, const QScriptString &name, uint, const QScriptValue &)
{
    QString msg = Tr::tr("Removing or setting property '%1' in a binding is invalid.");
    engine()->currentContext()->throwError(msg.arg(name.toString()));
}

static QScriptValue evaluate(QScriptEngine *engine, const QScriptProgram &expression)
{
    QScriptValue result = engine->evaluate(expression);
    if (engine->hasUncaughtException()) {
        QString errorMessage = engine->uncaughtException().toString();
        int errorLine = engine->uncaughtExceptionLineNumber();
        engine->clearExceptions();
        throw Error(errorMessage, expression.fileName(), errorLine);
    }
    if (result.isError())
        throw Error(result.toString());
    return result;
}

Scope::Scope(QScriptEngine *engine, ScopesCachePtr cache, const QString &name)
    : QScriptClass(engine)
    , m_scopesCache(cache)
    , m_name(name)
{
}

QSharedPointer<Scope> Scope::create(QScriptEngine *engine, ScopesCachePtr cache, const QString &name, ProjectFile *owner)
{
    QSharedPointer<Scope> obj(new Scope(engine, cache, name));
    obj->value = engine->newObject(obj.data());
    owner->registerScope(obj);
    return obj;
}

Scope::~Scope()
{
}

QString Scope::name() const
{
    return m_name;
}

static const bool debugProperties = false;

Scope::QueryFlags Scope::queryProperty(const QScriptValue &object, const QScriptString &name,
                                       QueryFlags flags, uint *id)
{
    const QString nameString = name.toString();
    if (properties.contains(nameString)) {
        *id = 0;
        return (HandlesReadAccess | HandlesWriteAccess) & flags;
    }
    if (fallbackScope && fallbackScope.data()->queryProperty(object, name, flags, id)) {
        *id = 1;
        return (HandlesReadAccess | HandlesWriteAccess) & flags;
    }

    QScriptValue proto = value.prototype();
    if (proto.isValid()) {
        QScriptValue v = proto.property(name);
        if (!v.isValid()) {
            *id = 2;
            return (HandlesReadAccess | HandlesWriteAccess) & flags;
        }
    }

    if (debugProperties)
        qbsTrace() << "PROPERTIES: we don't handle " << name.toString();
    return 0;
}

QScriptValue Scope::property(const QScriptValue &object, const QScriptString &name, uint id)
{
    if (id == 1)
        return fallbackScope.data()->property(object, name, 0);
    else if (id == 2) {
        QString msg = Tr::tr("Property %0.%1 is undefined.");
        return engine()->currentContext()->throwError(msg.arg(m_name, name));
    }

    const QString nameString = name.toString();

    Property property = properties.value(nameString);

    if (debugProperties)
        qbsTrace() << "PROPERTIES: evaluating " << nameString;

    if (!property.isValid()) {
        if (debugProperties)
            qbsTrace() << " : no such property";
        return QScriptValue(); // does this raise an error?
    }

    if (property.scope) {
        if (debugProperties)
            qbsTrace() << " : object property";
        return property.scope->value;
    }

    if (property.value.isValid()) {
        if (debugProperties)
            qbsTrace() << " : pre-evaluated property: " << property.value.toVariant();
        return property.value;
    }

    // evaluate now
    if (debugProperties)
        qbsTrace() << " : evaluating now: " << property.valueSource.sourceCode();
    QScriptContext *context = engine()->currentContext();
    const QScriptValue oldActivation = context->activationObject();

    // evaluate base properties
    QLatin1String baseValueName("base");
    if (property.valueSourceUsesBase) {
        foreach (const Property &baseProperty, property.baseProperties) {
            context->setActivationObject(baseProperty.scopeChain->value());
            QScriptValue baseValue;
            try {
                baseValue = evaluate(engine(), baseProperty.valueSource);
            } catch (const Error &e) {
                baseValue = engine()->currentContext()->throwError(Tr::tr("error while evaluating:\n%1").arg(e.toString()));
            }
            if (baseValue.isUndefined())
                baseValue = engine()->newArray();
            engine()->globalObject().setProperty(baseValueName, baseValue);
        }
    }

    context->setActivationObject(property.scopeChain->value());

    QLatin1String oldValueName("outer");
    const bool usesOldProperty = fallbackScope && property.valueSourceUsesOuter;
    if (usesOldProperty) {
        QScriptValue oldValue = fallbackScope.data()->value.property(name);
        if (oldValue.isValid() && !oldValue.isError())
            engine()->globalObject().setProperty(oldValueName, oldValue);
    }

    QScriptValue result;
    // Do not throw exceptions through the depths of the script engine.
    try {
        result = evaluate(engine(), property.valueSource);
    }
    catch (const Error &e)
    {
        result = engine()->currentContext()->throwError(Tr::tr("error while evaluating:\n%1").arg(e.toString()));
    }

    if (debugProperties) {
        qbsTrace() << "PROPERTIES: evaluated " << nameString << " to " << result.toVariant() << " " << result.toString();
        if (result.isError())
            qbsTrace() << "            was error!";
    }

    m_scopesCache->insert(this);
    property.value = result;
    properties.insert(nameString, property);

    if (usesOldProperty)
        engine()->globalObject().setProperty(oldValueName, engine()->undefinedValue());
    if (property.valueSourceUsesBase)
        engine()->globalObject().setProperty(baseValueName, engine()->undefinedValue());
    context->setActivationObject(oldActivation);

    return result;
}

QScriptValue Scope::property(const QString &name) const
{
    QScriptValue result = value.property(name);
    if (result.isError())
        throw Error(result.toString());
    return result;
}

bool Scope::boolValue(const QString &name, bool defaultValue) const
{
    QScriptValue scriptValue = property(name);
    if (scriptValue.isBool())
        return scriptValue.toBool();
    return defaultValue;
}

QString Scope::stringValue(const QString &name) const
{
    QScriptValue scriptValue = property(name);
    if (scriptValue.isString())
        return scriptValue.toString();
    QVariant v = scriptValue.toVariant();
    if (v.type() == QVariant::String) {
        return v.toString();
    } else if (v.type() == QVariant::StringList) {
        const QStringList lst = v.toStringList();
        if (lst.count() == 1)
            return lst.first();
    }
    return QString();
}

QStringList Scope::stringListValue(const QString &name) const
{
    return toStringList(property(name));
}

QString Scope::verbatimValue(const QString &name) const
{
    const Property &property = properties.value(name);
    return property.valueSource.sourceCode();
}

void Scope::dump(const QByteArray &aIndent) const
{
    QByteArray indent = aIndent;
    printf("%sScope: {\n", indent.constData());
    indent.append(dumpIndent);
    printf("%sName: '%s'\n", indent.constData(), qPrintable(m_name));
    if (!properties.isEmpty()) {
        printf("%sProperties: [\n", indent.constData());
        indent.append(dumpIndent);
        foreach (const QString &propertyName, properties.keys()) {
            QScriptValue scriptValue = property(propertyName);
            QString propertyValue;
            if (scriptValue.isString())
                propertyValue = stringValue(propertyName);
            else if (scriptValue.isArray())
                propertyValue = stringListValue(propertyName).join(", ");
            else if (scriptValue.isBool())
                propertyValue = boolValue(propertyName) ? "true" : "false";
            else
                propertyValue = verbatimValue(propertyName);
            printf("%s'%s': %s\n", indent.constData(), qPrintable(propertyName), qPrintable(propertyValue));
        }
        indent.chop(dumpIndent.length());
        printf("%s]\n", indent.constData());
    }
    if (!declarations.isEmpty())
        printf("%sPropertyDeclarations: [%s]\n", indent.constData(), qPrintable(QStringList(declarations.keys()).join(", ")));

    indent.chop(dumpIndent.length());
    printf("%s}\n", indent.constData());
}

void Scope::insertAndDeclareProperty(const QString &propertyName, const Property &property, PropertyDeclaration::Type propertyType)
{
    properties.insert(propertyName, property);
    declarations.insert(propertyName, PropertyDeclaration(propertyName, propertyType));
}

ProbeScope::ProbeScope(QScriptEngine *engine, const Scope::Ptr &scope)
    : QScriptClass(engine), m_scope(scope)
{
    m_value = engine->newObject(this);
    Property property = m_scope->properties.value("configure");
    m_scopeChain = property.scopeChain.staticCast<QScriptClass>();
}

ProbeScope::Ptr ProbeScope::create(QScriptEngine *engine, const Scope::Ptr &scope)
{
    return ProbeScope::Ptr(new ProbeScope(engine, scope));
}

ProbeScope::~ProbeScope()
{
}

QScriptValue ProbeScope::value()
{
    return m_value;
}

QScriptClass::QueryFlags ProbeScope::queryProperty(const QScriptValue &object, const QScriptString &name,
                                                           QScriptClass::QueryFlags flags, uint *id)
{
    Q_UNUSED(object);
    Q_UNUSED(name);
    Q_UNUSED(flags);
    Q_UNUSED(id);
    return (HandlesReadAccess | HandlesWriteAccess) & flags;
}

QScriptValue ProbeScope::property(const QScriptValue &object, const QScriptString &name, uint id)
{
    const QString nameString = name.toString();
    if (m_scope->properties.contains(nameString))
        return m_scope->property(name);
    QScriptValue proto = m_value.prototype();
    if (proto.isValid()) {
        QScriptValue value = proto.property(name);
        if (value.isValid())
            return value;
    }
    return m_scopeChain->property(object, name, id);
}

void ProbeScope::setProperty(QScriptValue &object, const QScriptString &name, uint id, const QScriptValue &value)
{
    const QString nameString = name.toString();
    if (nameString == "configure") {
        throw Error(Tr::tr("Can not access 'configure' property from itself"));
    } else if (m_scope->properties.contains(nameString)) {
        Property &property = m_scope->properties[nameString];
        property.value = value;
    } else {
        m_scopeChain->setProperty(object, name, id, value);
    }
}

EvaluationObject::EvaluationObject(LanguageObject *instantiatingObject)
{
    instantiatingObject->file->registerEvaluationObject(this);
    objects.append(instantiatingObject);
}

EvaluationObject::~EvaluationObject()
{
    ProjectFile *file = instantiatingObject()->file;
    if (!file->isDestructing())
        file->unregisterEvaluationObject(this);
}

LanguageObject *EvaluationObject::instantiatingObject() const
{
    return objects.first();
}

void EvaluationObject::dump(QByteArray &indent)
{
    printf("%sEvaluationObject: {\n", indent.constData());
    indent.append(dumpIndent);
    printf("%sProtoType: '%s'\n", indent.constData(), qPrintable(prototype));
    if (!modules.isEmpty()) {
        printf("%sModules: [\n", indent.constData());
        indent.append(dumpIndent);
        foreach (const QSharedPointer<Module> module, modules)
            module->dump(indent);
        indent.chop(dumpIndent.length());
        printf("%s]\n", indent.constData());
    }
    scope->dump(indent);
    foreach (EvaluationObject *child, children)
        child->dump(indent);
    indent.chop(dumpIndent.length());
    printf("%s}\n", indent.constData());
}

Module::Module()
    : object(0)
    , dependsCount(0)
{
}

Module::~Module()
{
}

ProjectFile *Module::file() const
{
    return object->instantiatingObject()->file;
}

void Module::dump(QByteArray &indent)
{
    printf("%s'%s': %s\n", indent.constData(), qPrintable(name), qPrintable(dependsLocation.fileName));
}

static QStringList resolvePaths(const QStringList &paths, const QString &base)
{
    QStringList resolved;
    foreach (const QString &path, paths) {
        QString resolvedPath = FileInfo::resolvePath(base, path);
        resolvedPath = QDir::cleanPath(resolvedPath);
        resolved += resolvedPath;
    }
    return resolved;
}


static const char szLoaderPropertyName[] = "qbs_loader_ptr";
static const QLatin1String name_FileTagger("FileTagger");
static const QLatin1String name_Rule("Rule");
static const QLatin1String name_Transformer("Transformer");
static const QLatin1String name_Artifact("Artifact");
static const QLatin1String name_Group("Group");
static const QLatin1String name_Project("Project");
static const QLatin1String name_Product("Product");
static const QLatin1String name_ProductModule("ProductModule");
static const QLatin1String name_Module("Module");
static const QLatin1String name_Properties("Properties");
static const QLatin1String name_PropertyOptions("PropertyOptions");
static const QLatin1String name_Depends("Depends");
static const QLatin1String name_moduleSearchPaths("moduleSearchPaths");
static const QLatin1String name_Probe("Probe");
static const uint hashName_FileTagger = qHash(name_FileTagger);
static const uint hashName_Rule = qHash(name_Rule);
static const uint hashName_Transformer = qHash(name_Transformer);
static const uint hashName_Artifact = qHash(name_Artifact);
static const uint hashName_Group = qHash(name_Group);
static const uint hashName_Project = qHash(name_Project);
static const uint hashName_Product = qHash(name_Product);
static const uint hashName_ProductModule = qHash(name_ProductModule);
static const uint hashName_Module = qHash(name_Module);
static const uint hashName_Properties = qHash(name_Properties);
static const uint hashName_PropertyOptions = qHash(name_PropertyOptions);
static const uint hashName_Depends = qHash(name_Depends);
static const uint hashName_Probe = qHash(name_Probe);
static const QLatin1String name_productPropertyScope("product property scope");
static const QLatin1String name_projectPropertyScope("project property scope");

Loader::Loader(ScriptEngine *engine) : d(new LoaderPrivate(engine))
{
}

Loader::~Loader()
{
    delete d;
}

void Loader::setProgressObserver(ProgressObserver *observer)
{
    d->m_progressObserver = observer;
}

static bool compare(const QStringList &list, const QString &value)
{
    if (list.size() != 1)
        return false;
    return list.first() == value;
}

void Loader::setSearchPaths(const QStringList &searchPaths)
{
    d->m_searchPaths.clear();
    foreach (const QString &searchPath, searchPaths) {
        if (!FileInfo::exists(searchPath)) {
            qbsWarning() << Tr::tr("Search path '%1' does not exist.")
                    .arg(QDir::toNativeSeparators(searchPath));
        } else {
            d->m_searchPaths << searchPath;
        }
    }

    d->m_moduleSearchPaths.clear();
    foreach (const QString &path, d->m_searchPaths)
        d->m_moduleSearchPaths += FileInfo::resolvePath(path, moduleSearchSubDir);
}

ResolvedProjectPtr Loader::loadProject(const QString &fileName, const QString &buildRoot,
                                         const QVariantMap &userProperties)
{
    TimedActivityLogger loadLogger(QLatin1String("Loading project"));
    d->loadProject(fileName);
    return d->resolveProject(buildRoot, userProperties);
}

QByteArray Loader::qmlTypeInfo()
{
    // Header:
    QByteArray result;
    result.append("import QtQuick.tooling 1.0\n\n");
    result.append("// This file describes the plugin-supplied types contained in the library.\n");
    result.append("// It is used for QML tooling purposes only.\n\n");
    result.append("Module {\n");

    // Individual Components:
    foreach (const QString &component, d->m_builtinDeclarations.keys()) {
        QByteArray componentName = component.toUtf8();
        result.append("    Component {\n");
        result.append(QByteArray("        name: \"") + componentName + QByteArray("\"\n"));
        result.append("        exports: [ \"qbs/");
        result.append(componentName);
        result.append(" ");
        result.append(QBS_LANGUAGE_VERSION);
        result.append("\" ]\n");
        result.append("        prototype: \"QQuickItem\"\n");

        QList<PropertyDeclaration> propertyList = d->m_builtinDeclarations.value(component);
        foreach (const PropertyDeclaration &property, propertyList) {
            result.append("        Property { name=\"");
            result.append(property.name.toUtf8());
            result.append("\"; ");
            switch (property.type) {
            case qbs::Internal::PropertyDeclaration::UnknownType:
                result.append("type=\"unknown\"");
                break;
            case qbs::Internal::PropertyDeclaration::Boolean:
                result.append("type=\"bool\"");
                break;
            case qbs::Internal::PropertyDeclaration::Path:
                result.append("type=\"string\"");
                break;
            case qbs::Internal::PropertyDeclaration::PathList:
                result.append("type=\"string\"; isList=true");
                break;
            case qbs::Internal::PropertyDeclaration::String:
                result.append("type=\"string\"");
                break;
            case qbs::Internal::PropertyDeclaration::Variant:
                result.append("type=\"QVariant\"");
                break;
            case qbs::Internal::PropertyDeclaration::Verbatim:
                result.append("type=\"string\"");
                break;
            }
            result.append(" }\n"); // Property
        }

        result.append("    }\n"); // Component
    }

    // Footer:
    result.append("}\n"); // Module
    return result;
}

Loader::LoaderPrivate::LoaderPrivate(ScriptEngine *engine)
    : m_progressObserver(0), m_engine(engine), m_scopesWithEvaluatedProperties(new ScopesCache)
{
    QVariant v;
    v.setValue(static_cast<void*>(this));
    engine->setProperty(szLoaderPropertyName, v);

    m_jsFunction_getHostOS  = engine->newFunction(js_getHostOS, 0);
    m_jsFunction_getHostDefaultArchitecture
            = engine->newFunction(js_getHostDefaultArchitecture, 0);
    m_jsFunction_getenv = engine->newFunction(js_getenv, 0);
    m_jsFunction_configurationValue = engine->newFunction(js_configurationValue, 2);
    setupBuiltinDeclarations();
}

void Loader::LoaderPrivate::loadProject(const QString &fileName)
{
    m_moduleDirListCache.clear();
    m_settings.loadProjectSettings(fileName);
    m_project = parseFile(fileName);
}

static void setPathAndFilePath(const Scope::Ptr &scope, const QString &filePath, const QString &prefix = QString())
{
    QString filePathPropertyName("filePath");
    QString pathPropertyName("path");
    if (!prefix.isEmpty()) {
        filePathPropertyName = prefix + QLatin1String("FilePath");
        pathPropertyName = prefix + QLatin1String("Path");
    }
    scope->properties.insert(filePathPropertyName, Property(QScriptValue(filePath)));
    scope->properties.insert(pathPropertyName, Property(QScriptValue(FileInfo::path(filePath))));
}

void Loader::LoaderPrivate::clearScopesCache()
{
    QScriptValue nullScriptValue;
    ScopesCache::const_iterator it = m_scopesWithEvaluatedProperties->begin();
    const ScopesCache::const_iterator scopeEnd = m_scopesWithEvaluatedProperties->end();
    for (; it != scopeEnd; ++it) {
        const QHash<QString, Property>::iterator propertiesEnd = (*it)->properties.end();
        for (QHash<QString, Property>::iterator pit = (*it)->properties.begin(); pit != propertiesEnd; ++pit) {
            Property &property = pit.value();
            if (!property.valueSource.isNull())
                property.value = nullScriptValue;
        }
    }
    m_scopesWithEvaluatedProperties->clear();
}

Scope::Ptr Loader::LoaderPrivate::buildFileContext(ProjectFile *file)
{
    Scope::Ptr context = Scope::create(m_engine, m_scopesWithEvaluatedProperties,
                                       QLatin1String("global file context"), file);
    setPathAndFilePath(context, file->fileName, QLatin1String("local"));
    evaluateImports(context, file->jsImports);

    return context;
}

bool Loader::LoaderPrivate::existsModuleInSearchPath(const QString &moduleName)
{
    foreach (const QString &dirPath, m_moduleSearchPaths)
        if (FileInfo(dirPath + QLatin1Char('/') + moduleName).exists())
            return true;
    return false;
}

void Loader::LoaderPrivate::resolveInheritance(LanguageObject *object, EvaluationObject *evaluationObject,
                                ScopeChain::Ptr moduleScope, const QVariantMap &userProperties)
{
    if (object->prototypeFileName.isEmpty()) {
        if (object->prototype.size() != 1)
            throw Error(Tr::tr("prototype with dots does not resolve to a file"), object->prototypeLocation);
        evaluationObject->prototype = object->prototype.first();

        setupInternalPrototype(object, evaluationObject);

        // once we know something is a project/product, add a property to
        // the correct scope
        if (moduleScope) {
            if (evaluationObject->prototype == name_Project) {
                if (Scope::Ptr projectPropertyScope = moduleScope->find(name_projectPropertyScope))
                    projectPropertyScope->properties.insert("project", Property(evaluationObject));
            }
            else if (evaluationObject->prototype == name_Product) {
                if (Scope::Ptr productPropertyScope = moduleScope->find(name_productPropertyScope))
                    productPropertyScope->properties.insert("product", Property(evaluationObject));
            }
        }

        return;
    }

    // load prototype (cache result)
    ProjectFile::Ptr file = parseFile(object->prototypeFileName);

    // recurse to prototype's prototype
    if (evaluationObject->objects.contains(file->root)) {
        QString msg = Tr::tr("circular prototypes in instantiation of '%1', '%2' recurred");
        throw Error(msg.arg(evaluationObject->instantiatingObject()->prototype.join("."),
                                   object->prototype.join(".")));
    }
    evaluationObject->objects.append(file->root);
    resolveInheritance(file->root, evaluationObject, moduleScope, userProperties);

    // ### expensive, and could be shared among all builds of this prototype instance
    Scope::Ptr context = buildFileContext(file.data());

    // project and product scopes are always available
    ScopeChain::Ptr scopeChain(new ScopeChain(m_engine, context));
    if (moduleScope) {
        if (Scope::Ptr projectPropertyScope = moduleScope->findNonEmpty(name_projectPropertyScope))
            scopeChain->prepend(projectPropertyScope);
        if (Scope::Ptr productPropertyScope = moduleScope->findNonEmpty(name_productPropertyScope))
            scopeChain->prepend(productPropertyScope);
    }

    scopeChain->prepend(evaluationObject->scope);

    // having a module scope enables resolving of Depends blocks
    if (moduleScope)
        evaluateDependencies(file->root, evaluationObject, scopeChain, moduleScope, userProperties);

    fillEvaluationObject(scopeChain, file->root, evaluationObject->scope, evaluationObject, userProperties);

//    QByteArray indent;
//    evaluationObject->dump(indent);
}

static bool checkFileCondition(QScriptEngine *engine, const ScopeChain::Ptr &scope, const ProjectFile *file)
{
    static const bool debugCondition = false;
    if (debugCondition)
        qbsTrace() << "Checking condition";

    const Binding &condition = file->root->bindings.value(QStringList("condition"));
    if (!condition.isValid())
        return true;

    QScriptContext *context = engine->currentContext();
    const QScriptValue oldActivation = context->activationObject();
    context->setActivationObject(scope->value());

    if (debugCondition)
        qbsTrace() << "   code is: " << condition.valueSource.sourceCode();
    const QScriptValue value = evaluate(engine, condition.valueSource);
    bool result = false;
    if (value.isBool())
        result = value.toBool();
    else
        throw Error(Tr::tr("Condition return type must be boolean."), condition.codeLocation());
    if (debugCondition)
        qbsTrace() << "   result: " << value.toString();

    context->setActivationObject(oldActivation);
    return result;
}

static void applyFunctions(QScriptEngine *engine, LanguageObject *object, EvaluationObject *evaluationObject)
{
    foreach (const Function &func, object->functions) {
        Property property;
        property.value = evaluate(engine, func.source);
        evaluationObject->scope->properties.insert(func.name, property);
    }
}

static void applyFunctions(QScriptEngine *engine, LanguageObject *object, EvaluationObject *evaluationObject, const QScriptValue &value)
{
    if (object->functions.isEmpty())
        return;

    // set the activation object to the correct scope
    QScriptValue oldActivation = engine->currentContext()->activationObject();
    engine->currentContext()->setActivationObject(value);

    applyFunctions(engine, object, evaluationObject);

    engine->currentContext()->setActivationObject(oldActivation);
}

static void applyFunctions(QScriptEngine *engine, LanguageObject *object, EvaluationObject *evaluationObject, ScopeChain::Ptr scope)
{
    return applyFunctions(engine, object, evaluationObject, scope->value());
}

static void applyBinding(LanguageObject *object, const Binding &binding, const ScopeChain::Ptr &scopeChain)
{
    Scope *target;
    if (binding.name.size() == 1) {
        target = scopeChain->first().data(); // assume the top scope is the 'current' one
    } else {
        if (compare(object->prototype, name_Artifact))
            return;
        QScriptValue targetValue = scopeChain->value().property(binding.name.first());
        if (!targetValue.isValid() || targetValue.isError()) {
            QString msg = Tr::tr("Binding '%1' failed, no property '%2' in the scope of %3");
            throw Error(msg.arg(binding.name.join("."),
                                       binding.name.first(),
                                       scopeChain->first()->name()),
                               binding.codeLocation());
        }
        target = dynamic_cast<Scope *>(targetValue.scriptClass());
        if (!target) {
            QString msg = Tr::tr("Binding '%1' failed, property '%2' in the scope of %3 has no properties");
            throw Error(msg.arg(binding.name.join("."),
                                       binding.name.first(),
                                       scopeChain->first()->name()),
                               binding.codeLocation());
        }
    }

    for (int i = 1; i < binding.name.size() - 1; ++i) {
        Scope *oldTarget = target;
        const QString &bindingName = binding.name.at(i);
        const QScriptValue &value = target->property(bindingName);
        if (!value.isValid()) {
            QString msg = Tr::tr("Binding '%1' failed, no property '%2' in %3");
            throw Error(msg.arg(binding.name.join("."),
                                       binding.name.at(i),
                                       target->name()),
                               binding.codeLocation());
        }
        target = dynamic_cast<Scope *>(value.scriptClass());
        if (!target) {
            QString msg = Tr::tr("Binding '%1' failed, property '%2' in %3 has no properties");
            throw Error(msg.arg(binding.name.join("."),
                                       bindingName,
                                       oldTarget->name()),
                               binding.codeLocation());
        }
    }

    const QString name = binding.name.last();

    if (!target->declarations.contains(name)) {
        QString msg = Tr::tr("Binding '%1' failed, no property '%2' in %3");
        throw Error(msg.arg(binding.name.join("."),
                                   name,
                                   target->name()),
                           binding.codeLocation());
    }

    Property newProperty;
    newProperty.valueSource = binding.valueSource;
    newProperty.valueSourceUsesBase = binding.valueSourceUsesBase;
    newProperty.valueSourceUsesOuter = binding.valueSourceUsesOuter;
    newProperty.scopeChain = scopeChain;
    newProperty.sourceObject = object;

    Property &property = target->properties[name];
    if (!property.valueSource.isNull()) {
        newProperty.baseProperties += property.baseProperties;
        property.baseProperties.clear();
        newProperty.baseProperties += property;
    }
    property = newProperty;
}

static void applyBindings(LanguageObject *object, const ScopeChain::Ptr &scopeChain)
{
    foreach (const Binding &binding, object->bindings)
        applyBinding(object, binding, scopeChain);
}

void Loader::LoaderPrivate::setupInternalPrototype(LanguageObject *object, EvaluationObject *evaluationObject)
{
    if (!m_builtinDeclarations.contains(evaluationObject->prototype))
        throw Error(Tr::tr("Type name '%1' is unknown.").arg(evaluationObject->prototype),
                           evaluationObject->instantiatingObject()->prototypeLocation);

    foreach (const PropertyDeclaration &pd, m_builtinDeclarations.value(evaluationObject->prototype)) {
        evaluationObject->scope->declarations.insert(pd.name, pd);
        evaluationObject->scope->properties.insert(pd.name, Property(m_engine->undefinedValue()));

        // If there's an initial value and the language object doesn't have a binding for that property, create one.
        if (!pd.initialValueSource.isEmpty()) {
            const QStringList bindingName(pd.name);
            Binding &binding = object->bindings[bindingName];
            if (!binding.isValid()) {
                binding.name = bindingName;
                binding.valueSource = QScriptProgram(pd.initialValueSource);
            }
        }
    }
}

struct ConditionalBinding
{
    QString condition;
    QString rhs;
};

void Loader::LoaderPrivate::fillEvaluationObject(const ScopeChain::Ptr &scope, LanguageObject *object, Scope::Ptr ids, EvaluationObject *evaluationObject, const QVariantMap &userProperties)
{
    // filter Properties items
    typedef QHash<QStringList, QVector<ConditionalBinding> > ConditionalBindings;
    ConditionalBindings conditionalBindings;
    QList<LanguageObject *>::iterator childIt = object->children.begin();
    while (childIt != object->children.end()) {
        LanguageObject *propertiesItem = *childIt;
        if (!compare(propertiesItem->prototype, name_Properties)) {
            ++childIt;
            continue;
        }
        childIt = object->children.erase(childIt);

        if (!propertiesItem->children.isEmpty())
            throw Error(Tr::tr("Properties block may not have children"), propertiesItem->children.first()->prototypeLocation);

        const QStringList conditionName("condition");
        const Binding condition = propertiesItem->bindings.value(conditionName);
        if (!condition.isValid())
            throw Error(Tr::tr("Properties block must have a condition property"), propertiesItem->prototypeLocation);

        const QString conditionCode = condition.valueSource.sourceCode();
        QHashIterator<QStringList, Binding> it(propertiesItem->bindings);
        while (it.hasNext()) {
            it.next();
            if (it.key() == conditionName)
                continue;

            const Binding &binding = it.value();
            ConditionalBinding conditionalBinding;
            conditionalBinding.condition = conditionCode;
            conditionalBinding.rhs = binding.valueSource.sourceCode();
            conditionalBindings[binding.name] += conditionalBinding;
        }
    }

    // rewrite conditional bindings
    for (ConditionalBindings::const_iterator it = conditionalBindings.constBegin(); it != conditionalBindings.constEnd(); ++it) {
        const QStringList &bindingName = it.key();
        Binding &parentBinding = object->bindings[bindingName];
        QString rewrittenSource = QLatin1String("(function() {\n"
                                                "var outer = ");
        if (parentBinding.isValid()) {
            rewrittenSource += parentBinding.valueSource.sourceCode() + QLatin1Char('\n');
        } else {
            rewrittenSource += QLatin1String("undefined\n");
            parentBinding.name = bindingName;
        }

        foreach (const ConditionalBinding &cb, it.value())
            rewrittenSource += QLatin1String("if (") + cb.condition
                    + QLatin1String(") outer = ") + cb.rhs + QLatin1Char('\n');

        rewrittenSource += QLatin1String("return outer})()");
        parentBinding.valueSource = rewrittenSource;
    }

    // fill subobjects recursively
    foreach (LanguageObject *child, object->children) {
        // 'Depends' blocks are already handled before this function is called
        // and should not appear in the children list
        if (compare(child->prototype, name_Depends))
            continue;

        EvaluationObject *childEvObject = new EvaluationObject(child);
        const QString propertiesName = child->prototype.join(QLatin1String("."));
        childEvObject->scope = Scope::create(m_engine, m_scopesWithEvaluatedProperties,
                                             propertiesName, object->file);

        resolveInheritance(child, childEvObject); // ### need to pass 'moduleScope' for product/project property scopes
        const uint childPrototypeHash = qHash(childEvObject->prototype);

        ScopeChain::Ptr childScope(scope->clone()->prepend(childEvObject->scope));

        if (!child->id.isEmpty()) {
            ids->properties.insert(child->id, Property(childEvObject));
        }

        const bool isProductModule = (childPrototypeHash == hashName_ProductModule);
        const bool isArtifact = (childPrototypeHash == hashName_Artifact);
        if (isProductModule) {
            // give ProductModules their own module namespace
            childScope = ScopeChain::Ptr(new ScopeChain(m_engine, childEvObject->scope));
            ScopeChain::Ptr moduleScope(new ScopeChain(m_engine));
            moduleScope->prepend(scope->findNonEmpty(name_productPropertyScope));
            moduleScope->prepend(scope->findNonEmpty(name_projectPropertyScope));
            moduleScope->prepend(childEvObject->scope);
            Property productProperty(evaluationObject);
            childEvObject->scope->properties.insert("product", productProperty);
            Property projectProperty(scope->lookupProperty("project"));
            childEvObject->scope->properties.insert("project", projectProperty);
            evaluateDependencies(child, childEvObject, childScope, moduleScope, userProperties);
        } else if (isArtifact || childPrototypeHash == hashName_Group) {
            // for Group and Artifact, add new module instances
            QHashIterator<QString, Module::Ptr> moduleIt(evaluationObject->modules);
            while (moduleIt.hasNext()) {
                moduleIt.next();
                Module::Ptr module = moduleIt.value();
                if (module->id.isEmpty())
                    continue;

                Scope::Ptr moduleInstance = Scope::create(m_engine,
                                                          m_scopesWithEvaluatedProperties,
                                                          module->object->scope->name(),
                                                          module->file());
                if (!isArtifact)
                    moduleInstance->fallbackScope = module->object->scope;
                moduleInstance->declarations = module->object->scope->declarations;
                insertModulePropertyIntoScope(childEvObject->scope, module, moduleInstance);
            }
        } else if (childPrototypeHash == hashName_Probe) {
            Module::Ptr baseModule = searchAndLoadModule(QStringList("qbs"), QLatin1String("qbs"),
                                                         childScope, userProperties, CodeLocation(object->file->fileName));
            if (!baseModule)
                throw Error(Tr::tr("Cannot load the qbs base module."));
            childEvObject->modules.insert(baseModule->name, baseModule);
            childEvObject->scope->properties.insert(baseModule->id.first(), Property(baseModule->object));
        }

        fillEvaluationObject(childScope, child, ids, childEvObject, userProperties);
        evaluationObject->children.append(childEvObject);
    }

    fillEvaluationObjectBasics(scope, object, evaluationObject);
}

void Loader::LoaderPrivate::fillEvaluationObjectBasics(const ScopeChain::Ptr &scopeChain, LanguageObject *object, EvaluationObject *evaluationObject)
{
    // append the property declarations
    foreach (const PropertyDeclaration &pd, object->propertyDeclarations) {
        PropertyDeclaration &scopePropertyDeclaration = evaluationObject->scope->declarations[pd.name];
        if (!scopePropertyDeclaration.isValid())
            scopePropertyDeclaration = pd;
    }

    applyFunctions(m_engine, object, evaluationObject, scopeChain);
    applyBindings(object, scopeChain);
}

void Loader::LoaderPrivate::setupBuiltinDeclarations()
{
    QList<PropertyDeclaration> decls;
    decls += PropertyDeclaration("name", PropertyDeclaration::String);
    decls += PropertyDeclaration("submodules", PropertyDeclaration::Variant);
    decls += PropertyDeclaration("condition", PropertyDeclaration::Boolean);
    decls += PropertyDeclaration("required", PropertyDeclaration::Boolean);
    decls += PropertyDeclaration("failureMessage", PropertyDeclaration::String);
    foreach (const PropertyDeclaration &pd, decls)
        m_dependsPropertyDeclarations.insert(pd.name, pd);

    decls.clear();
    decls += PropertyDeclaration("condition", PropertyDeclaration::Boolean);
    decls += PropertyDeclaration("name", PropertyDeclaration::String, PropertyDeclaration::PropertyNotAvailableInConfig);
    decls += PropertyDeclaration("files", PropertyDeclaration::Variant, PropertyDeclaration::PropertyNotAvailableInConfig);
    decls += PropertyDeclaration("excludeFiles", PropertyDeclaration::Variant, PropertyDeclaration::PropertyNotAvailableInConfig);
    PropertyDeclaration recursiveProperty("recursive", PropertyDeclaration::Boolean, PropertyDeclaration::PropertyNotAvailableInConfig);
    recursiveProperty.initialValueSource = "false";
    decls += recursiveProperty;
    decls += PropertyDeclaration("fileTags", PropertyDeclaration::Variant, PropertyDeclaration::PropertyNotAvailableInConfig);
    decls += PropertyDeclaration("prefix", PropertyDeclaration::Variant, PropertyDeclaration::PropertyNotAvailableInConfig);

    PropertyDeclaration declaration;
    declaration.name = "overrideTags";
    declaration.type = PropertyDeclaration::Boolean;
    declaration.flags = PropertyDeclaration::PropertyNotAvailableInConfig;
    declaration.initialValueSource = "true";
    decls += declaration;

    foreach (const PropertyDeclaration &pd, decls)
        m_groupPropertyDeclarations.insert(pd.name, pd);

    m_builtinDeclarations.insert(name_Depends, m_dependsPropertyDeclarations.values());
    m_builtinDeclarations.insert(name_Group, m_groupPropertyDeclarations.values());
    PropertyDeclaration conditionProperty("condition", PropertyDeclaration::Boolean);

    QList<PropertyDeclaration> project;
    project += PropertyDeclaration("references", PropertyDeclaration::Variant);
    project += PropertyDeclaration(name_moduleSearchPaths, PropertyDeclaration::Variant);
    m_builtinDeclarations.insert(name_Project, project);

    QList<PropertyDeclaration> product;
    product += PropertyDeclaration("condition", PropertyDeclaration::Boolean);
    product += PropertyDeclaration("type", PropertyDeclaration::String);
    product += PropertyDeclaration("name", PropertyDeclaration::String);
    PropertyDeclaration decl = PropertyDeclaration("targetName", PropertyDeclaration::String);
    decl.initialValueSource = "name";
    product += decl;
    product += PropertyDeclaration("destination", PropertyDeclaration::String);
    product += PropertyDeclaration("consoleApplication", PropertyDeclaration::Boolean);
    product += PropertyDeclaration("files", PropertyDeclaration::Variant, PropertyDeclaration::PropertyNotAvailableInConfig);
    product += PropertyDeclaration("module", PropertyDeclaration::Variant);
    product += PropertyDeclaration("modules", PropertyDeclaration::Variant);
    product += PropertyDeclaration(name_moduleSearchPaths, PropertyDeclaration::Variant);
    m_builtinDeclarations.insert(name_Product, product);

    QList<PropertyDeclaration> fileTagger;
    fileTagger += PropertyDeclaration("pattern", PropertyDeclaration::String);
    fileTagger += PropertyDeclaration("fileTags", PropertyDeclaration::Variant);
    m_builtinDeclarations.insert(name_FileTagger, fileTagger);

    QList<PropertyDeclaration> artifact;
    artifact += conditionProperty;
    artifact += PropertyDeclaration("fileName", PropertyDeclaration::Verbatim);
    artifact += PropertyDeclaration("fileTags", PropertyDeclaration::Variant);
    artifact += PropertyDeclaration("alwaysUpdated", PropertyDeclaration::Boolean);
    m_builtinDeclarations.insert(name_Artifact, artifact);

    QList<PropertyDeclaration> rule;
    rule += PropertyDeclaration("multiplex", PropertyDeclaration::Boolean);
    rule += PropertyDeclaration("inputs", PropertyDeclaration::Variant);
    rule += PropertyDeclaration("usings", PropertyDeclaration::Variant);
    rule += PropertyDeclaration("explicitlyDependsOn", PropertyDeclaration::Variant);
    rule += PropertyDeclaration("prepare", PropertyDeclaration::Verbatim);
    m_builtinDeclarations.insert(name_Rule, rule);

    QList<PropertyDeclaration> transformer;
    transformer += PropertyDeclaration("inputs", PropertyDeclaration::Variant);
    transformer += PropertyDeclaration("prepare", PropertyDeclaration::Verbatim);
    transformer += conditionProperty;
    m_builtinDeclarations.insert(name_Transformer, transformer);

    QList<PropertyDeclaration> productModule;
    m_builtinDeclarations.insert(name_ProductModule, productModule);

    QList<PropertyDeclaration> module;
    module += PropertyDeclaration("name", PropertyDeclaration::String);
    module += PropertyDeclaration("setupBuildEnvironment", PropertyDeclaration::Verbatim);
    module += PropertyDeclaration("setupRunEnvironment", PropertyDeclaration::Verbatim);
    module += PropertyDeclaration("additionalProductFileTags", PropertyDeclaration::Variant);
    module += conditionProperty;
    m_builtinDeclarations.insert(name_Module, module);

    QList<PropertyDeclaration> propertyOptions;
    propertyOptions += PropertyDeclaration("name", PropertyDeclaration::String);
    propertyOptions += PropertyDeclaration("allowedValues", PropertyDeclaration::Variant);
    propertyOptions += PropertyDeclaration("description", PropertyDeclaration::String);
    m_builtinDeclarations.insert(name_PropertyOptions, propertyOptions);

    QList<PropertyDeclaration> probe;
    probe += PropertyDeclaration("condition", PropertyDeclaration::Boolean);
    PropertyDeclaration foundProperty("found", PropertyDeclaration::Boolean);
    foundProperty.initialValueSource = "false";
    probe += foundProperty;
    probe += PropertyDeclaration("configure", PropertyDeclaration::Verbatim);
    m_builtinDeclarations.insert(name_Probe, probe);
}

void Loader::LoaderPrivate::evaluateImports(Scope::Ptr target, const JsImports &jsImports)
{
    QScriptValue importScope;
    for (JsImports::const_iterator it = jsImports.begin(); it != jsImports.end(); ++it) {
        QScriptValue targetObject = m_engine->newObject();
        m_engine->import(*it, importScope, targetObject);
        target->properties.insert(it->scopeName, Property(targetObject.property(it->scopeName)));
    }
}

void Loader::LoaderPrivate::evaluatePropertyOptions(LanguageObject *object)
{
    foreach (LanguageObject *child, object->children) {
        if (child->prototype.last() != name_PropertyOptions)
            continue;

        const Binding nameBinding = child->bindings.value(QStringList("name"));

        if (!nameBinding.isValid())
            throw Error(name_PropertyOptions + " needs to define a 'name'");

        const QScriptValue nameScriptValue = evaluate(m_engine, nameBinding.valueSource);
        const QString name = nameScriptValue.toString();

        if (!object->propertyDeclarations.contains(name))
            throw Error(Tr::tr("no propery with name '%1' found").arg(name));

        PropertyDeclaration &decl = object->propertyDeclarations[name];

        const Binding allowedValuesBinding = child->bindings.value(QStringList("allowedValues"));
        if (allowedValuesBinding.isValid())
            decl.allowedValues = evaluate(m_engine, allowedValuesBinding.valueSource);

        const Binding descriptionBinding = child->bindings.value(QStringList("description"));
        if (descriptionBinding.isValid()) {
            const QScriptValue description = evaluate(m_engine, descriptionBinding.valueSource);
            decl.description = description.toString();
        }
    }
}

static void checkAllowedPropertyValues(const PropertyDeclaration &decl, const QScriptValue &value)
{
    if (!decl.allowedValues.isValid())
        return;

    if (decl.allowedValues.isArray()) {
        QScriptValue length = decl.allowedValues.property("length");
        if (length.isNumber()) {
            const int c = length.toInt32();
            for (int i = 0; i < c; ++i) {
                QScriptValue allowedValue = decl.allowedValues.property(i);
                if (allowedValue.equals(value))
                    return;
            }
        }
    } else if (decl.allowedValues.equals(value)) {
        return;
    }

    QString msg = Tr::tr("value %1 not allowed in property %2").arg(value.toString(), decl.name);
    throw Error(msg);
}

static QString sourceDirPath(const Property &property, const ResolvedProductConstPtr &rproduct)
{
    return property.sourceObject
            ? FileInfo::path(property.sourceObject->file->fileName) : rproduct->sourceDirectory;
}

QVariantMap Loader::LoaderPrivate::evaluateAll(const ResolvedProductConstPtr &rproduct,
                                const Scope::Ptr &properties)
{
    checkCancelation();
    QVariantMap &result = m_convertedScopesCache[properties];
    if (!result.isEmpty())
        return result;

    if (properties->fallbackScope)
        result = evaluateAll(rproduct, properties->fallbackScope);

    typedef QHash<QString, PropertyDeclaration>::const_iterator iter;
    iter end = properties->declarations.end();
    for (iter it = properties->declarations.begin(); it != end; ++it) {
        const PropertyDeclaration &decl = it.value();
        if (decl.type == PropertyDeclaration::Verbatim
            || decl.flags.testFlag(PropertyDeclaration::PropertyNotAvailableInConfig))
        {
            continue;
        }

        Property property = properties->properties.value(it.key());
        if (!property.isValid())
            continue;

        QVariant value;
        if (property.scope) {
            value = evaluateAll(rproduct, property.scope);
        } else {
            QScriptValue scriptValue = properties->property(it.key());
            checkAllowedPropertyValues(decl, scriptValue);
            value = scriptValue.toVariant();
        }

        if (decl.type == PropertyDeclaration::Path) {
            QString fileName = value.toString();
            if (!fileName.isEmpty())
                value = FileInfo::resolvePath(sourceDirPath(property, rproduct), fileName);
        } else if (decl.type == PropertyDeclaration::PathList) {
            QStringList lst = value.toStringList();
            value = resolvePaths(lst, sourceDirPath(property, rproduct));
        }

        result.insert(it.key(), value);
    }
    return result;
}

static Scope::Ptr moduleScopeById(Scope::Ptr scope, const QStringList &moduleId)
{
    for (int i = 0; i < moduleId.count(); ++i) {
        scope = scope->properties.value(moduleId.at(i)).scope;
        if (!scope)
            break;
    }
    return scope;
}

QVariantMap Loader::LoaderPrivate::evaluateModuleValues(const ResolvedProductConstPtr &rproduct,
                                         EvaluationObject *moduleContainer, Scope::Ptr objectScope)
{
    QVariantMap values;
    QVariantMap modules;
    for (QHash<QString, Module::Ptr>::const_iterator it = moduleContainer->modules.begin();
         it != moduleContainer->modules.end(); ++it)
    {
        Module::Ptr module = it.value();
        const QString name = module->name;
        const QStringList id = module->id;
        if (!id.isEmpty()) {
            Scope::Ptr moduleScope = moduleScopeById(objectScope, id);
            if (!moduleScope)
                moduleScope = moduleScopeById(moduleContainer->scope, id);
            if (!moduleScope)
                continue;
            modules.insert(name, evaluateAll(rproduct, moduleScope));
        } else {
            modules.insert(name, evaluateAll(rproduct, module->object->scope));
        }
    }
    values.insert(QLatin1String("modules"), modules);
    return values;
}

Module::Ptr Loader::LoaderPrivate::loadModule(ProjectFile *file, const QStringList &moduleId, const QString &moduleName,
                               ScopeChain::Ptr moduleBaseScope, const QVariantMap &userProperties,
                               const CodeLocation &dependsLocation)
{
    checkCancelation();
    const bool isBaseModule = (moduleName == "qbs");

    Module::Ptr module = Module::Ptr(new Module);
    module->id = moduleId;
    module->name = moduleName;
    module->dependsLocation = dependsLocation;
    module->object = new EvaluationObject(file->root);
    const QString propertiesName = QString("module %1").arg(moduleName);
    module->object->scope = Scope::create(m_engine, m_scopesWithEvaluatedProperties,
                                          propertiesName, file);

    resolveInheritance(file->root, module->object, moduleBaseScope, userProperties);
    if (module->object->prototype != name_Module)
        return Module::Ptr();

    module->object->scope->properties.insert("name", Property(m_engine->toScriptValue(moduleName)));
    module->context = buildFileContext(file);

    ScopeChain::Ptr moduleScope(moduleBaseScope->clone());
    moduleScope->prepend(module->context);
    moduleScope->prepend(module->object->scope);
    if (isBaseModule) {
        // setup helper properties of the base module
        Property p;
        p.value = m_jsFunction_getHostOS;
        module->object->scope->properties.insert("getHostOS", p);
        p.value = m_jsFunction_getHostDefaultArchitecture;
        module->object->scope->properties.insert("getHostDefaultArchitecture", p);
        p.value = m_jsFunction_getenv;
        module->object->scope->properties.insert("getenv", p);
        p.value = m_jsFunction_configurationValue;
        module->object->scope->properties.insert("configurationValue", p);
    }

    evaluatePropertyOptions(file->root);
    evaluateDependencies(file->root, module->object, moduleScope, moduleBaseScope, userProperties, !isBaseModule);
    if (!checkFileCondition(m_engine, moduleScope, file))
        return Module::Ptr();

    qbsTrace() << "loading module '" << moduleName << "' from " << file->fileName;
    buildModulesProperty(module->object);

    if (!file->root->id.isEmpty())
        module->context->properties.insert(file->root->id, Property(module->object));
    fillEvaluationObject(moduleScope, file->root, module->object->scope, module->object, userProperties);
    evaluateDependencyConditions(module->object);

    if (!module->object->unknownModules.isEmpty()) {
        // Some module dependencies could not be resolved.
        // We're deferring the error emission because this module
        // might be removed later due to an unsatisfied dependency condition.
        return module;
    }

    // override properties given on the command line
    const QVariantMap userModuleProperties = userProperties.value(moduleName).toMap();
    for (QVariantMap::const_iterator vmit = userModuleProperties.begin(); vmit != userModuleProperties.end(); ++vmit) {
        if (!module->object->scope->properties.contains(vmit.key()))
            throw Error(Tr::tr("Unknown property: %1.%2").arg(module->id.join("."), vmit.key()));
        module->object->scope->properties.insert(vmit.key(), Property(m_engine->toScriptValue(vmit.value())));
    }

    return module;
}

/**
 * Set up the module and submodule properties in \a targetScope.
 */
void Loader::LoaderPrivate::insertModulePropertyIntoScope(Scope::Ptr targetScope, const Module::Ptr &module, Scope::Ptr moduleInstance)
{
    if (!moduleInstance)
        moduleInstance = module->object->scope;

    for (int i=0; i < module->id.count() - 1; ++i) {
        const QString &currentModuleId = module->id.at(i);
        Scope::Ptr superModuleScope;
        Property p = targetScope->properties.value(currentModuleId);
        if (p.isValid() && p.scope) {
            superModuleScope = p.scope;
        } else {
            ProjectFile *owner = module->object->instantiatingObject()->file;
            superModuleScope = Scope::create(m_engine, m_scopesWithEvaluatedProperties,
                                             currentModuleId, owner);
            superModuleScope->properties.insert("name", Property(m_engine->toScriptValue(currentModuleId)));
            targetScope->insertAndDeclareProperty(currentModuleId, Property(superModuleScope));
        }
        targetScope = superModuleScope;
    }
    targetScope->insertAndDeclareProperty(module->id.last(), Property(moduleInstance));
}

/// load all module.qbs files, checking their conditions
Module::Ptr Loader::LoaderPrivate::searchAndLoadModule(const QStringList &moduleId, const QString &moduleName, ScopeChain::Ptr moduleBaseScope,
                                        const QVariantMap &userProperties, const CodeLocation &dependsLocation,
                                        const QStringList &extraSearchPaths)
{
    Q_ASSERT(!moduleName.isEmpty());
    Module::Ptr module;
    QStringList searchPaths = extraSearchPaths;
    searchPaths.append(m_moduleSearchPaths);

    foreach (const QString &path, searchPaths) {
        QString dirPath = FileInfo::resolvePath(path, moduleName);
        QStringList moduleFileNames = m_moduleDirListCache.value(dirPath);
        if (moduleFileNames.isEmpty()) {
            QString origDirPath = dirPath;
            QFileInfo dirInfo(dirPath);
            if (!dirInfo.isDir()) {
                bool found = false;
                if (HostOsInfo::isWindowsHost()) {
                    // On case sensitive file systems try to find the path.
                    QStringList subPaths = moduleName.split("/", QString::SkipEmptyParts);
                    QDir dir(path);
                    if (!dir.cd(moduleSearchSubDir))
                        continue;
                    do {
                        QStringList lst = dir.entryList(QStringList(subPaths.takeFirst()), QDir::Dirs);
                        if (lst.count() != 1)
                            break;
                        if (!dir.cd(lst.first()))
                            break;
                        if (subPaths.isEmpty()) {
                            found = true;
                            dirPath = dir.absolutePath();
                        }
                    } while (!found);
                }
                if (!found)
                    continue;
            }

            QDirIterator dirIter(dirPath, QStringList("*.qbs"));
            while (dirIter.hasNext())
                moduleFileNames += dirIter.next();

            m_moduleDirListCache.insert(origDirPath, moduleFileNames);
        }
        foreach (const QString &fileName, moduleFileNames) {
            ProjectFile::Ptr file = parseFile(fileName);
            if (!file)
                throw Error(Tr::tr("Error while parsing file: %s").arg(fileName), dependsLocation);

            module = loadModule(file.data(), moduleId, moduleName, moduleBaseScope, userProperties, dependsLocation);
            if (module)
                return module;
        }
    }

    return module;
}

void Loader::LoaderPrivate::evaluateDependencies(LanguageObject *object, EvaluationObject *evaluationObject, const ScopeChain::Ptr &localScope,
                                  ScopeChain::Ptr moduleScope, const QVariantMap &userProperties, bool loadBaseModule)
{
    // check for additional module search paths in the product
    QStringList extraSearchPaths;
    Binding searchPathsBinding = object->bindings.value(QStringList(name_moduleSearchPaths));
    if (searchPathsBinding.isValid()) {
        applyBinding(object, searchPathsBinding, localScope);
        const QScriptValue scriptValue = localScope->value().property(name_moduleSearchPaths);
        extraSearchPaths = scriptValue.toVariant().toStringList();
    }

    // ProductModule does not have moduleSearchPaths property
    Property productProperty = localScope->lookupProperty("product");
    if (productProperty.isValid() && productProperty.scope)
        extraSearchPaths = productProperty.scope->stringListValue(name_moduleSearchPaths);
    Property projectProperty = localScope->lookupProperty("project");
    if (projectProperty.isValid() && projectProperty.scope) {
        // if no product.moduleSearchPaths found, check for additional module search paths in the project
        if (extraSearchPaths.isEmpty())
            extraSearchPaths = projectProperty.scope->stringListValue(name_moduleSearchPaths);

        // resolve all found module search paths
        extraSearchPaths = resolvePaths(extraSearchPaths, projectProperty.scope->stringValue("path"));
    }

    if (loadBaseModule) {
        Module::Ptr baseModule = searchAndLoadModule(QStringList("qbs"), QLatin1String("qbs"),
                                                     moduleScope, userProperties, CodeLocation(object->file->fileName));
        if (!baseModule)
            throw Error(Tr::tr("Cannot load the qbs base module."));
        evaluationObject->modules.insert(baseModule->name, baseModule);
        evaluationObject->scope->properties.insert(baseModule->id.first(), Property(baseModule->object));
    }

    foreach (LanguageObject *child, object->children) {
        if (compare(child->prototype, name_Depends)) {
            QList<UnknownModule::Ptr> unknownModules;
            foreach (const Module::Ptr &m, evaluateDependency(child, localScope, moduleScope, extraSearchPaths, &unknownModules, userProperties)) {
                Module::Ptr m2 = evaluationObject->modules.value(m->name);
                if (m2) {
                    m2->dependsCount++;
                    continue;
                }
                m->dependsCount = 1;
                evaluationObject->modules.insert(m->name, m);
                insertModulePropertyIntoScope(evaluationObject->scope, m, m->object->scope);
            }
            evaluationObject->unknownModules.append(unknownModules);
        }
    }
}

void Loader::LoaderPrivate::evaluateDependencyConditions(EvaluationObject *evaluationObject)
{
    bool mustEvaluateConditions = false;
    QVector<Module::Ptr> modules;
    QVector<QSharedPointer<ModuleBase> > moduleBaseObjects;
    foreach (const Module::Ptr &module, evaluationObject->modules) {
        if (!module->condition.isNull())
            mustEvaluateConditions = true;
        modules += module;
        moduleBaseObjects += module;
    }
    foreach (const UnknownModule::Ptr &module, evaluationObject->unknownModules) {
        if (!module->condition.isNull())
            mustEvaluateConditions = true;
        moduleBaseObjects += module;
    }
    if (!mustEvaluateConditions)
        return;

    QScriptContext *context = m_engine->currentContext();
    const QScriptValue activationObject = context->activationObject();

    foreach (const QSharedPointer<ModuleBase> &moduleBaseObject, moduleBaseObjects) {
        if (moduleBaseObject->condition.isNull())
            continue;

        context->setActivationObject(moduleBaseObject->conditionScopeChain->value());
        QScriptValue conditionValue = m_engine->evaluate(moduleBaseObject->condition);
        if (conditionValue.isError()) {
            CodeLocation location(moduleBaseObject->condition.fileName(), moduleBaseObject->condition.firstLineNumber());
            throw Error(Tr::tr("Error while evaluating Depends.condition: %1").arg(conditionValue.toString()), location);
        }
        if (!conditionValue.toBool()) {
            // condition is false, thus remove the module from evaluationObject
            if (Module::Ptr module = moduleBaseObject.dynamicCast<Module>()) {
                if (--module->dependsCount == 0)
                    evaluationObject->modules.remove(module->name);
            } else {
                evaluationObject->unknownModules.removeOne(moduleBaseObject.dynamicCast<UnknownModule>());
            }
        }
    }

    context->setActivationObject(activationObject);
}

void Loader::LoaderPrivate::buildModulesProperty(EvaluationObject *evaluationObject)
{
    // set up a XXX.modules property
    Scope::Ptr modules = Scope::create(m_engine, m_scopesWithEvaluatedProperties,
                                       QLatin1String("modules property"),
                                       evaluationObject->instantiatingObject()->file);
    for (QHash<QString, Module::Ptr>::const_iterator it = evaluationObject->modules.begin();
         it != evaluationObject->modules.end(); ++it)
    {
        modules->properties.insert(it.key(), Property(it.value()->object));
        modules->declarations.insert(it.key(), PropertyDeclaration(it.key(), PropertyDeclaration::Variant));
    }
    evaluationObject->scope->properties.insert("modules", Property(modules));
    evaluationObject->scope->declarations.insert("modules", PropertyDeclaration("modules", PropertyDeclaration::Variant));
}

void Loader::LoaderPrivate::checkModuleDependencies(const Module::Ptr &module)
{
    if (!module->object->unknownModules.isEmpty()) {
        UnknownModule::Ptr missingModule = module->object->unknownModules.first();
        throw Error(Tr::tr("Module '%1' cannot be loaded.").arg(missingModule->name),
                    missingModule->dependsLocation);
    }

    foreach (const Module::Ptr &dependency, module->object->modules)
        checkModuleDependencies(dependency);
}

QList<Module::Ptr> Loader::LoaderPrivate::evaluateDependency(LanguageObject *depends, ScopeChain::Ptr conditionScopeChain,
                                              ScopeChain::Ptr moduleScope, const QStringList &extraSearchPaths,
                                              QList<UnknownModule::Ptr> *unknownModules, const QVariantMap &userProperties)
{
    const CodeLocation dependsLocation = depends->prototypeLocation;

    // check for the use of undeclared properties
    foreach (const Binding &binding, depends->bindings) {
        if (binding.name.count() > 1)
            throw Error(Tr::tr("Bindings with dots are forbidden in Depends."), dependsLocation);
        if (!m_dependsPropertyDeclarations.contains(binding.name.first()))
            throw Error(Tr::tr("There's no property '%1' in Depends.").arg(binding.name.first()),
                               CodeLocation(depends->file->fileName, binding.valueSource.firstLineNumber()));
    }

    QScriptProgram condition;
    Binding binding = depends->bindings.value(QStringList("condition"));
    if (binding.isValid())
        condition = binding.valueSource;

    bool isRequired = true;
    binding = depends->bindings.value(QStringList("required"));
    if (!binding.valueSource.isNull())
        isRequired = evaluate(m_engine, binding.valueSource).toBool();

    QString failureMessage;
    binding = depends->bindings.value(QStringList("failureMessage"));
    if (!binding.valueSource.isNull())
        failureMessage = evaluate(m_engine, binding.valueSource).toString();

    QString moduleName;
    binding = depends->bindings.value(QStringList("name"));
    if (!binding.valueSource.isNull()) {
        moduleName = evaluate(m_engine, binding.valueSource).toString();
    } else {
        moduleName = depends->id;
    }

    QString moduleId = depends->id;
    if (moduleId.isEmpty())
        moduleId = moduleName.toLower();

    QStringList subModules;
    Binding subModulesBinding = depends->bindings.value(QStringList("submodules"));
    if (!subModulesBinding.valueSource.isNull())
        subModules = evaluate(m_engine, subModulesBinding.valueSource).toVariant().toStringList();

    QList<QStringList> fullModuleIds;
    QStringList fullModuleNames;
    if (subModules.isEmpty()) {
        fullModuleIds.append(moduleId.split(QLatin1Char('.')));
        fullModuleNames.append(moduleName.toLower().replace('.', "/"));
    } else {
        foreach (const QString &subModuleName, subModules) {
            fullModuleIds.append(QStringList() << moduleId << subModuleName);
            fullModuleNames.append(moduleName.toLower().replace('.', "/") + "/" + subModuleName.toLower().replace('.', "/"));
        }
    }

    QList<Module::Ptr> modules;
    unknownModules->clear();
    for (int i=0; i < fullModuleNames.count(); ++i) {
        const QString &fullModuleName = fullModuleNames.at(i);
        Module::Ptr module = searchAndLoadModule(fullModuleIds.at(i), fullModuleName, moduleScope, userProperties, dependsLocation, extraSearchPaths);
        ModuleBase::Ptr moduleBase;
        if (module) {
            moduleBase = module;
            modules.append(module);
        } else {
            UnknownModule::Ptr unknownModule(new UnknownModule);
            unknownModule->name = fullModuleName;
            unknownModule->required = isRequired;
            unknownModule->failureMessage = failureMessage;
            unknownModule->dependsLocation = dependsLocation;
            moduleBase = unknownModule;
            unknownModules->append(unknownModule);
        }
        moduleBase->condition = condition;
        moduleBase->conditionScopeChain = conditionScopeChain;
    }
    return modules;
}

static void findModuleDependencies_impl(const Module::Ptr &module, QHash<QString, ProjectFile *> &result)
{
    QString moduleName = module->name;
    ProjectFile *file = module->file();
    ProjectFile *otherFile = result.value(moduleName);
    if (otherFile && otherFile != file) {
        throw Error(Tr::tr("two different versions of '%1' were included: '%2' and '%3'").arg(
                               moduleName, file->fileName, otherFile->fileName));
    } else if (otherFile) {
        return;
    }

    result.insert(moduleName, file);
    foreach (const Module::Ptr &depModule, module->object->modules) {
        findModuleDependencies_impl(depModule, result);
    }
}

static QHash<QString, ProjectFile *> findModuleDependencies(EvaluationObject *root)
{
    QHash<QString, ProjectFile *> result;
    foreach (const Module::Ptr &module, root->modules) {
        foreach (const Module::Ptr &depModule, module->object->modules) {
            findModuleDependencies_impl(depModule, result);
        }
    }
    return result;
}

static void applyFileTaggers(const SourceArtifactPtr &artifact,
        const ResolvedProductConstPtr &product)
{
    if (!artifact->overrideFileTags || artifact->fileTags.isEmpty()) {
        QSet<QString> fileTags = product->fileTagsForFileName(artifact->absoluteFilePath);
        artifact->fileTags.unite(fileTags);
        if (artifact->fileTags.isEmpty())
            artifact->fileTags.insert(QLatin1String("unknown-file-tag"));
        if (qbsLogLevel(LoggerTrace))
            qbsTrace() << "[LDR] adding file tags " << artifact->fileTags << " to " << FileInfo::fileName(artifact->absoluteFilePath);
    }
}

static bool checkCondition(EvaluationObject *object)
{
    QScriptValue scriptValue = object->scope->property("condition");
    if (scriptValue.isString()) {
        // Condition is user-defined
        const QString str = scriptValue.toString();
        if (str == "true")
            return true;
        else if (str == "false")
            return false;
    }
    if (scriptValue.isBool()) {
        return scriptValue.toBool();
    } else if (scriptValue.isValid() && !scriptValue.isUndefined()) {
        const QScriptProgram &scriptProgram = object->objects.first()->bindings.value(QStringList("condition")).valueSource;
        throw Error(Tr::tr("Invalid condition."), CodeLocation(scriptProgram.fileName(), scriptProgram.firstLineNumber()));
    }
    // no 'condition' property means 'the condition is true'
    return true;
}

ResolvedProjectPtr Loader::LoaderPrivate::resolveProject(const QString &buildRoot,
                                                           const QVariantMap &userProperties)
{
    Q_ASSERT(FileInfo::isAbsolute(buildRoot));
    if (qbsLogLevel(LoggerTrace))
        qbsTrace() << "[LDR] resolving " << m_project->fileName;
    ScriptEngineContextPusher contextPusher(m_engine);
    m_scopesWithEvaluatedProperties->clear();
    m_convertedScopesCache.clear();
    ResolvedProjectPtr rproject = ResolvedProject::create();
    rproject->qbsFile = m_project->fileName;
    rproject->setBuildConfiguration(userProperties);
    rproject->buildDirectory = ResolvedProject::deriveBuildDirectory(buildRoot, rproject->id());

    Scope::Ptr context = buildFileContext(m_project.data());
    ScopeChain::Ptr scope(new ScopeChain(m_engine, context));

    ResolvedModulePtr dummyModule = ResolvedModule::create();
    dummyModule->jsImports = m_project->jsImports;
    QList<RulePtr> globalRules;
    QList<FileTagger::ConstPtr> globalFileTaggers;

    ProjectData projectData;
    resolveTopLevel(rproject,
                    m_project->root,
                    m_project->fileName,
                    &projectData,
                    &globalRules,
                    &globalFileTaggers,
                    userProperties,
                    scope,
                    dummyModule);

    ProductMap resolvedProducts;
    QHash<ResolvedProductPtr, ProductData>::iterator it = projectData.products.begin();
    if (m_progressObserver)
        m_progressObserver->initialize(Tr::tr("Loading project"), projectData.products.count());
    for (; it != projectData.products.end(); ++it) {
        if (m_progressObserver) {
            checkCancelation();
            m_progressObserver->incrementProgressValue();
        }
        resolveProduct(it.key(), rproject, it.value(), resolvedProducts, globalRules,
                       globalFileTaggers, dummyModule);
    }

    // Check, if the userProperties contain invalid items.
    checkUserProperties(projectData, userProperties);

    // Check all modules for unresolved dependencies.
    foreach (ResolvedProductPtr rproduct, rproject->products)
        foreach (Module::Ptr module, projectData.products.value(rproduct).product->modules)
            checkModuleDependencies(module);

    // Resolve inter-product dependencies.
    resolveProductDependencies(rproject, projectData, resolvedProducts);

    return rproject;
}

void Loader::LoaderPrivate::resolveModule(ResolvedProductPtr rproduct, const QString &moduleName, EvaluationObject *module)
{
    ResolvedModulePtr rmodule = ResolvedModule::create();
    rmodule->name = moduleName;
    rmodule->jsImports = module->instantiatingObject()->file->jsImports;
    rmodule->setupBuildEnvironmentScript = module->scope->verbatimValue("setupBuildEnvironment");
    rmodule->setupRunEnvironmentScript = module->scope->verbatimValue("setupRunEnvironment");
    QStringList additionalProductFileTags = module->scope->stringListValue("additionalProductFileTags");
    if (!additionalProductFileTags.isEmpty()) {
        rproduct->additionalFileTags.append(additionalProductFileTags);
        rproduct->additionalFileTags = rproduct->additionalFileTags.toSet().toList();
    }
    foreach (Module::Ptr m, module->modules)
        rmodule->moduleDependencies.append(m->name);
    rproduct->modules.append(rmodule);
    QList<EvaluationObject *> unhandledChildren = resolveCommonItems(module->children, rproduct, rmodule);
    if (!unhandledChildren.isEmpty()) {
        EvaluationObject *child = unhandledChildren.first();
        QString msg = Tr::tr("Items of type %0 not allowed in a Module.");
        throw Error(msg.arg(child->prototype));
    }
}

static void createSourceArtifact(const ResolvedProductConstPtr &rproduct,
                                 const PropertyMapPtr &properties,
                                 const QString &fileName,
                                 const QSet<QString> &fileTags,
                                 bool overrideTags,
                                 QList<SourceArtifactPtr> &artifactList)
{
    SourceArtifactPtr artifact = SourceArtifact::create();
    artifact->absoluteFilePath = FileInfo::resolvePath(rproduct->sourceDirectory, fileName);
    artifact->fileTags = fileTags;
    artifact->overrideFileTags = overrideTags;
    artifact->properties = properties;
    artifactList += artifact;
}

/**
  * Resolve Group {} and the files part of Product {}.
  */
void Loader::LoaderPrivate::resolveGroup(ResolvedProductPtr rproduct, EvaluationObject *product, EvaluationObject *group)
{
    const bool isGroup = product != group;

    PropertyMapPtr properties = rproduct->properties;

    if (isGroup) {
        clearScopesCache();

        if (!checkCondition(group))
            return;

        // Walk through all bindings and check if we set anything
        // that required a separate config for this group.
        bool createNewConfig = false;
        for (int i = 0; i < group->objects.count() && !createNewConfig; ++i) {
            foreach (const Binding &binding, group->objects.at(i)->bindings) {
                if (binding.name.count() > 1 || !m_groupPropertyDeclarations.contains(binding.name.first())) {
                    createNewConfig = true;
                    break;
                }
            }
        }

        if (createNewConfig) {
            // build configuration for this group
            properties = PropertyMap::create();
            properties->setValue(evaluateModuleValues(rproduct, product, group->scope));
        }
    }

    // Products can have 'files' but not 'fileTags'
    QStringList files = group->scope->stringListValue("files");
    if (isGroup && files.isEmpty()) {
        // Yield an error if Group without files binding is encountered.
        // An empty files value is OK but a binding must exist.
        bool filesBindingFound = false;
        const QStringList filesBindingName(QStringList() << "files");
        foreach (LanguageObject *obj, group->objects) {
            if (obj->bindings.contains(filesBindingName)) {
                filesBindingFound = true;
                break;
            }
        }
        if (!filesBindingFound)
            throw Error(Tr::tr("Group without files is not allowed."), group->instantiatingObject()->prototypeLocation);
    }
    QStringList patterns;
    QString prefix;
    for (int i = files.count(); --i >= 0;) {
        if (FileInfo::isPattern(files[i]))
            patterns.append(files.takeAt(i));
    }
    if (isGroup) {
        prefix = group->scope->stringValue("prefix");
        if (!prefix.isEmpty()) {
            for (int i = files.count(); --i >= 0;)
                    files[i].prepend(prefix);
        }
    }
    QSet<QString> fileTags;
    if (isGroup)
        fileTags = group->scope->stringListValue("fileTags").toSet();
    bool overrideTags = true;
    if (isGroup)
        overrideTags = group->scope->boolValue("overrideTags", true);

    ResolvedGroup::Ptr resolvedGroup = ResolvedGroup::create();
    resolvedGroup->qbsLine = group->instantiatingObject()->prototypeLocation.line;

    if (!patterns.isEmpty()) {
        SourceWildCards::Ptr wildcards = SourceWildCards::create();
        if (isGroup) {
            wildcards->recursive = group->scope->boolValue("recursive");
            wildcards->excludePatterns = group->scope->stringListValue("excludeFiles");
        }
        wildcards->prefix = prefix;
        wildcards->patterns = patterns;
        QSet<QString> files = wildcards->expandPatterns(rproduct->sourceDirectory);
        foreach (const QString &fileName, files)
            createSourceArtifact(rproduct, properties, fileName,
                                 fileTags, overrideTags, wildcards->files);
        resolvedGroup->wildcards = wildcards;
    }

    foreach (const QString &fileName, files)
        createSourceArtifact(rproduct, properties, fileName,
                             fileTags, overrideTags, resolvedGroup->files);

    resolvedGroup->name = group->scope->stringValue("name");
    if (resolvedGroup->name.isEmpty())
        resolvedGroup->name = Tr::tr("Group %1").arg(rproduct->groups.count());
    resolvedGroup->properties = properties;
    rproduct->groups += resolvedGroup;
}

void Loader::LoaderPrivate::resolveProductModule(const ResolvedProductConstPtr &rproduct,
        EvaluationObject *productModule)
{
    Q_ASSERT(!rproduct->name.isEmpty());

    evaluateDependencyConditions(productModule);
    clearScopesCache();
    QVariantMap moduleValues = evaluateModuleValues(rproduct, productModule, productModule->scope);
    m_productModules.insert(rproduct->name.toLower(), moduleValues);
}

void Loader::LoaderPrivate::resolveTransformer(ResolvedProductPtr rproduct, EvaluationObject *trafo, ResolvedModuleConstPtr module)
{
    if (!checkCondition(trafo))
        return;

    ResolvedTransformer::Ptr rtrafo = ResolvedTransformer::create();
    rtrafo->module = module;
    rtrafo->jsImports = trafo->instantiatingObject()->file->jsImports;
    rtrafo->inputs = trafo->scope->stringListValue("inputs");
    for (int i=0; i < rtrafo->inputs.count(); ++i)
        rtrafo->inputs[i] = FileInfo::resolvePath(rproduct->sourceDirectory, rtrafo->inputs[i]);
    const PrepareScriptPtr transform = PrepareScript::create();
    transform->script = trafo->scope->verbatimValue("prepare");
    transform->location.fileName = trafo->instantiatingObject()->file->fileName;
    transform->location.column = 1;
    Binding binding = trafo->instantiatingObject()->bindings.value(QStringList("prepare"));
    transform->location.line = binding.valueSource.firstLineNumber();
    rtrafo->transform = transform;

    foreach (EvaluationObject *child, trafo->children) {
        if (child->prototype != name_Artifact)
            throw Error(Tr::tr("Transformer: wrong child type '%0'.").arg(child->prototype));
        SourceArtifactPtr artifact = SourceArtifact::create();
        artifact->properties = rproduct->properties;
        QString fileName = child->scope->stringValue("fileName");
        if (fileName.isEmpty())
            throw Error(Tr::tr("Artifact fileName must not be empty."));
        artifact->absoluteFilePath = FileInfo::resolvePath(rproduct->project->buildDirectory,
                                                           fileName);
        artifact->fileTags = child->scope->stringListValue("fileTags").toSet();
        rtrafo->outputs += artifact;
    }
    rproduct->transformers += rtrafo;
}

void Loader::LoaderPrivate::resolveProbe(EvaluationObject *node)
{
    if (!checkCondition(node))
        return;
    if (!m_probeScriptScope.isValid()) {
        m_probeScriptScope = m_engine->newObject();
        File::init(m_probeScriptScope);
        TextFile::init(m_probeScriptScope);
        Process::init(m_probeScriptScope);
    }
    QScriptContext *ctx = m_engine->pushContext();
    ctx->pushScope(m_probeScriptScope);
    ProbeScope::Ptr scope = ProbeScope::create(m_engine, node->scope);
    ctx->setActivationObject(scope->value());
    for (int i = node->objects.size() - 1; i >= 0; --i)
        applyFunctions(m_engine, node->objects.at(i), node);
    QString constructor = node->scope->verbatimValue("configure");
    evaluate(m_engine, constructor);
    ctx->popScope();
    m_engine->popContext();
}

/**
 *Resolve stuff that Module and Product have in common.
 */
QList<EvaluationObject *> Loader::LoaderPrivate::resolveCommonItems(const QList<EvaluationObject *> &objects,
                                                        ResolvedProductPtr rproduct, const ResolvedModuleConstPtr &module)
{
    QList<RulePtr> rules;

    QList<EvaluationObject *> unhandledObjects;
    foreach (EvaluationObject *object, objects) {
        const uint hashPrototypeName = qHash(object->prototype);
        if (hashPrototypeName == hashName_FileTagger) {
            rproduct->fileTaggers.insert(resolveFileTagger(object));
        } else if (hashPrototypeName == hashName_Rule) {
            const RulePtr rule = resolveRule(object, module);
            rproduct->rules.insert(rule);
            rules.append(rule);
        } else if (hashPrototypeName == hashName_Transformer) {
            resolveTransformer(rproduct, object, module);
        } else if (hashPrototypeName == hashName_PropertyOptions) {
            // Just ignore this type to allow it. It is handled elsewhere.
        } else if (hashPrototypeName == hashName_Probe) {
            resolveProbe(object);
        } else {
            unhandledObjects.append(object);
        }
    }

    return unhandledObjects;
}

RulePtr Loader::LoaderPrivate::resolveRule(EvaluationObject *object, ResolvedModuleConstPtr module)
{
    RulePtr rule = Rule::create();

    // read artifacts
    QList<RuleArtifactConstPtr> artifacts;
    bool hasAlwaysUpdatedArtifact = false;
    foreach (EvaluationObject *child, object->children) {
        const uint hashChildPrototypeName = qHash(child->prototype);
        if (hashChildPrototypeName == hashName_Artifact) {
            RuleArtifactPtr artifact = RuleArtifact::create();
            artifacts.append(artifact);
            artifact->fileName = child->scope->verbatimValue("fileName");
            artifact->fileTags = child->scope->stringListValue("fileTags");
            artifact->alwaysUpdated = child->scope->boolValue("alwaysUpdated", true);
            if (artifact->alwaysUpdated)
                hasAlwaysUpdatedArtifact = true;
            LanguageObject *origArtifactObj = child->instantiatingObject();
            foreach (const Binding &binding, origArtifactObj->bindings) {
                if (binding.name.length() <= 1)
                    continue;
                RuleArtifact::Binding rabinding;
                rabinding.name = binding.name;
                rabinding.code = binding.valueSource.sourceCode();
                rabinding.location.fileName = binding.valueSource.fileName();
                rabinding.location.line = binding.valueSource.firstLineNumber();
                artifact->bindings.append(rabinding);
            }
        } else {
            throw Error(Tr::tr("'Rule' can only have children of type 'Artifact'."),
                               child->instantiatingObject()->prototypeLocation);
        }
    }

    if (!hasAlwaysUpdatedArtifact)
        throw Error(Tr::tr("At least one output artifact of a rule "
                           "must have alwaysUpdated set to true."),
                    object->instantiatingObject()->prototypeLocation);

    const PrepareScriptPtr prepareScript = PrepareScript::create();
    prepareScript->script = object->scope->verbatimValue("prepare");
    prepareScript->location.fileName = object->instantiatingObject()->file->fileName;
    prepareScript->location.column = 1;
    {
        Binding binding = object->instantiatingObject()->bindings.value(QStringList("prepare"));
        prepareScript->location.line = binding.valueSource.firstLineNumber();
    }

    rule->jsImports = object->instantiatingObject()->file->jsImports;
    rule->script = prepareScript;
    rule->artifacts = artifacts;
    rule->multiplex = object->scope->boolValue("multiplex", false);
    rule->inputs = object->scope->stringListValue("inputs");
    rule->usings = object->scope->stringListValue("usings");
    rule->explicitlyDependsOn = object->scope->stringListValue("explicitlyDependsOn");
    rule->module = module;

    return rule;
}

FileTagger::ConstPtr Loader::LoaderPrivate::resolveFileTagger(EvaluationObject *evaluationObject)
{
    const Scope::Ptr scope = evaluationObject->scope;
    return FileTagger::create(QRegExp(scope->stringValue("pattern")),
            scope->stringListValue("fileTags"));
}

/// --------------------------------------------------------------------------


template <typename T>
static QString textOf(const QString &source, T *node)
{
    if (!node)
        return QString();
    return source.mid(node->firstSourceLocation().begin(), node->lastSourceLocation().end() - node->firstSourceLocation().begin());
}

static void bindFunction(LanguageObject *result, const QString &source, FunctionDeclaration *ast)
{
    Function f;
    if (ast->name.isNull())
        throw Error(Tr::tr("function decl without name"));
    f.name = ast->name.toString();

    // remove the name
    QString funcNoName = textOf(source, ast);
    funcNoName.replace(QRegExp("^(\\s*function\\s*)\\w*"), "(\\1");
    funcNoName.append(")");
    f.source = QScriptProgram(funcNoName, result->file->fileName, ast->firstSourceLocation().startLine);
    result->functions.insert(f.name, f);
}

static QStringList toStringList(UiQualifiedId *qid)
{
    QStringList result;
    for (; qid; qid = qid->next) {
        if (!qid->name.isEmpty())
            result.append(qid->name.toString());
        else
            result.append(QString()); // throw error instead?
    }
    return result;
}

static CodeLocation toCodeLocation(const QString &fileName, SourceLocation location)
{
    return CodeLocation(fileName, location.startLine, location.startColumn);
}

static QScriptProgram bindingProgram(const QString &fileName, const QString &source, Statement *statement)
{
    QString sourceCode = textOf(source, statement);
    if (cast<Block *>(statement)) {
        // rewrite blocks to be able to use return statements in property assignments
        sourceCode.prepend("(function()");
        sourceCode.append(")()");
    }
    return QScriptProgram(sourceCode, fileName,
                          statement->firstSourceLocation().startLine);
}

static void checkDuplicateBinding(LanguageObject *object, const QStringList &bindingName, const SourceLocation &sourceLocation)
{
    if (object->bindings.contains(bindingName)) {
        QString msg = Tr::tr("Duplicate binding for '%1'");
        throw Error(msg.arg(bindingName.join(".")),
                    toCodeLocation(object->file->fileName, sourceLocation));
    }
}

static void bindBinding(LanguageObject *result, const QString &source, UiScriptBinding *ast)
{
    Binding p;
    if (!ast->qualifiedId || ast->qualifiedId->name.isEmpty())
        throw Error(Tr::tr("script binding without name"));
    p.name = toStringList(ast->qualifiedId);
    checkDuplicateBinding(result, p.name, ast->qualifiedId->identifierToken);

    if (p.name == QStringList("id")) {
        ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement);
        if (!expStmt)
            throw Error(Tr::tr("id: must be followed by identifier"));
        IdentifierExpression *idExp = cast<IdentifierExpression *>(expStmt->expression);
        if (!idExp || idExp->name.isEmpty())
            throw Error(Tr::tr("id: must be followed by identifier"));
        result->id = idExp->name.toString();
        return;
    }

    p.valueSource = bindingProgram(result->file->fileName, source, ast->statement);

    IdentifierSearch idsearch;
    idsearch.add(QLatin1String("base"), &p.valueSourceUsesBase);
    idsearch.add(QLatin1String("outer"), &p.valueSourceUsesOuter);
    idsearch.start(ast->statement);

    result->bindings.insert(p.name, p);
}

static void bindBinding(LanguageObject *result, const QString &source, UiPublicMember *ast)
{
    Binding p;
    if (ast->name.isNull())
        throw Error(Tr::tr("public member without name"));
    p.name = QStringList(ast->name.toString());
    checkDuplicateBinding(result, p.name, ast->identifierToken);

    if (ast->statement) {
        p.valueSource = bindingProgram(result->file->fileName, source, ast->statement);
        IdentifierSearch idsearch;
        idsearch.add(QLatin1String("base"), &p.valueSourceUsesBase);
        idsearch.add(QLatin1String("outer"), &p.valueSourceUsesOuter);
        idsearch.start(ast->statement);
    } else {
        p.valueSource = QScriptProgram("undefined");
    }

    result->bindings.insert(p.name, p);
}

static PropertyDeclaration::Type propertyTypeFromString(const QString &typeName)
{
    if (typeName == "bool")
        return PropertyDeclaration::Boolean;
    if (typeName == "path")
        return PropertyDeclaration::Path;
    if (typeName == "pathList")
        return PropertyDeclaration::PathList;
    if (typeName == "string")
        return PropertyDeclaration::String;
    if (typeName == "var" || typeName == "variant")
        return PropertyDeclaration::Variant;
    return PropertyDeclaration::UnknownType;
}

static void bindPropertyDeclaration(LanguageObject *result, UiPublicMember *ast)
{
    PropertyDeclaration p;
    if (ast->name.isEmpty())
        throw Error(Tr::tr("public member without name"));
    if (ast->memberType.isEmpty())
        throw Error(Tr::tr("public member without type"));
    if (ast->type == UiPublicMember::Signal)
        throw Error(Tr::tr("public member with signal type not supported"));
    p.name = ast->name.toString();
    p.type = propertyTypeFromString(ast->memberType.toString());
    if (ast->typeModifier.compare(QLatin1String("list")))
        p.flags |= PropertyDeclaration::ListProperty;
    else if (!ast->typeModifier.isEmpty())
        throw Error(Tr::tr("public member with type modifier '%1' not supported").arg(ast->typeModifier.toString()));

    result->propertyDeclarations.insert(p.name, p);
}

static LanguageObject *bindObject(ProjectFile::Ptr file, const QString &source, UiObjectDefinition *ast,
                              const QHash<QStringList, QString> prototypeToFile)
{
    LanguageObject *result = new LanguageObject(file.data());
    result->file = file.data();

//    result->location = CodeLocation(
//            currentSourceFileName,
//            ast->firstSourceLocation().startLine,
//            ast->firstSourceLocation().startColumn
//    );

    if (!ast->qualifiedTypeNameId || ast->qualifiedTypeNameId->name.isEmpty())
        throw Error(Tr::tr("no prototype"));
    result->prototype = toStringList(ast->qualifiedTypeNameId);
    result->prototypeLocation = toCodeLocation(file->fileName, ast->qualifiedTypeNameId->identifierToken);

    // resolve prototype if possible
    result->prototypeFileName = prototypeToFile.value(result->prototype);

    if (!ast->initializer)
        return result;

    for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
        if (UiPublicMember *publicMember = cast<UiPublicMember *>(it->member)) {
            bindPropertyDeclaration(result, publicMember);
            bindBinding(result, source, publicMember);
        } else if (UiScriptBinding *scriptBinding = cast<UiScriptBinding *>(it->member)) {
            bindBinding(result, source, scriptBinding);
        } else if (UiSourceElement *sourceElement = cast<UiSourceElement *>(it->member)) {
           FunctionDeclaration *fdecl = cast<FunctionDeclaration *>(sourceElement->sourceElement);
           if (!fdecl)
               continue;
           bindFunction(result, source, fdecl);
        } else if (UiObjectDefinition *objDef = cast<UiObjectDefinition *>(it->member)) {
            result->children += bindObject(file, source, objDef, prototypeToFile);
        }
    }

    return result;
}

static void collectPrototypes(const QString &path, const QString &as,
                              QHash<QStringList, QString> *prototypeToFile)
{
    QDirIterator dirIter(path, QStringList("*.qbs"));
    while (dirIter.hasNext()) {
        const QString filePath = dirIter.next();
        const QString fileName = dirIter.fileName();

        if (fileName.size() <= 4)
            continue;

        const QString componentName = fileName.left(fileName.size() - 4);
        // ### validate componentName

        if (!componentName.at(0).isUpper())
            continue;

        QStringList prototypeName;
        if (!as.isEmpty())
            prototypeName.append(as);
        prototypeName.append(componentName);

        prototypeToFile->insert(prototypeName, filePath);
    }
}

static ProjectFile::Ptr bindFile(const QString &source, const QString &fileName, UiProgram *ast, QStringList searchPaths)
{
    ProjectFile::Ptr file(new ProjectFile);
    file->fileName = fileName;
    const QString path = FileInfo::path(fileName);

    // maps names of known prototypes to absolute file names
    QHash<QStringList, QString> prototypeToFile;

    // files in the same directory are available as prototypes
    collectPrototypes(path, QString(), &prototypeToFile);

    QSet<QString> importAsNames;
    QHash<QString, JsImport> jsImports;

    for (const QbsQmlJS::AST::UiImportList *it = ast->imports; it; it = it->next) {
        const QbsQmlJS::AST::UiImport *const import = it->import;

        QStringList importUri;
        bool isBase = false;
        if (import->importUri) {
            importUri = toStringList(import->importUri);
            if (importUri.size() == 2
                    && importUri.first() == "qbs"
                    && importUri.last() == "base")
                isBase = true; // ### check version!
        }

        QString as;
        if (isBase) {
            if (!import->importId.isNull()) {
                throw Error(Tr::tr("Import of qbs.base must have no 'as <Name>'"),
                            toCodeLocation(fileName, import->importIdToken));
            }
        } else {
            if (import->importId.isNull()) {
                throw Error(Tr::tr("Imports require 'as <Name>'"),
                            toCodeLocation(fileName, import->importToken));
            }

            as = import->importId.toString();
            if (importAsNames.contains(as)) {
                throw Error(Tr::tr("Can't import into the same name more than once."),
                            toCodeLocation(fileName, import->importIdToken));
            }
            importAsNames.insert(as);
        }

        if (!import->fileName.isNull()) {
            QString name = FileInfo::resolvePath(path, import->fileName.toString());

            QFileInfo fi(name);
            if (!fi.exists())
                throw Error(Tr::tr("Can't find imported file %0.").arg(name),
                            CodeLocation(fileName, import->fileNameToken.startLine, import->fileNameToken.startColumn));
            name = fi.canonicalFilePath();
            if (fi.isDir()) {
                collectPrototypes(name, as, &prototypeToFile);
            } else {
                if (name.endsWith(".js", Qt::CaseInsensitive)) {
                    JsImport &jsImport = jsImports[as];
                    jsImport.scopeName = as;
                    jsImport.fileNames.append(name);
                    jsImport.location = toCodeLocation(fileName, import->firstSourceLocation());
                } else if (name.endsWith(".qbs", Qt::CaseInsensitive)) {
                    prototypeToFile.insert(QStringList(as), name);
                } else {
                    throw Error(Tr::tr("Can only import .qbs and .js files"),
                                CodeLocation(fileName, import->fileNameToken.startLine, import->fileNameToken.startColumn));
                }
            }
        } else if (!importUri.isEmpty()) {
            const QString importPath = importUri.join(QDir::separator());
            bool found = false;
            foreach (const QString &searchPath, searchPaths) {
                const QFileInfo fi(FileInfo::resolvePath(FileInfo::resolvePath(searchPath, "imports"), importPath));
                if (fi.isDir()) {
                    // ### versioning, qbsdir file, etc.
                    const QString &resultPath = fi.absoluteFilePath();
                    collectPrototypes(resultPath, as, &prototypeToFile);

                    QDirIterator dirIter(resultPath, QStringList("*.js"));
                    while (dirIter.hasNext()) {
                        dirIter.next();
                        JsImport &jsImport = jsImports[as];
                        if (jsImport.scopeName.isNull()) {
                            jsImport.scopeName = as;
                            jsImport.location = toCodeLocation(fileName, import->firstSourceLocation());
                        }
                        jsImport.fileNames.append(dirIter.filePath());
                    }
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw Error(Tr::tr("import %1 not found").arg(importUri.join(".")),
                            toCodeLocation(fileName, import->fileNameToken));
            }
        }
    }

    UiObjectDefinition *rootDef = cast<UiObjectDefinition *>(ast->members->member);
    if (rootDef)
        file->root = bindObject(file, source, rootDef, prototypeToFile);

    file->jsImports = jsImports.values();
    return file;
}

ProjectFile::Ptr Loader::LoaderPrivate::parseFile(const QString &fileName)
{
    ProjectFile::Ptr result = m_parsedFiles.value(fileName);
    if (result)
        return result;

    QFile file(fileName);
    if (!file.open(QFile::ReadOnly))
        throw Error(Tr::tr("Couldn't open '%1'.").arg(fileName));

    const QString code = QTextStream(&file).readAll();
    QScopedPointer<QbsQmlJS::Engine> engine(new QbsQmlJS::Engine);
    QbsQmlJS::Lexer lexer(engine.data());
    lexer.setCode(code, 1);
    QbsQmlJS::Parser parser(engine.data());
    parser.parse();

    QList<QbsQmlJS::DiagnosticMessage> parserMessages = parser.diagnosticMessages();
    if (!parserMessages.isEmpty()) {
        Error err;
        foreach (const QbsQmlJS::DiagnosticMessage &msg, parserMessages)
            err.append(msg.message, fileName, msg.loc.startLine, msg.loc.startColumn);
        throw err;
    }

    result = bindFile(code, fileName, parser.ast(), m_searchPaths);
    if (result) {
        Q_ASSERT(!m_parsedFiles.contains(result->fileName));
        m_parsedFiles.insert(result->fileName, result);
    }
    return result;
}

void Loader::LoaderPrivate::checkCancelation() const
{
    if (m_progressObserver && m_progressObserver->canceled())
        throw Error(Tr::tr("Loading canceled."));
}

Loader::LoaderPrivate *Loader::LoaderPrivate::get(QScriptEngine *engine)
{
    QVariant v = engine->property(szLoaderPropertyName);
    return static_cast<LoaderPrivate*>(v.value<void*>());
}

QScriptValue Loader::LoaderPrivate::js_getHostOS(QScriptContext *context, QScriptEngine *engine)
{
    Q_UNUSED(context);
    QString hostSystem;

    // TODO: Do we really not support other UNIX systems?
#if defined(Q_OS_WIN)
    hostSystem = "windows";
#elif defined(Q_OS_MAC)
    hostSystem = "mac";
#elif defined(Q_OS_LINUX)
    hostSystem = "linux";
#else
#   error unknown host platform
#endif
    return engine->toScriptValue(hostSystem);
}

QScriptValue Loader::LoaderPrivate::js_getHostDefaultArchitecture(QScriptContext *context, QScriptEngine *engine)
{
    // ### TODO implement properly, do not hard-code
    Q_UNUSED(context);
    QString architecture;
#if defined(Q_OS_WIN)
    architecture = "x86";
#elif defined(Q_OS_MAC)
    architecture = "x86_64";
#elif defined(Q_OS_LINUX)
    architecture = "x86_64";
#else
#   error unknown host platform
#endif
    return engine->toScriptValue(architecture);
}

QScriptValue Loader::LoaderPrivate::js_getenv(QScriptContext *context, QScriptEngine *engine)
{
    if (context->argumentCount() < 1) {
        return context->throwError(QScriptContext::SyntaxError,
                                   QLatin1String("getenv expects 1 argument"));
    }
    const QByteArray name = context->argument(0).toString().toLocal8Bit();
    const QByteArray value = qgetenv(name);
    return value.isNull() ? engine->undefinedValue() : QString::fromLocal8Bit(value);
}

QScriptValue Loader::LoaderPrivate::js_configurationValue(QScriptContext *context, QScriptEngine *engine)
{
    if (context->argumentCount() < 1 || context->argumentCount() > 2) {
        return context->throwError(QScriptContext::SyntaxError,
                                   QString("configurationValue expects 1 or 2 arguments"));
    }

    const Settings &settings = get(engine)->m_settings;
    const bool defaultValueProvided = context->argumentCount() > 1;
    const QString key = context->argument(0).toString();
    QString defaultValue;
    if (defaultValueProvided) {
        const QScriptValue arg = context->argument(1);
        if (!arg.isUndefined())
            defaultValue = arg.toString();
    }
    QVariant v = settings.value(key, defaultValue);
    if (!defaultValueProvided && v.isNull())
        return context->throwError(QScriptContext::SyntaxError,
                                   QString("configuration value '%1' does not exist").arg(context->argument(0).toString()));
    return engine->toScriptValue(v);
}

void Loader::LoaderPrivate::resolveTopLevel(const ResolvedProjectPtr &rproject,
                             LanguageObject *object,
                             const QString &projectFileName,
                             ProjectData *projectData,
                             QList<RulePtr> *globalRules,
                             QList<FileTagger::ConstPtr> *globalFileTaggers,
                             const QVariantMap &userProperties,
                             const ScopeChain::Ptr &scope,
                             const ResolvedModuleConstPtr &dummyModule)
{
    if (qbsLogLevel(LoggerTrace))
        qbsTrace() << "[LDR] resolve top-level " << object->file->fileName;
    EvaluationObject *evaluationObject = new EvaluationObject(object);

    const QString propertiesName = object->prototype.join(".");
    evaluationObject->scope = Scope::create(m_engine, m_scopesWithEvaluatedProperties,
                                            propertiesName, object->file);

    Scope::Ptr productProperty = Scope::create(m_engine, m_scopesWithEvaluatedProperties,
                                               name_productPropertyScope, object->file);
    Scope::Ptr projectProperty = Scope::create(m_engine, m_scopesWithEvaluatedProperties,
                                               name_projectPropertyScope, object->file);
    Scope::Ptr oldProductProperty(scope->findNonEmpty(name_productPropertyScope));
    Scope::Ptr oldProjectProperty(scope->findNonEmpty(name_projectPropertyScope));

    // for the 'product' and 'project' property available to the modules
    ScopeChain::Ptr moduleScope(new ScopeChain(m_engine));
    moduleScope->prepend(oldProductProperty);
    moduleScope->prepend(oldProjectProperty);
    moduleScope->prepend(productProperty);
    moduleScope->prepend(projectProperty);

    ScopeChain::Ptr localScope(scope->clone());
    localScope->prepend(productProperty);
    localScope->prepend(projectProperty);
    localScope->prepend(evaluationObject->scope);

    evaluationObject->scope->properties.insert("configurationValue", Property(m_jsFunction_configurationValue));

    resolveInheritance(object, evaluationObject, moduleScope, userProperties);

    if (evaluationObject->prototype == name_Project) {
        // if this is a nested project, set a fallback scope
        Property outerProperty = scope->lookupProperty("project");
        if (outerProperty.isValid() && outerProperty.scope) {
            evaluationObject->scope->fallbackScope = outerProperty.scope;
        } else {
            // set the 'path' and 'filePath' properties
            setPathAndFilePath(evaluationObject->scope, object->file->fileName);
        }

        fillEvaluationObjectBasics(localScope, object, evaluationObject);

        // override properties from command line
        const QVariantMap overriddenProperties = userProperties.value("project").toMap();
        for (QVariantMap::const_iterator it = overriddenProperties.begin(); it != overriddenProperties.end(); ++it) {
            if (!evaluationObject->scope->properties.contains(it.key()))
                throw Error(Tr::tr("No property '%1' in project scope.").arg(it.key()));
            evaluationObject->scope->properties.insert(it.key(), Property(m_engine->toScriptValue(it.value())));
        }

        // load referenced files
        foreach (const QString &reference, evaluationObject->scope->stringListValue("references")) {
            QString projectFileDir = FileInfo::path(projectFileName);
            QString absReferencePath = FileInfo::resolvePath(projectFileDir, reference);
            ProjectFile::Ptr referencedFile = parseFile(absReferencePath);
            ScopeChain::Ptr referencedFileScope(new ScopeChain(m_engine, buildFileContext(referencedFile.data())));
            referencedFileScope->prepend(projectProperty);
            resolveTopLevel(rproject,
                            referencedFile->root,
                            referencedFile->fileName,
                            projectData,
                            globalRules,
                            globalFileTaggers,
                            userProperties,
                            referencedFileScope,
                            dummyModule);
        }

        // load children
        ScopeChain::Ptr childScope(scope->clone()->prepend(projectProperty));
        foreach (LanguageObject *child, object->children)
            resolveTopLevel(rproject,
                            child,
                            projectFileName,
                            projectData,
                            globalRules,
                            globalFileTaggers,
                            userProperties,
                            childScope,
                            dummyModule);

        return;
    } else if (evaluationObject->prototype == name_Rule) {
        fillEvaluationObject(localScope, object, evaluationObject->scope, evaluationObject, userProperties);
        globalRules->append(resolveRule(evaluationObject, dummyModule));

        return;
    } else if (evaluationObject->prototype == name_FileTagger) {
        fillEvaluationObject(localScope, object, evaluationObject->scope, evaluationObject, userProperties);
        globalFileTaggers->append(resolveFileTagger(evaluationObject));

        return;
    } else if (evaluationObject->prototype != name_Product) {
        QString msg = Tr::tr("'%1' is not allowed here.");
        throw Error(msg.arg(evaluationObject->prototype),
                    evaluationObject->instantiatingObject()->prototypeLocation);
    }

    // set the 'path' and 'filePath' properties
    setPathAndFilePath(evaluationObject->scope, object->file->fileName);

    const ResolvedProductPtr rproduct = ResolvedProduct::create();
    rproduct->qbsFile = projectFileName;
    rproduct->qbsLine = evaluationObject->instantiatingObject()->prototypeLocation.line;
    rproduct->sourceDirectory = QFileInfo(projectFileName).absolutePath();
    rproduct->project = rproject;

    ProductData productData;
    productData.product = evaluationObject;

    evaluateDependencies(object, evaluationObject, localScope, moduleScope, userProperties);
    fillEvaluationObject(localScope, object, evaluationObject->scope, evaluationObject, userProperties);
    evaluateDependencyConditions(evaluationObject);
    productData.usedProducts = evaluationObject->unknownModules;

    // check if product's name is empty and set a default value
    Property &nameProperty = evaluationObject->scope->properties["name"];
    if (nameProperty.value.isUndefined()) {
        QString projectName = FileInfo::fileName(projectFileName);
        projectName.chop(4);
        nameProperty.value = m_engine->toScriptValue(projectName);
    }

    // override properties from command line
    productData.originalProductName = evaluationObject->scope->stringValue("name");
    const QVariantMap overriddenProperties = userProperties.value(productData.originalProductName).toMap();
    for (QVariantMap::const_iterator it = overriddenProperties.begin(); it != overriddenProperties.end(); ++it) {
        if (!evaluationObject->scope->properties.contains(it.key()))
            throw Error(Tr::tr("No property '%1' in product '%2'.").arg(it.key(), productData.originalProductName));
        evaluationObject->scope->properties.insert(it.key(), Property(m_engine->toScriptValue(it.value())));
    }

    if (!object->id.isEmpty()) {
        Scope::Ptr context = scope->last();
        context->properties.insert(object->id, Property(evaluationObject));
    }

    // collect all dependent modules and put them into the product
    QHash<QString, ProjectFile *> moduleDependencies = findModuleDependencies(evaluationObject);
    QHashIterator<QString, ProjectFile *> it(moduleDependencies);
    while (it.hasNext()) {
        it.next();

        Module::Ptr moduleInProduct = productData.product->modules.value(it.key());
        if (moduleInProduct) {
            if (moduleInProduct->file() != it.value())
                throw Error(Tr::tr("two different versions of '%1' were used: '%2' and '%3'").arg(
                                it.key(), it.value()->fileName, moduleInProduct->file()->fileName));
            continue;
        }

        Module::Ptr module = loadModule(it.value(), QStringList(), it.key(), moduleScope, userProperties,
                                        CodeLocation(object->file->fileName));
        if (!module) {
            throw Error(Tr::tr("could not load module '%1' from file '%2' into product even though it was loaded into a submodule").arg(
                                   it.key(), it.value()->fileName));
        }
        evaluationObject->modules.insert(module->name, module);
    }
    buildModulesProperty(evaluationObject);

    // check the product's condition
    if (!checkCondition(evaluationObject)) {
        // Remove product from configuration if it is disabled
        const QString productName = evaluationObject->scope->stringValue("name");
        projectData->removedProducts += productData;
        if (qbsLogLevel(LoggerTrace))
            qbsTrace() << "[LDR] condition for product '" << productName << "' is false.";
        return;
    }

    projectData->products.insert(rproduct, productData);
}

void Loader::LoaderPrivate::checkUserProperties(const Loader::LoaderPrivate::ProjectData &projectData,
                                 const QVariantMap &userProperties)
{
    QSet<QString> allowedUserPropertyNames;
    allowedUserPropertyNames << QLatin1String("project");
    for (QHash<ResolvedProductPtr, ProductData>::const_iterator it = projectData.products.constBegin();
         it != projectData.products.constEnd(); ++it)
    {
        const ResolvedProductPtr &product = it.key();
        const ProductData &productData = it.value();
        allowedUserPropertyNames += product->name;
        allowedUserPropertyNames += productData.originalProductName;
        foreach (const ResolvedModuleConstPtr &module, product->modules) {
            allowedUserPropertyNames += module->name;
            foreach (const QString &dependency, module->moduleDependencies)
                allowedUserPropertyNames += dependency;
        }
    }
    foreach (const ProductData &productData, projectData.removedProducts) {
        allowedUserPropertyNames += productData.originalProductName;
        allowedUserPropertyNames += productData.product->scope->stringValue("name");
    }

    for (QVariantMap::const_iterator it = userProperties.begin(); it != userProperties.end(); ++it) {
        const QString &propertyName = it.key();
        if (allowedUserPropertyNames.contains(propertyName))
            continue;
        if (existsModuleInSearchPath(propertyName))
            continue;
        throw Error(Tr::tr("%1 is not a product or a module.").arg(propertyName));
    }
}

void Loader::LoaderPrivate::resolveProduct(const ResolvedProductPtr &rproduct,
        const ResolvedProjectPtr &project, ProductData &data, Loader::LoaderPrivate::ProductMap &products,
        const QList<RulePtr> &globalRules, const QList<FileTagger::ConstPtr> &globalFileTaggers,
        const ResolvedModuleConstPtr &dummyModule)
{
    Scope *productProps = data.product->scope.data();

    rproduct->name = productProps->stringValue("name");
    rproduct->targetName = productProps->stringValue("targetName");
    rproduct->properties = PropertyMap::create();

    // insert property "buildDirectory"
    {
        Property p(m_engine->toScriptValue(project->buildDirectory));
        productProps->properties.insert("buildDirectory", p);
    }

    rproduct->fileTags = productProps->stringListValue("type");
    rproduct->destinationDirectory = productProps->stringValue("destination");
    foreach (const RulePtr &rule, globalRules)
        rproduct->rules.insert(rule);
    foreach (const FileTagger::ConstPtr &fileTagger, globalFileTaggers)
        rproduct->fileTaggers.insert(fileTagger);
    const QString lowerProductName = rproduct->name.toLower();
    products.insert(lowerProductName, rproduct);

    // resolve the modules for this product
    for (QHash<QString, Module::Ptr>::const_iterator modIt = data.product->modules.begin();
         modIt != data.product->modules.end(); ++modIt)
    {
        resolveModule(rproduct, modIt.key(), modIt.value()->object);
    }

    QList<EvaluationObject *> unresolvedChildren
            = resolveCommonItems(data.product->children, rproduct, dummyModule);

    // fill the product's configuration
    QVariantMap productCfg = evaluateAll(rproduct, data.product->scope);
    rproduct->properties->setValue(productCfg);

    // handle the 'Product.files' property
    {
        QScriptValue files = data.product->scope->property("files");
        if (files.isValid()) {
            resolveGroup(rproduct, data.product, data.product);
        }
    }

    foreach (EvaluationObject *child, unresolvedChildren) {
        const uint prototypeNameHash = qHash(child->prototype);
        if (prototypeNameHash == hashName_Group) {
            resolveGroup(rproduct, data.product, child);
        } else if (prototypeNameHash == hashName_ProductModule) {
            child->scope->properties.insert("product", Property(data.product));
            resolveProductModule(rproduct, child);
            data.usedProductsFromProductModule += child->unknownModules;
        }
    }

    // Apply file taggers.
    foreach (const SourceArtifactPtr &artifact, rproduct->allFiles())
        applyFileTaggers(artifact, rproduct);
    foreach (const ResolvedTransformer::Ptr &transformer, rproduct->transformers)
        foreach (const SourceArtifactPtr &artifact, transformer->outputs)
            applyFileTaggers(artifact, rproduct);

    // Merge duplicate artifacts.
    QHash<QString, QPair<ResolvedGroup::Ptr, SourceArtifactPtr> > uniqueArtifacts;
    foreach (const ResolvedGroup::Ptr &group, rproduct->groups) {
        Q_ASSERT(group->properties);

        QList<SourceArtifactPtr> artifactsInGroup = group->files;
        if (group->wildcards)
            artifactsInGroup += group->wildcards->files;

        foreach (const SourceArtifactPtr &artifact, artifactsInGroup) {
            QPair<ResolvedGroup::Ptr, SourceArtifactPtr> p = uniqueArtifacts.value(artifact->absoluteFilePath);
            SourceArtifactPtr existing = p.second;
            if (existing) {
                // if an artifact is in the product and in a group, prefer the group configuration
                if (existing->properties != rproduct->properties)
                    throw Error(Tr::tr("Artifact '%1' is in more than one group.").arg(artifact->absoluteFilePath),
                                CodeLocation(m_project->fileName));

                // Remove the artifact that's in the product's group.
                p.first->files.removeOne(existing);

                // Merge artifacts.
                if (!artifact->overrideFileTags)
                    artifact->fileTags.unite(existing->fileTags);
            }
            uniqueArtifacts.insert(artifact->absoluteFilePath, qMakePair(group, artifact));
        }
    }

    project->products.append(rproduct);
}

void Loader::LoaderPrivate::resolveProductDependencies(const ResolvedProjectPtr &project,
        ProjectData &projectData, const ProductMap &resolvedProducts)
{
    // Collect product dependencies from ProductModules.
    bool productDependenciesAdded;
    do {
        productDependenciesAdded = false;
        foreach (ResolvedProductPtr rproduct, project->products) {
            ProductData &productData = projectData.products[rproduct];
            foreach (const UnknownModule::Ptr &unknownModule, productData.usedProducts) {
                const QString &usedProductName = unknownModule->name;
                QList<ResolvedProductPtr> usedProductCandidates = resolvedProducts.values(usedProductName);
                if (usedProductCandidates.count() < 1) {
                    if (!unknownModule->required) {
                        if (!unknownModule->failureMessage.isEmpty())
                            qbsWarning() << unknownModule->failureMessage;
                        continue;
                    }
                    throw Error(Tr::tr("Product dependency '%1' not found in '%2'.").arg(usedProductName, rproduct->qbsFile),
                                CodeLocation(m_project->fileName));
                }
                if (usedProductCandidates.count() > 1)
                    throw Error(Tr::tr("Product dependency '%1' is ambiguous.").arg(usedProductName),
                                CodeLocation(m_project->fileName));
                ResolvedProductPtr usedProduct = usedProductCandidates.first();
                const ProductData &usedProductData = projectData.products.value(usedProduct);
                bool added;
                productData.addUsedProducts(usedProductData.usedProductsFromProductModule, &added);
                if (added)
                    productDependenciesAdded = true;
            }
        }
    } while (productDependenciesAdded);

    // Resolve all inter-product dependencies.
    foreach (ResolvedProductPtr rproduct, project->products) {
        foreach (const UnknownModule::Ptr &unknownModule, projectData.products.value(rproduct).usedProducts) {
            const QString &usedProductName = unknownModule->name;
            QList<ResolvedProductPtr> usedProductCandidates = resolvedProducts.values(usedProductName);
            if (usedProductCandidates.count() < 1) {
                if (!unknownModule->required) {
                    if (!unknownModule->failureMessage.isEmpty())
                        qbsWarning() << unknownModule->failureMessage;
                    continue;
                }
                throw Error(Tr::tr("Product dependency '%1' not found.").arg(usedProductName),
                            CodeLocation(m_project->fileName));
            }
            if (usedProductCandidates.count() > 1)
                throw Error(Tr::tr("Product dependency '%1' is ambiguous.").arg(usedProductName),
                            CodeLocation(m_project->fileName));
            ResolvedProductPtr usedProduct = usedProductCandidates.first();
            rproduct->dependencies.insert(usedProduct);

            // insert the configuration of the ProductModule into the product's configuration
            const QVariantMap productModuleConfig = m_productModules.value(usedProductName);
            if (productModuleConfig.isEmpty())
                continue;

            QVariantMap productProperties = rproduct->properties->value();
            QVariantMap modules = productProperties.value("modules").toMap();
            modules.insert(usedProductName, productModuleConfig);
            productProperties.insert("modules", modules);
            rproduct->properties->setValue(productProperties);

            // insert the configuration of the ProductModule into the artifact configurations
            foreach (SourceArtifactPtr artifact, rproduct->allFiles()) {
                if (artifact->properties == rproduct->properties)
                    continue; // Already inserted above.
                QVariantMap sourceArtifactProperties = artifact->properties->value();
                QVariantMap modules = sourceArtifactProperties.value("modules").toMap();
                modules.insert(usedProductName, productModuleConfig);
                sourceArtifactProperties.insert("modules", modules);
                artifact->properties->setValue(sourceArtifactProperties);
            }
        }
    }
}

ProjectFile::ProjectFile()
    : m_destructing(false)
{
}

ProjectFile::~ProjectFile()
{
    m_destructing = true;
    qDeleteAll(m_evaluationObjects);
    qDeleteAll(m_languageObjects);
}

void Loader::LoaderPrivate::ProductData::addUsedProducts(const QList<UnknownModule::Ptr> &additionalUsedProducts, bool *productsAdded)
{
    int oldCount = usedProducts.count();
    QSet<QString> usedProductNames;
    foreach (const UnknownModule::Ptr &usedProduct, usedProducts)
        usedProductNames += usedProduct->name;
    foreach (const UnknownModule::Ptr &usedProduct, additionalUsedProducts)
        if (!usedProductNames.contains(usedProduct->name))
            usedProducts += usedProduct;
    *productsAdded = (oldCount != usedProducts.count());
}

} // namespace Internal
} // namespace qbs

QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(qbs::ConditionalBinding, Q_MOVABLE_TYPE);
QT_END_NAMESPACE