File: cmakeprojectvisitor.cpp

package info (click to toggle)
kdevelop 4%3A4.3.1-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 18,844 kB
  • sloc: cpp: 91,758; python: 1,095; lex: 422; ruby: 120; sh: 114; xml: 42; makefile: 38
file content (2428 lines) | stat: -rw-r--r-- 81,943 bytes parent folder | download
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
/* KDevelop CMake Support
 *
 * Copyright 2007-2008 Aleix Pol <aleixpol@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include "cmakeprojectvisitor.h"
#include "cmakeast.h"
#include "cmakecondition.h"
#include "astfactory.h"

#include <language/editor/simplerange.h>
#include <language/duchain/topducontext.h>
#include <language/duchain/duchain.h>
#include <language/duchain/duchainlock.h>
#include <language/duchain/parsingenvironment.h>
#include <language/duchain/declaration.h>
#include <language/duchain/types/functiontype.h>
#include <language/duchain/types/delayedtype.h>

#include <KProcess>
#include <KLocale>
#include <KDebug>
#include <QHash>
#include <QQueue>
#include <QFile>
#include <QDir>
#include <QtCore/qglobal.h>
#include <QByteArray>
#include <QFileInfo>
#include <QScriptEngine>
#include <QScriptValue>

using namespace KDevelop;

void debugMsgs(const QString& message) { kDebug(9032) << "message:" << message; }

CMakeProjectVisitor::message_callback CMakeProjectVisitor::s_msgcallback=debugMsgs;

CMakeProjectVisitor::CMakeProjectVisitor(const QString& root, ReferencedTopDUContext parent)
    : m_root(root), m_vars(0), m_macros(0), m_topctx(0), m_parentCtx(parent), m_hitBreak(false)
{
}

QStringList CMakeProjectVisitor::envVarDirectories(const QString &varName) const
{
    QString env;
    QMap< QString, QString >::const_iterator it=m_environmentProfile.constFind(varName);
    if(it!=m_environmentProfile.constEnd())
        env = *it;
    else
        env = QString::fromLatin1(qgetenv(varName.toLatin1()));
    
//     kDebug(9042) << ".......resolving env:" << varName << "=" << QProcess::systemEnvironment() << env;
    if(!env.isEmpty())
    {
        QChar separator;
#ifdef Q_OS_WIN
        separator = ';';
#else
        separator = ':';
#endif
        kDebug(9042) << "resolving env:" << varName << "=" << env;
        return env.split(separator);
    }
    else
    {
        kDebug(9032) << "warning:" << varName << " not found";
        return QStringList();
    }
}

QList< CMakeProjectVisitor::IntPair > CMakeProjectVisitor::parseArgument(const QString &exp)
{
    QString name;
    QStack<int> opened;
    QList< IntPair > pos;
    bool gotDollar=false;
    for(int i=exp.indexOf('$'); i<exp.size() && i>=0; i++)
    {
        switch(exp[i].unicode())
        {
            case '$':
                gotDollar=true;
                break;
            case '{':
                if(gotDollar)
                {
                    opened.push(i);
                }
                gotDollar=false;
                break;
            case '}':
                if(!opened.isEmpty())
                    pos.append(IntPair(opened.pop(), i, opened.count()));
                break;
        }
    }

    for(int i=pos.count()-1; i>=0 && !opened.isEmpty(); i--)
    {
        if(pos[i].first==opened.top())
            opened.pop();
        pos[i].level -= opened.size();
    }
    return pos;
}

QStringList CMakeProjectVisitor::variableValue(const QString& var) const
{
    VariableMap::const_iterator it=m_vars->constFind(var);
    if(it!=m_vars->constEnd())
        return *it;
    else {
        CacheValues::const_iterator it=m_cache->constFind(var);
        if(it!=m_cache->constEnd())
            return it->value.split(';');
    }
    return QStringList();
}

QStringList CMakeProjectVisitor::theValue(const QString& exp, const IntPair& thecase) const
{
    int dollar=exp.lastIndexOf('$', thecase.first);
    QString type=exp.mid(dollar+1, thecase.first-dollar-1);
    QString var=exp.mid(thecase.first+1, thecase.second-thecase.first-1);
    QStringList value;
//     kDebug() << "lalalallalala" << exp << thecase.print();
    if(type.isEmpty())
    {
        value=variableValue(var);
    }
    else if(type=="ENV")
    {
        value=envVarDirectories(var);
    }
    else
        kDebug() << "error: I do not understand the key: " << type;

//     kDebug() << "solving: " << var << vars << exp;
    return value;
}

QString replaceOne(const QString& var, const QString& id, const QString& value, int dollar)
{
//     kDebug() << "ooo" << var << value << id << var[dollar+id.size()-1] << (dollar+id.size());
//     kDebug() << "kkkk" << var.mid(0, dollar) << value << var.mid(dollar+id.size(), var.size()-(dollar+id.size()));
    return var.mid(0, dollar)+value+var.mid(dollar+id.size(), var.size()-(dollar+id.size()));
}

QStringList CMakeProjectVisitor::value(const QString& exp, const QList<IntPair>& poss, int& desired) const
{
    QString var=exp;
    QList<IntPair> invars;
    invars += poss[desired];
    //kDebug() << ">>>>>" << exp << desired << poss.count();
    for(; desired+1<poss.size() && poss[desired].level>1; desired++)
    {
        invars+=poss[desired+1];
        //kDebug() << "poss@"<< desired+1 << "="<< poss[desired+1].print();
    }

    //kDebug() << ";;;;;" << invars.count();
    if(invars.count()>1)
    {
        QList<IntPair>::const_iterator itConstEnd=invars.constEnd();
        QList<IntPair>::iterator itEnd=invars.end();
        QList<IntPair>::iterator itBegin=invars.begin();
        for(QList<IntPair>::const_iterator it=invars.constBegin(); (it+1)!=itConstEnd; ++it)
        {
            const IntPair& subvar=*it;
            int dollar=var.lastIndexOf('$', subvar.first);
            QString id=var.mid(dollar, subvar.second-dollar+1), value=theValue(var, subvar).join(QChar(';'));

            int diff=value.size()-id.size();
            for(QList<IntPair>::iterator it=itBegin; it!=itEnd; ++it)
            {
                if(it->first > subvar.first) it->first += diff;
                if(it->second> subvar.second) it->second+= diff;
            }

            var=replaceOne(var, id, value, dollar);
        }
    }
    return theValue(var, invars.last());
}

QStringList CMakeProjectVisitor::resolveVariable(const CMakeFunctionArgument &exp)
{
    QStringList ret;
    ret += QString();
    QList< IntPair > var = parseArgument(exp.value);

    int i=0;
    IntPair last(-1,-1, 0);

    for(QList<IntPair>::const_iterator it=var.constBegin(); it!=var.constEnd(); ++it, ++i)
    {
        while(it!=var.constEnd() && it->level>1)
            ++it;

        const IntPair& p=*it;
//         kDebug () << "reeeeeet" << ret << exp.value << p.print();
        int dollar=exp.value.lastIndexOf('$', p.first);
        QString pre=exp.value.mid(last.second+1, dollar-last.second-1);

        QStringList vars = value(exp.value, var, i);
//         kDebug() << "aaaaaaaaaA" << pre << vars;

        if(!vars.isEmpty())
        {
            pre+=vars.takeFirst();
        }
        ret.last()+=pre;
        ret += vars;
        last=p;
        
//         kDebug() << "yaaaaaaa" << ret;
//         i++;
    }
    ret.last().append(exp.value.mid(last.second+1, exp.value.count()-last.second));

    if(exp.quoted) {
        ret=QStringList(ret.join(QChar(';')));
    } else if(ret.size()==1 && ret.first().isEmpty()) {
        ret.clear();
    }
    
    return ret;
}

int CMakeProjectVisitor::notImplemented(const QString &name) const
{
    kDebug(9042) << "not implemented!" << name;
    return 1;
}

bool CMakeProjectVisitor::hasMacro(const QString& name) const
{
    Q_ASSERT(m_macros);
    return m_macros->contains(name);
}

int CMakeProjectVisitor::visit(const CMakeAst *ast)
{
    kDebug(9042) << "error! function not implemented" << ast->content()[ast->line()].name;
    foreach(const CMakeFunctionArgument& arg, ast->outputArguments())
    {
        //NOTE: this is a workaround, but fixes some issues.
        kDebug(9042) << "reseting: " << arg.value;
        m_vars->insert(arg.value, QStringList());
    }
    return 1;
}

int CMakeProjectVisitor::visit( const AddTestAst * test)
{
    Q_UNUSED(test);
    return 1;
}

int CMakeProjectVisitor::visit(const ProjectAst *project)
{
    m_projectName = project->projectName();
    if(!m_vars->contains("CMAKE_PROJECT_NAME"))
        m_vars->insert("CMAKE_PROJECT_NAME", QStringList(project->projectName()));
    
    m_vars->insert("PROJECT_NAME", QStringList(project->projectName()));
    m_vars->insert("PROJECT_SOURCE_DIR", m_vars->value("CMAKE_CURRENT_SOURCE_DIR"));
    m_vars->insert("PROJECT_BINARY_DIR", m_vars->value("CMAKE_CURRENT_BINARY_DIR"));
    m_vars->insert(QString("%1_SOURCE_DIR").arg(m_projectName), m_vars->value("CMAKE_CURRENT_SOURCE_DIR"));
    m_vars->insert(QString("%1_BINARY_DIR").arg(m_projectName), m_vars->value("CMAKE_CURRENT_BINARY_DIR"));
    return 1;
}

int CMakeProjectVisitor::visit( const SetTargetPropsAst * targetProps)
{
    kDebug(9042) << "setting target props for " << targetProps->targets() << targetProps->properties();
    foreach(const QString& tname, targetProps->targets())
    {
        foreach(const SetTargetPropsAst::PropPair& t, targetProps->properties())
        {
            m_props[TargetProperty][tname][t.first] = t.second.split(';');
        }
    }
    return 1;
}

int CMakeProjectVisitor::visit( const SetDirectoryPropsAst * dirProps)
{   
    QString dir=m_vars->value("CMAKE_CURRENT_SOURCE_DIR").join(QString());
    kDebug(9042) << "setting directory props for " << dirProps->properties() << dir;
    foreach(const SetDirectoryPropsAst::PropPair& t, dirProps->properties())
    {
        m_props[DirectoryProperty][dir][t.first] = t.second.split(';');
    }
    return 1;
}

int CMakeProjectVisitor::visit( const GetTargetPropAst * prop)
{
    kDebug(9042) << "getting target " << prop->target() << " prop " << prop->property() << prop->variableName();
    QStringList value;
    
    CategoryType& category = m_props[TargetProperty];
    CategoryType::iterator itTarget = category.find(prop->target());
    if(itTarget!=category.end()) {
        QMap<QString, QStringList>& targetProps = itTarget.value();
        if(!targetProps.contains(prop->property())) {
            if(prop->property().startsWith("LOCATION_") && targetProps.contains("IMPORTED_"+prop->property()))
                targetProps[prop->property()] = targetProps["IMPORTED_"+prop->property()];
        }
        value = targetProps.value(prop->property());
    }
    if(value.isEmpty())
        value += QString(prop->variableName()+"-NOTFOUND");
    
    m_vars->insert(prop->variableName(), value);
//     kDebug(9042) << "goooooot" << m_vars->value(prop->variableName());
    return 1;
}

int CMakeProjectVisitor::visit(const AddSubdirectoryAst *subd)
{
    kDebug(9042) << "adding subdirectory" << subd->sourceDir();

    VisitorState p=stackTop();

    Subdirectory d;
    d.name=subd->sourceDir();
    d.build_dir=subd->binaryDir().isEmpty() ? d.name : subd->binaryDir();
    d.desc=p.code->at(p.line);
    
    m_subdirectories += d;
    return 1;
}

int CMakeProjectVisitor::visit(const SubdirsAst *sdirs)
{
    kDebug(9042) << "adding subdirectories" << sdirs->directories() << sdirs->exluceFromAll();
    VisitorState p=stackTop();
    CMakeFunctionDesc desc=p.code->at(p.line);
    
    foreach(const QString& dir, sdirs->directories() + sdirs->exluceFromAll()) {
        Subdirectory d;
        d.name=dir;
        d.build_dir=dir;
        d.desc=desc;
        
        m_subdirectories += d;
    }
    return 1;
}

void CMakeProjectVisitor::printBacktrace(const QStack<VisitorState> &backtrace)
{
    int i=0;
    kDebug() << "backtrace" << backtrace.count();
    foreach(const VisitorState& v, backtrace)
    {
        if(v.code->count()>v.line)
          kDebug(9042) << i << ": ";//           << v.code->at(v.line).name;
        else
          kDebug(9042) << i << ": ------------------------";
        i++;
    }
}

CMakeProjectVisitor::VisitorState CMakeProjectVisitor::stackTop() const
{
    VisitorState p;
    QString filename=m_backtrace.front().code->at(m_backtrace.front().line).filePath;
    QStack<VisitorState>::const_iterator it=m_backtrace.constBegin();

    for(; it!=m_backtrace.constEnd(); ++it)
    {
        if(filename!=it->code->at(it->line).filePath)
            break;

        p=*it;
    }
    return p;
}

void CMakeProjectVisitor::defineTarget(const QString& id, const QStringList& sources, Target::Type t)
{
    kDebug(9042) << "Defining target" << id;
    if (m_targetForId.contains(id))
        kDebug(9032) << "warning! there already was a target called" << id;

    VisitorState p=stackTop();

    Declaration *d=0;
    if(!p.code->at(p.line).arguments.isEmpty()) {
        DUChainWriteLocker lock(DUChain::lock());
        d= new Declaration(p.code->at(p.line).arguments.first().range(), p.context);
        d->setIdentifier( Identifier(id) );
    }
    
    Target target;
    target.name=id.isEmpty() ? "<wrong-target>" : id;
    target.declaration=d;
    target.files=sources;
    target.type=t;
    target.desc=p.code->at(p.line);
    
    m_targetForId[id]=target;

    QString exe=id;
    switch(t) {
        case Target::Executable:
            exe += m_vars->value("CMAKE_EXECUTABLE_SUFFIX").join(QString());
            break;
        case Target::Library:
            exe = QString("%1%2%3").arg(m_vars->value("CMAKE_LIBRARY_PREFIX").join(QString())).arg(id).arg(m_vars->value("CMAKE_LIBRARY_SUFFIX").join(QString()));
            break;
        case Target::Custom:
            break;
    }
    
    m_props[TargetProperty][id]["LOCATION"]=QStringList(m_vars->value("CMAKE_CURRENT_BINARY_DIR").join(QString())+'/'+exe);
}

int CMakeProjectVisitor::visit(const AddExecutableAst *exec)
{
    if(!exec->isImported())
        defineTarget(exec->executable(), exec->sourceLists(), Target::Executable);
    else
        kDebug(9042) << "imported executable" << exec->executable();
    kDebug(9042) << "exec:" << exec->executable() << "->" << m_targetForId.contains(exec->executable())
        << "imported" << exec->isImported();
    return 1;
}

int CMakeProjectVisitor::visit(const AddLibraryAst *lib)
{
    if(!lib->isImported())
        defineTarget(lib->libraryName(), lib->sourceLists(), Target::Library);
    kDebug(9042) << "lib:" << lib->libraryName();
    return 1;
}

int CMakeProjectVisitor::visit(const SetAst *set)
{
    //TODO: Must deal with ENV{something} case
    if(set->storeInCache()) {
        QStringList values;
        CacheValues::const_iterator itCache= m_cache->constFind(set->variableName());
        if(itCache!=m_cache->constEnd())
            values = itCache->value.split(';');
        else
            values = set->values();
        
        m_vars->insertGlobal(set->variableName(), values);
    } else
        m_vars->insert(set->variableName(), set->values(), set->parentScope());
    
    kDebug(9042) << "setting variable:" << set->variableName() << set->parentScope() /*<< "to" << values*/;
    return 1;
}

int CMakeProjectVisitor::visit(const IncludeDirectoriesAst * dirs)
{
    kDebug(9042) << "adding include directories" << dirs->includedDirectories();
    IncludeDirectoriesAst::IncludeType t = dirs->includeType();

    QStringList toInclude = dirs->includedDirectories();

    if(t==IncludeDirectoriesAst::Default)
    {
        if(m_vars->contains("CMAKE_INCLUDE_DIRECTORIES_BEFORE") && m_vars->value("CMAKE_INCLUDE_DIRECTORIES_BEFORE")[0]=="ON")
            t = IncludeDirectoriesAst::Before;
        else
            t = IncludeDirectoriesAst::After;
    }

    if(t==IncludeDirectoriesAst::After)
        m_includeDirectories += toInclude;
    else
        m_includeDirectories = toInclude + m_includeDirectories;
    kDebug(9042) << "done." << m_includeDirectories;
    return 1;
}

QString CMakeProjectVisitor::findFile(const QString &file, const QStringList &folders,
        const QStringList& suffixes, bool location)
{
    if( file.isEmpty() || QFileInfo(file).isAbsolute() )
         return file;

    QStringList suffixFolders, useSuffixes(suffixes);
    useSuffixes.prepend(QString());
    foreach(const QString& apath, folders)
    {
        foreach(const QString& suffix, useSuffixes)
        {
            suffixFolders.append(apath+'/'+suffix);
        }
    }

    KUrl path;
    foreach(const QString& mpath, suffixFolders)
    {
        if(mpath.isEmpty())
            continue;

        KUrl afile(mpath);
        afile.addPath(file);
        kDebug(9042) << "Trying:" << mpath << '.' << file;
        QFileInfo f(afile.toLocalFile());
        if(f.exists() && f.isFile())
        {
            if(location)
                path=mpath;
            else
                path=afile;
            break;
        }
    }
    //kDebug(9042) << "find file" << file << "into:" << folders << "found at:" << path;
    return path.toLocalFile(KUrl::RemoveTrailingSlash);
}

int CMakeProjectVisitor::visit(const IncludeAst *inc)
{
    Q_ASSERT(m_vars->contains("CMAKE_CURRENT_SOURCE_DIR"));
    const QStringList modulePath = m_vars->value("CMAKE_MODULE_PATH") + m_modulePath + m_vars->value("CMAKE_CURRENT_SOURCE_DIR");
    kDebug(9042) << "Include:" << inc->includeFile() << "@" << modulePath << " into ";

    QString possib=inc->includeFile();
    QString path;
    if(!KUrl(possib).isRelative() && QFile::exists(possib))
        path=possib;
    else
    {
        if(!possib.contains('.'))
            possib += ".cmake";
        path=findFile(possib, modulePath);
    }

    if(!path.isEmpty())
    {
        m_vars->insertMulti("CMAKE_CURRENT_LIST_FILE", QStringList(path));
        m_vars->insertMulti("CMAKE_CURRENT_LIST_DIR", QStringList(KUrl(path).directory()));
        CMakeFileContent include = CMakeListsParser::readCMakeFile(path);
        if ( !include.isEmpty() )
        {
            kDebug(9042) << "including:" << path;
            walk(include, 0, true);
        }
        else
        {
            //FIXME: Put here the error.
            kDebug(9042) << "Include. Parsing error.";
        }
        m_vars->remove("CMAKE_CURRENT_LIST_FILE");
        m_vars->remove("CMAKE_CURRENT_LIST_DIR");
    }
    else
    {
        if(!inc->optional())
        {
            kDebug(9032) << "error!! Could not find" << inc->includeFile() << "=" << possib << "into" << modulePath;
        }
    }

    if(!inc->resultVariable().isEmpty())
    {
        QString result="NOTFOUND";
        if(!path.isEmpty())
            result=path;
        m_vars->insert(inc->resultVariable(), QStringList(result));
    }
    kDebug(9042) << "include of" << inc->includeFile() << "done.";
    return 1;
}

int CMakeProjectVisitor::visit(const FindPackageAst *pack)
{
    if(!haveToFind(pack->name()))
        return 1;
    kDebug(9042) << "Find:" << pack->name() << "package." << pack->version() << m_modulePath << "No module: " << pack->noModule();

    QStringList possibleModuleNames;
    if(!pack->noModule()) //TODO Also implied by a whole slew of additional options.
    {
        // Look for a Find{package}.cmake
        QString possib=pack->name();
        if(!possib.endsWith(".cmake"))
            possib += ".cmake";
        possib.prepend("Find");
        possibleModuleNames += possib;
    }

    const QStringList modulePath = m_vars->value("CMAKE_MODULE_PATH") + m_modulePath;
    QString name=pack->name();
    QStringList postfix=QStringList() << QString() << "/cmake" << "/CMake";
    QStringList configPath;
    QStringList lookupPaths = m_cache->value("CMAKE_PREFIX_PATH").value.split(';', QString::SkipEmptyParts) + m_vars->value("CMAKE_SYSTEM_PREFIX_PATH");
    
    foreach(const QString& lookup, lookupPaths)
    {
        if(QFile::exists(lookup))
            foreach(const QString& post, postfix)
            {
                configPath.prepend(lookup+"/share/"+name.toLower()+post);
                configPath.prepend(lookup+"/lib/"+name.toLower()+post);
                configPath.prepend(lookup+"/share/"+name+post);
                configPath.prepend(lookup+"/lib/"+name+post);
            }
    }

    QString varName=pack->name()+"_DIR";
    if(m_cache->contains(varName))
        configPath.prepend(m_cache->value(varName).value);

    QStringList possibleConfigNames;
    possibleConfigNames+=QString("%1Config.cmake").arg(pack->name());
    possibleConfigNames+=QString("%1-config.cmake").arg(pack->name().toLower());

    bool isConfig=false;
    QString path;
    foreach(const QString& possib, possibleConfigNames) {
        path = findFile(possib, configPath);
        if (!path.isEmpty()) {
            m_vars->insertGlobal(pack->name()+"_DIR", QStringList(KUrl(path).directory()));
            isConfig=true;
            break;
        }
    }
    
    if (path.isEmpty()) {
        foreach(const QString& possib, possibleModuleNames)
        {
            path=findFile(possib, modulePath);
            if(!path.isEmpty()) {
                break;
            }
        }
    }

    if(!path.isEmpty())
    {
        m_vars->insertMulti("CMAKE_CURRENT_LIST_FILE", QStringList(path));
        m_vars->insertMulti("CMAKE_CURRENT_LIST_DIR", QStringList(KUrl(path).directory()));
        if(pack->isRequired())
            m_vars->insert(pack->name()+"_FIND_REQUIRED", QStringList("TRUE"));
        if(pack->isQuiet())
            m_vars->insert(pack->name()+"_FIND_QUIET", QStringList("TRUE"));
        if(!pack->components().isEmpty()) m_vars->insert(pack->name()+"_FIND_COMPONENTS", pack->components());
        m_vars->insert(pack->name()+"_FIND_VERSION", QStringList(pack->version()));
        QStringList version = pack->version().split('.');
        if(version.size()>=1) m_vars->insert(pack->name()+"_FIND_VERSION_MAJOR", QStringList(version[0]));
        if(version.size()>=2) m_vars->insert(pack->name()+"_FIND_VERSION_MINOR", QStringList(version[1]));
        if(version.size()>=3) m_vars->insert(pack->name()+"_FIND_VERSION_PATCH", QStringList(version[2]));
        if(version.size()>=4) m_vars->insert(pack->name()+"_FIND_VERSION_TWEAK", QStringList(version[3]));
        m_vars->insert(pack->name()+"_FIND_VERSION_COUNT", QStringList(QString::number(version.size())));
        
        CMakeFileContent package=CMakeListsParser::readCMakeFile( path );
        if ( !package.isEmpty() )
        {
            path=KUrl(path).pathOrUrl();
            kDebug(9042) << "================== Found" << path << "===============";
            walk(package, 0, true);
        }
        else
        {
            kDebug(9032) << "error: find_package. Parsing error." << path;
        }

        if(pack->noModule())
        {
            m_vars->insertGlobal(QString("%1_CONFIG").arg(pack->name()), QStringList(path));
        }
        m_vars->remove("CMAKE_CURRENT_LIST_FILE");
        m_vars->remove("CMAKE_CURRENT_LIST_DIR");
        
        if(isConfig)
            m_vars->insert(pack->name()+"_FOUND", QStringList("TRUE"));
    }
    else
    {
        if(pack->isRequired()) {
            //FIXME: Put here the error.
            kDebug(9032) << "error: Could not find" << pack->name() << "into" << modulePath;
        }
        m_vars->insertGlobal(QString("%1_DIR").arg(pack->name()), QStringList(QString("%1_DIR-NOTFOUND").arg(pack->name())));
    }
    kDebug(9042) << "Exit. Found:" << pack->name() << m_vars->value(pack->name()+"_FOUND");

    return 1;
}

KDevelop::ReferencedTopDUContext CMakeProjectVisitor::createContext(const KUrl& path, ReferencedTopDUContext aux,
                                                                    int endl ,int endc, bool isClean)
{
    DUChainWriteLocker lock(DUChain::lock());
    KDevelop::ReferencedTopDUContext topctx=DUChain::self()->chainForDocument(path);
    
    if(topctx)
    {
        if(isClean) {
            topctx->deleteLocalDeclarations();
            topctx->deleteChildContextsRecursively();
            topctx->deleteUses();
        }
        
        foreach(DUContext* importer, topctx->importers())
            importer->removeImportedParentContext(topctx);
        topctx->clearImportedParentContexts();
    }
    else
    {
        IndexedString idxpath(path);
        ParsingEnvironmentFile* env = new ParsingEnvironmentFile(idxpath);
        env->setLanguage(IndexedString("cmake"));
        topctx=new TopDUContext(idxpath, RangeInRevision(0,0, endl, endc), env);
        DUChain::self()->addDocumentChain(topctx);

        Q_ASSERT(DUChain::self()->chainForDocument(path));
    }
    
    //Clean the re-used top-context. This is problematic since it may affect independent projects, but it's better then letting things accumulate.
    ///@todo This is problematic when the same file is used from within multiple CMakeLists.txts,
    ///      for example a standard import like FindKDE4.cmake, because it creates a cross-dependency
    ///      between the topducontext's of independent projects, like for example kdebase and kdevplatform
    ///@todo Solve that by creating unique versions of all used top-context on a per-project basis using ParsingEnvironmentFile for disambiguation.
    
    topctx->addImportedParentContext(aux);

    /// @todo should we check for NULL or assert?
    if (aux)
      aux->addImportedParentContext(topctx);
    
    return topctx;
}

bool CMakeProjectVisitor::haveToFind(const QString &varName)
{
    if(m_vars->contains(varName+"_FOUND"))
        return false;
    
    m_vars->remove(varName+"-NOTFOUND");
    return true;
}

int CMakeProjectVisitor::visit(const FindProgramAst *fprog)
{
    if(!haveToFind(fprog->variableName()))
        return 1;
    if(m_cache->contains(fprog->variableName()))
    {
        kDebug(9042) << "FindProgram: cache" << fprog->variableName() << m_cache->value(fprog->variableName()).value;
        return 1;
    }

    QStringList modulePath = fprog->path();
#ifdef Q_OS_WIN
    if(!fprog->noSystemEnvironmentPath() && !fprog->noDefaultPath())
        modulePath += envVarDirectories("Path");
    kDebug() << "added Path env for program finding" << envVarDirectories("Path");
#else
    if(!fprog->noSystemEnvironmentPath() && !fprog->noDefaultPath())
        modulePath += envVarDirectories("PATH");
#endif
    kDebug(9042) << "Find:" << fprog->variableName() << fprog->filenames() << "program into" << modulePath<<":"<< fprog->path();
    QString path;
    foreach(const QString& filename, fprog->filenames())
    {
        path=findExecutable(filename, modulePath, fprog->pathSuffixes());
        if(!path.isEmpty())
            break;
    }

    if(!path.isEmpty())
        m_vars->insertGlobal(fprog->variableName(), QStringList(path));
    else
        m_vars->insertGlobal(fprog->variableName()+"-NOTFOUND", QStringList());

    kDebug(9042) << "FindProgram:" << fprog->variableName() << "=" << m_vars->value(fprog->variableName()) << modulePath;
    return 1;
}

QString CMakeProjectVisitor::findExecutable(const QString& file,
                const QStringList& directories, const QStringList& pathSuffixes) const
{
    QString path;
    QStringList suffixes=m_vars->value("CMAKE_EXECUTABLE_SUFFIX");
    suffixes.prepend(QString());
    kDebug() << "finding executable, using suffixes" << suffixes;

    foreach(const QString& suffix, suffixes)
    {
        path=findFile(file+suffix, directories, pathSuffixes);
        if(!path.isEmpty())
            break;
    }
    return path;
}

int CMakeProjectVisitor::visit(const FindPathAst *fpath)
{
    if(!haveToFind(fpath->variableName()))
        return 1;
    if(m_cache->contains(fpath->variableName()))
    {
        kDebug() << "FindPath: cache" << fpath->variableName();
        return 1;
    }

    bool error=false;
    QStringList locationOptions = fpath->path()+fpath->hints();
    QStringList path, files=fpath->filenames();
    QStringList suffixes=fpath->pathSuffixes();

    if(!fpath->noDefaultPath())
    {
        QStringList pp=m_vars->value("CMAKE_PREFIX_PATH");
        foreach(const QString& path, pp) {
            locationOptions += path+"/include";
        }
        locationOptions += pp;
        locationOptions += m_vars->value("CMAKE_INCLUDE_PATH");
        locationOptions += m_vars->value("CMAKE_FRAMEWORK_PATH");
        
        pp=m_vars->value("CMAKE_SYSTEM_PREFIX_PATH");
        foreach(const QString& path, pp) {
            locationOptions += path+"/include";
        }
        locationOptions += m_vars->value("CMAKE_SYSTEM_INCLUDE_PATH");
        locationOptions += m_vars->value("CMAKE_SYSTEM_FRAMEWORK_PATH");
    }

    kDebug(9042) << "Find:" << /*locationOptions << "@" <<*/ fpath->variableName() << /*"=" << files <<*/ " path.";
    foreach(const QString& p, files)
    {
        QString p1=findFile(p, locationOptions, suffixes, true);
        if(p1.isEmpty())
        {
            kDebug(9042) << p << "not found";
            error=true;
        }
        else
        {
            path += p1;
        }
    }

    if(!path.isEmpty())
    {
        m_vars->insertGlobal(fpath->variableName(), QStringList(path));
    }
    else
    {
        kDebug(9042) << "Path not found";
    }
    kDebug(9042) << "Find path: " << fpath->variableName() << m_vars->value(fpath->variableName());
//     m_vars->insert(fpath->variableName()+"-NOTFOUND", QStringList());
    return 1;
}

int CMakeProjectVisitor::visit(const FindLibraryAst *flib)
{
    if(!haveToFind(flib->variableName()))
        return 1;
    if(m_cache->contains(flib->variableName()))
    {
        kDebug(9042) << "FindLibrary: cache" << flib->variableName();
        return 1;
    }

    bool error=false;
    QStringList locationOptions = flib->path()+flib->hints();
    QStringList files=flib->filenames();
    QString path;

    if(!flib->noDefaultPath())
    {

        QStringList opt=m_vars->value("CMAKE_PREFIX_PATH");
        foreach(const QString& s, opt)
            locationOptions.append(s+"/lib");

        locationOptions += m_vars->value("CMAKE_LIBRARY_PATH");
        locationOptions += m_vars->value("CMAKE_FRAMEWORK_PATH");
        
        locationOptions += m_vars->value("CMAKE_SYSTEM_LIBRARY_PATH");
        
        opt=m_vars->value("CMAKE_SYSTEM_PREFIX_PATH");
        foreach(const QString& s, opt)
            locationOptions.append(s+"/lib");
    }
    
    foreach(const QString& p, files)
    {
        foreach(const QString& prefix, m_vars->value("CMAKE_FIND_LIBRARY_PREFIXES"))
        {
            foreach(const QString& suffix, m_vars->value("CMAKE_FIND_LIBRARY_SUFFIXES"))
            {
                QString p1=findFile(prefix+p+suffix, locationOptions, flib->pathSuffixes());
                if(p1.isEmpty())
                {
                    kDebug(9042) << p << "not found";
                    error=true;
                }
                else
                {
                    path = p1;
                    break;
                }
            }
            if(!path.isEmpty())
                break;
        }
        if(!path.isEmpty())
            break;
    }

    if(!path.isEmpty())
    {
        m_vars->insertGlobal(flib->variableName(), QStringList(path));
    }
    else
        kDebug(9032) << "error. Library" << flib->filenames() << "not found";
//     m_vars->insert(fpath->variableName()+"-NOTFOUND", QStringList());
    kDebug(9042) << "Find Library:" << flib->filenames() << m_vars->value(flib->variableName());
    return 1;
}

int CMakeProjectVisitor::visit(const FindFileAst *ffile)
{
    if(!haveToFind(ffile->variableName()))
        return 1;
    if(m_cache->contains(ffile->variableName()))
    {
        kDebug(9042) << "FindFile: cache" << ffile->variableName();
        return 1;
    }

    bool error=false;
    QStringList locationOptions = ffile->path()+ffile->hints();
    if(!ffile->noDefaultPath())
    {
        QStringList pp=m_vars->value("CMAKE_PREFIX_PATH");
        foreach(const QString& path, pp) {
            locationOptions += path+"/include";
        }
        locationOptions += pp;
        locationOptions += m_vars->value("CMAKE_INCLUDE_PATH");
        locationOptions += m_vars->value("CMAKE_FRAMEWORK_PATH");
        
        pp=m_vars->value("CMAKE_SYSTEM_PREFIX_PATH");
        foreach(const QString& path, pp) {
            locationOptions += path+"/include";
        }
        locationOptions += m_vars->value("CMAKE_SYSTEM_INCLUDE_PATH");
        locationOptions += m_vars->value("CMAKE_SYSTEM_FRAMEWORK_PATH");
    }
    
    QStringList path, files=ffile->filenames();

    kDebug(9042) << "Find File:" << ffile->filenames();
    foreach(const QString& p, files)
    {
        QString p1=findFile(p, locationOptions, ffile->pathSuffixes());
        if(p1.isEmpty())
        {
            kDebug(9042) << p << "not found";
            error=true;
        }
        else
        {
            path += p1;
        }
    }

    if(!path.isEmpty())
    {
        m_vars->insertGlobal(ffile->variableName(), QStringList(path));
    }
    else
        kDebug(9032) << "error. File" << ffile->filenames() << "not found";
//     m_vars->insert(fpath->variableName()+"-NOTFOUND", QStringList());
    return 1;
}


int CMakeProjectVisitor::visit(const TryCompileAst *tca)
{
    kDebug(9042) << "try_compile" << tca->resultName() << tca->binDir() << tca->source()
            << "cmakeflags" << tca->cmakeFlags() << "outputvar" << tca->outputName();
    if(m_projectName.isEmpty())
    {
        kDebug(9042) << "file compile" << tca->compileDefinitions() << tca->copyFile();
    }
    else
    {
        kDebug(9042) << "project compile" << tca->projectName() << tca->targetName();
    }
    
    QString value;
    CacheValues::const_iterator it=m_cache->constFind(tca->resultName());
    if(it!=m_cache->constEnd())
        value=it->value;
    else
        value="TRUE";
    
    m_vars->insert(tca->resultName(), QStringList(value));
    return 1;
}


int CMakeProjectVisitor::visit(const TargetLinkLibrariesAst *)
{
    kDebug(9042) << "target_link_libraries";
    return 1;
}

void CMakeProjectVisitor::macroDeclaration(const CMakeFunctionDesc& def, const CMakeFunctionDesc& end, const QStringList& args)
{
    if(def.arguments.isEmpty() || end.arguments.isEmpty())
        return;
    QString id=def.arguments.first().value.toLower();
    
    Identifier identifier(id);
    DUChainWriteLocker lock(DUChain::lock());
    QList<Declaration*> decls=m_topctx->findDeclarations(identifier);
    RangeInRevision sr=def.arguments.first().range();
    RangeInRevision endsr=end.arguments.first().range();
    int idx;
    
    //Only consider declarations in a CMake file
    IndexedString cmakeName("cmake");
    for(QList<Declaration*>::iterator it=decls.begin(); it!=decls.end(); ) {
        if((*it)->topContext()->parsingEnvironmentFile()->language() == cmakeName)
            ++it;
        else
            it = decls.erase(it);
    }
    
    if(!decls.isEmpty())
    {
        idx=m_topctx->indexForUsedDeclaration(decls.first());
        m_topctx->createUse(idx, sr, 0);
    }
    else
    {
        Declaration *d = new Declaration(sr, m_topctx);
        d->setIdentifier( identifier );

        FunctionType* func=new FunctionType();
        foreach(const QString& arg, args)
        {
            DelayedType *delayed=new DelayedType;
            delayed->setIdentifier( IndexedTypeIdentifier(arg) );
            func->addArgument(AbstractType::Ptr(delayed));
        }
        d->setAbstractType( AbstractType::Ptr(func) );
        idx=m_topctx->indexForUsedDeclaration(d);
    }
    m_topctx->createUse(idx, endsr, 0);
}

int CMakeProjectVisitor::visit(const MacroAst *macro)
{
    kDebug(9042) << "Adding macro:" << macro->macroName();
    Macro m;
    m.name = macro->macroName();
    m.knownArgs=macro->knownArgs();
    m.isFunction=false;
    
    return declareFunction(m, macro->content(), macro->line(), "endmacro");
}

int CMakeProjectVisitor::visit(const FunctionAst *func)
{
    kDebug(9042) << "Adding function:" << func->name();
    Macro m;
    m.name = func->name();
    m.knownArgs=func->knownArgs();
    m.isFunction=true;
    
    return declareFunction(m, func->content(), func->line(), "endfunction");
}

int CMakeProjectVisitor::declareFunction(Macro m, const CMakeFileContent& content,
                                         int initial, const QString& end)
{
    CMakeFileContent::const_iterator it=content.constBegin()+initial;
    CMakeFileContent::const_iterator itEnd=content.constEnd();

    int lines=0;
    for(; it!=itEnd; ++it)
    {
        if(it->name.toLower()==end)
            break;
        m.code += *it;
        ++lines;
    }
    ++lines; //We do not want to return to endmacro

    if(it!=itEnd)
    {
        m_macros->insert(m.name, m);

        macroDeclaration(content[initial], content[initial+lines-1], m.knownArgs);
    }
    return lines;
}

int CMakeProjectVisitor::visit(const MacroCallAst *call)
{
    if(m_macros->contains(call->name()))
    {
        const Macro code=m_macros->value(call->name());
        kDebug(9042) << "Running macro:" << call->name() << "params:" << call->arguments() << "=" << code.knownArgs << "for" << code.code.count() << "lines";
        
        if(code.knownArgs.count() > call->arguments().count())
        {
            kDebug(9032) << "error: more parameters needed when calling" << call->name();
        }
        else
        {
            {
                DUChainWriteLocker lock(DUChain::lock());
                QList<Declaration*> decls=m_topctx->findDeclarations(Identifier(call->name().toLower()));

                if(!decls.isEmpty())
                {
                    int idx=m_topctx->indexForUsedDeclaration(decls.first());
                    m_topctx->createUse(idx, call->content()[call->line()].nameRange(), 0);
                }
            }

            //Giving value to parameters
            QStringList::const_iterator mit = code.knownArgs.constBegin();
            QStringList::const_iterator cit = call->arguments().constBegin();
            QStringList argn;
            bool haveArgn=false;
            int i=0;
            while(cit != call->arguments().constEnd())
            {
                m_vars->insertMulti(QString("ARGV%1").arg(i), QStringList(*cit));
                if(mit!=code.knownArgs.constEnd())
                {
                    kDebug(9042) << "param:" << *mit << "=" << *cit;
                    m_vars->insertMulti(*mit, QStringList(*cit));
                    mit++;
                }
                else
                {
                    haveArgn=true;
                    argn += *cit;
                }
                cit++;
                i++;
            }
            m_vars->insertMulti("ARGN", argn);
            m_vars->insertMulti("ARGV", call->arguments());
            m_vars->insertMulti("ARGC", QStringList(QString::number(call->arguments().count())));
            kDebug(9042) << "argn=" << m_vars->value("ARGN");

            bool isfunc = code.isFunction;
            if(isfunc)
                m_vars->pushScope();
            //Executing
            int len = walk(code.code, 1);
            kDebug(9042) << "visited!" << call->name()  <<
                m_vars->value("ARGV") << "_" << m_vars->value("ARGN") << "..." << len;

            if(isfunc)
                m_vars->popScope();
            //Restoring
            i=1;
            foreach(const QString& name, code.knownArgs)
            {
                m_vars->take(QString("ARGV%1").arg(i));
                m_vars->take(name);
                i++;
            }

            m_vars->take("ARGV");
            m_vars->take("ARGC");
            m_vars->take("ARGN");

        }
    }
    else
    {
        kDebug(9032) << "error: Did not find the macro:" << call->name() << call->content()[call->line()].writeBack();
    }
    
    return 1;
}

void usesForArguments(const QStringList& names, const QList<int>& args, const ReferencedTopDUContext& topctx, const CMakeFunctionDesc& func)
{
    //TODO: Should not return here
    if(args.size()!=names.size())
        return;

    //We define the uses for the used variable without ${}
    foreach(int use, args)
    {
        DUChainWriteLocker lock(DUChain::lock());
        QString var=names[use];
        QList<Declaration*> decls=topctx->findDeclarations(Identifier(var));

        if(!decls.isEmpty() && func.arguments.count() > use)
        {
            CMakeFunctionArgument arg=func.arguments[use];
            int idx=topctx->indexForUsedDeclaration(decls.first());
            topctx->createUse(idx, RangeInRevision(arg.line-1, arg.column-1, arg.line-1, arg.column-1+var.size()), 0);
        }
    }
}

int CMakeProjectVisitor::visit(const IfAst *ifast)  //Highly crappy code
{
    int lines=ifast->line();
    if( ifast->condition().isEmpty() )
    {
        const CMakeFunctionDesc d = ifast->content().at( ifast->line() );
        kWarning() << "Parser couldn't parse condition of an IF in file:" << ifast->condition() << d.filePath << d.line;
    }

    int inside=0;
    bool visited=false;
    QList<int> ini;
    for(; lines < ifast->content().size(); ++lines)
    {
        const CMakeFunctionDesc funcDesc = ifast->content().at(lines);
        QString funcName=funcDesc.name;
//         kDebug(9032) << "looking @" << lines << it->writeBack() << ">>" << inside << visited;
        if(funcName=="if")
        {
            inside++;
        }
        else if(funcName=="endif")
        {
            inside--; 
            if(inside<=0) {
//                 Q_ASSERT(!ini.isEmpty());
                if(!funcDesc.arguments.isEmpty())
                    usesForArguments(ifast->condition(), ini, m_topctx, funcDesc);
                break;
            }
//                 kDebug(9042) << "found an endif at:" << lines << "but" << inside;
        }

        if(inside==1)
        {
            bool result = false;

            if(funcName=="if" || funcName=="elseif")
            {
                CMakeCondition cond(this);
                IfAst myIf;
                QStringList condition;

                if(funcName=="if")
                {
                    condition=ifast->condition();
                }
                else
                {
                    if(!myIf.parseFunctionInfo(resolveVariables(funcDesc)))
                        kDebug(9042) << "uncorrect condition correct" << funcDesc.writeBack();
                    condition=myIf.condition();
                }
                result=cond.condition(condition);
                if(funcName=="if")
                    ini=cond.variableArguments();

                usesForArguments(condition, cond.variableArguments(), m_topctx, funcDesc);
                kDebug(9042) << ">> " << funcName << condition << result;
            }
            else if(funcName=="else")
            {
                kDebug(9042) << ">> else";
                result=true;
                usesForArguments(ifast->condition(), ini, m_topctx, funcDesc);
            }

            if(!visited && result)
            {
                kDebug(9042) << "About to visit " << funcName << "?" << result;
                lines = walk(ifast->content(), lines+1)-1;
                visited=true;
//                 kDebug(9042) << "Visited. now in" << it->name;
            }
        }
    }

    if(lines >= ifast->content().size())
    {
        kDebug() << "error. found an unfinished endif";
        return ifast->content().size()-ifast->line();
    }
    else
    {
//     kDebug() << "finish" << "<>" << ifast->condition() << '|' << lines-ifast->line() << " to " << lines << '<' << ifast->content().size();
//     kDebug(9042) << "endif==" << ifast->content()[lines].writeBack();
        return lines-ifast->line()+1;
    }
}

int CMakeProjectVisitor::visit(const ExecProgramAst *exec)
{
    QString execName = exec->executableName();
    QStringList argsTemp = exec->arguments();
    QStringList args;

    foreach(const QString& arg, argsTemp)
    {
        args += arg.split(' ');
    }
    kDebug(9042) << "Executing:" << execName << "::" << args << "in" << exec->workingDirectory();

    KProcess p;
    if(!exec->workingDirectory().isEmpty())
        p.setWorkingDirectory(exec->workingDirectory());
    p.setOutputChannelMode(KProcess::MergedChannels);
    p.setProgram(execName, args);
    p.start();

    if(!p.waitForFinished())
    {
        kDebug(9032) << "error: failed to execute:" << execName << "error:" << p.error() << p.exitCode();
    }

    if(!exec->returnValue().isEmpty())
    {
        kDebug(9042) << "execution returned: " << exec->returnValue() << " = " << p.exitCode();
        m_vars->insert(exec->returnValue(), QStringList(QString::number(p.exitCode())));
    }

    if(!exec->outputVariable().isEmpty())
    {
        QByteArray b = p.readAllStandardOutput();
        QString t;
        t.prepend(b.trimmed());
        m_vars->insert(exec->outputVariable(), QStringList(t.trimmed()));
        kDebug(9042) << "executed" << execName << "<" << t;
    }
    return 1;
}

int CMakeProjectVisitor::visit(const ExecuteProcessAst *exec)
{
    kDebug(9042) << "executing... " << exec->commands();
    QList<KProcess*> procs;
    foreach(const QStringList& _args, exec->commands())
    {
        if (_args.isEmpty())
        {
            kDebug(9032) << "Error: trying to execute empty command";
            break;
        }
        QStringList args(_args);
        KProcess *p=new KProcess(), *prev=0;
        if(!procs.isEmpty())
        {
            prev=procs.last();
        }
        p->setWorkingDirectory(exec->workingDirectory());
        p->setOutputChannelMode(KProcess::MergedChannels);
        QString execName=args.takeFirst();
        p->setProgram(execName, args);
        p->start();
        procs.append(p);
        kDebug(9042) << "Executing:" << execName << "::" << args /*<< "into" << *m_vars*/;

        if(prev)
        {
            prev->setStandardOutputProcess(p);
        }
    }

    foreach(KProcess* p, procs)
    {
        if(!p->waitForFinished())
        {
            kDebug(9042) << "error: failed to execute:" << p;
        }
    }
    
    if(!procs.isEmpty() && !exec->resultVariable().isEmpty())
    {
        kDebug(9042) << "execution returned: " << exec->resultVariable() << " = " << procs.last()->exitCode();
        m_vars->insert(exec->resultVariable(), QStringList(QString::number(procs.last()->exitCode())));
    }

    //FIXME: remove condition when filtering bad output
    if(!procs.isEmpty() && !exec->outputVariable().isEmpty())
    {
        QByteArray b = procs.last()->readAllStandardOutput();
        QString t;
        t.prepend(b.trimmed());
        m_vars->insert(exec->outputVariable(), QStringList(t.trimmed().replace("\\", "\\\\")));
        kDebug(9042) << "executed " << exec->outputVariable() << "=" << t;
    }
    qDeleteAll(procs);
    return 1;
}


int CMakeProjectVisitor::visit(const FileAst *file)
{
    Q_ASSERT(m_vars->contains("CMAKE_CURRENT_SOURCE_DIR"));
    switch(file->type()) //TODO
    {
        case FileAst::Write:
            kDebug(9042) << "(ni) File write: " << file->path() << file->message();
            break;
        case FileAst::Append:
            kDebug(9042) << "(ni) File append: " << file->path() << file->message();
            break;
        case FileAst::Read:
        {
            KUrl filename=file->path();
            QFileInfo ifile(filename.toLocalFile());
            kDebug(9042) << "FileAst: reading " << file->path() << ifile.isFile();
            if(!ifile.isFile())
                return 1;
            QFile f(filename.toLocalFile());
            if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
                return 1;
            QString output=f.readAll();
            m_vars->insert(file->variable(), QStringList(output));
            kDebug(9042) << "FileAst: read ";
        }
            break;
        case FileAst::Glob:
        case FileAst::GlobRecurse: {
            QStringList matches;
            foreach(QString expr, file->globbingExpressions())
            {
                if (expr.isEmpty())
                    continue;
                QString pathPrefix;
                if (QDir::isRelativePath(expr) && pathPrefix.isEmpty())
                    pathPrefix = m_vars->value("CMAKE_CURRENT_SOURCE_DIR").first();
                
                matches.append(traverseGlob(pathPrefix, expr, file->type() == FileAst::GlobRecurse, file->isFollowingSymlinks()));
            }
            
            if (!file->path().isEmpty())
            {
                // RELATIVE was specified, so we need to make all paths relative to file->path()
                QDir relative(file->path());
                QStringList::iterator endIt = matches.end();
                for(QStringList::iterator it = matches.begin(); it != endIt; ++it)
                {
                    *it = relative.relativeFilePath(*it);
                }
            }
            m_vars->insert(file->variable(), matches);
            
            kDebug(9042) << "glob. recurse:" << (file->type() == FileAst::GlobRecurse)
                         << "RELATIVE: " << file->path()
                         << "FOLLOW_SYMLINKS: " << file->isFollowingSymlinks()
                         << ", " << file->globbingExpressions() << ": " << matches;
        }
            break;
        case FileAst::Remove:
        case FileAst::RemoveRecurse:
            kDebug(9042) << "warning. file-remove or remove_recurse. KDevelop won't remove anything.";
            break;
        case FileAst::MakeDirectory:
            kDebug(9042) << "warning. file-make_directory. KDevelop won't create anything.";
            break;
        case FileAst::RelativePath:
            m_vars->insert(file->variable(), QStringList(KUrl::relativePath(file->directory(), file->path())));
            kDebug(9042) << "file relative_path" << file->directory() << file->path();
            break;
        case FileAst::ToCmakePath:
#ifdef Q_OS_WIN
            m_vars->insert(file->variable(), file->path().replace("\\", "/").split(';'));
#else
            m_vars->insert(file->variable(), file->path().split(':'));
#endif
            kDebug(9042) << "file TO_CMAKE_PATH variable:" << file->variable() << "="
                    << m_vars->value(file->variable()) << "path:" << file->path();
            break;
        case FileAst::ToNativePath:
            m_vars->insert(file->variable(), QStringList(file->path().replace('/', QDir::separator())));
            kDebug(9042) << "file TO_NATIVE_PATH variable:" << file->variable() << "="
                    << m_vars->value(file->variable()) << "path:" << file->path();
            break;
        case FileAst::Strings: {
            KUrl filename=file->path();
            QFileInfo ifile(filename.toLocalFile());
            kDebug(9042) << "FileAst: reading " << file->path() << ifile.isFile();
            if(!ifile.isFile())
                return 1;
            QFile f(filename.toLocalFile());
            if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
                return 1;
            QStringList output=QString(f.readAll()).split('\n');
            
            if(!file->regex().isEmpty()) {
                QRegExp rx(file->regex());
                for(QStringList::iterator it=output.begin(); it!=output.end(); ) {
                    if(rx.indexIn(*it)>=0)
                        ++it;
                    else
                        it = output.erase(it);
                }
            }
            
            m_vars->insert(file->variable(), output);
        }   break;
        default:
            kDebug(9032) << "error: not implemented. file:" << file->type() <<
                "variable:" << file->variable() << "file:" << file->path() << file->content()[file->line()].arguments[0].value;
            break;
    }
    return 1;
}

int CMakeProjectVisitor::visit(const MessageAst *msg)
{
    s_msgcallback(msg->message().join(QString()));
    return 1;
}

int CMakeProjectVisitor::visit(const MathAst *math)
{
    QScriptEngine eng;
    QScriptValue result = eng.evaluate(math->expression());

    if (result.isError())
    {
        kDebug(9032) << "error: found an error while calculating" << math->expression();
    }
    kDebug(9042) << "math. " << math->expression() << "=" << result.toInteger();
    m_vars->insert(math->outputVariable(), QStringList(QString::number(result.toInteger())));
    return 1;
}

int CMakeProjectVisitor::visit(const GetFilenameComponentAst *filecomp)
{
    Q_ASSERT(m_vars->contains("CMAKE_CURRENT_SOURCE_DIR"));

    QDir dir=m_vars->value("CMAKE_CURRENT_SOURCE_DIR").first();
    QFileInfo fi(dir, filecomp->fileName());

    QString val;
    switch(filecomp->type())
    {
        case GetFilenameComponentAst::Path:
            val=fi.path();
            break;
        case GetFilenameComponentAst::Absolute:
            val=fi.absoluteFilePath();
            break;
        case GetFilenameComponentAst::Name:
            val=fi.fileName();
            break;
        case GetFilenameComponentAst::Ext:
            val=fi.suffix();
            break;
        case GetFilenameComponentAst::NameWe:
            val=fi.baseName();
            break;
        case GetFilenameComponentAst::Program:
            kDebug(9042) << "error: filenamecopmonent PROGRAM not implemented"; //TODO: <<
            break;
    }
    m_vars->insert(filecomp->variableName(), QStringList(val));
    kDebug(9042) << "filename component" << filecomp->variableName() << "= "
            << filecomp->fileName() << "=" << val << endl;
    return 1;
}

int CMakeProjectVisitor::visit(const GetSourceFilePropAst* prop)
{
    kDebug(9042) << "not supported yet :::" << prop->variableName();
    m_vars->insert(prop->variableName(), QStringList());
    return 1;
}

int CMakeProjectVisitor::visit(const OptionAst *opt)
{
    kDebug(9042) << "option" << opt->variableName() << "-" << opt->description();
    if(!m_vars->contains(opt->variableName()) && !m_cache->contains(opt->variableName()))
    {
        m_vars->insert(opt->variableName(), QStringList(opt->defaultValue()));
    }
    return 1;
}

int CMakeProjectVisitor::visit(const ListAst *list)
{
    QString output = list->output();
    
    QStringList theList = m_vars->value(list->list());
    switch(list->type())
    {
        case ListAst::Length:
            m_vars->insert(output, QStringList(QString::number(theList.count())));
            kDebug(9042) << "List length" << m_vars->value(output);
            break;
        case ListAst::Get: {
            bool contains = m_vars->contains(list->list());
            QStringList indices;
            if(contains) {
                foreach(int idx, list->index())
                {
                    if(idx>=theList.count() || (-idx)>theList.count())
                        kDebug(9032) << "error! trying to GET an element that doesn't exist!" << idx;
                    else if(idx>=0)
                        indices += theList[idx];
                    else
                        indices += theList[theList.size()+idx];
                }
            } else
                indices += "NOTFOUND";
            m_vars->insert(output, indices);
            kDebug(9042) << "List: Get" << list->list() << theList << list->output() << list->index();
        }   break;
        case ListAst::Append:
            theList += list->elements();
            m_vars->insert(list->list(), theList);
            break;
        case ListAst::Find: {
            int idx=theList.indexOf(list->elements().first());
            
            m_vars->insert(list->output(), QStringList(QString::number(idx)));
            kDebug(9042) << "List: Find" << theList << list->output() << list->elements() << idx;
        }   break;
        case ListAst::Insert: {
            int p=list->index().first();
            foreach(const QString& elem, list->elements())
            {
                theList.insert(p >=0 ? p : (theList.size()+p), elem);
                p += p>=0? 1 : 0;
            }
            m_vars->insert(list->list(), theList);
        }   break;
        case ListAst::RemoveItem:
            kDebug(9042) << "list remove item: " << theList << list->elements();
            foreach(const QString& elem, list->elements())
            {
                theList.removeAll(elem);
            }

            m_vars->insert(list->list(), theList);
            break;
        case ListAst::RemoveAt: {
            QList<int> indices=list->index();
            qSort(indices);
            QList<int>::const_iterator it=indices.constEnd();
            kDebug(9042) << "list remove: " << theList << indices;
            do
            {
                --it;
                theList.removeAt(*it >= 0 ? *it : theList.size()+*it);
            } while(it!=indices.constBegin());
            m_vars->insert(list->list(), theList);
        }   break;
        case ListAst::Sort:
            qSort(theList);
            m_vars->insert(list->list(), theList);
            break;
        case ListAst::Reverse: {
            QStringList reversed;
            foreach(const QString& elem, theList)
                reversed.prepend(elem);
            m_vars->insert(list->list(), reversed);
            }
            break;
        case ListAst::RemoveDuplicates: {
            QStringList noduplicates;
            foreach(const QString& elem, theList) {
                if(!noduplicates.contains(elem))
                    noduplicates.append(elem);
            }
            m_vars->insert(list->list(), noduplicates);
        }   break;
    }
    kDebug(9042) << "List!!" << list->output() << '='<< m_vars->value(list->output()) << " -> " << m_vars->value(list->list());
    return 1;
}

int toCommandEnd(const CMakeAst* fea)
{
    QString command = fea->content()[fea->line()].name;
    QString endCommand = "end"+command;
    int lines=fea->line()+1, depth=1;
    CMakeFileContent::const_iterator it=fea->content().constBegin()+lines;
    CMakeFileContent::const_iterator itEnd=fea->content().constEnd();
    for(; depth>0 && it!=itEnd; ++it, lines++)
    {
        if(it->name==command)
        {
            depth++;
        }
        else if(it->name==endCommand)
        {
            depth--;
        }
    }
    return lines;
}

int CMakeProjectVisitor::visit(const ForeachAst *fea)
{
    kDebug(9042) << "foreach>" << fea->loopVar() << "=" << fea->arguments() << "range=" << fea->type();
    int end = -1;
    switch(fea->type()) {
        case ForeachAst::Range:
            for( int i = fea->ranges().start; i < fea->ranges().stop && !m_hitBreak; i += fea->ranges().step )
            {
                m_vars->insertMulti(fea->loopVar(), QStringList(QString::number(i)));
                end=walk(fea->content(), fea->line()+1);
                m_vars->remove(fea->loopVar());
                if(m_hitBreak)
                    break;
            }
        break;
        case ForeachAst::InItems: {
            QStringList args=fea->arguments();
            foreach(const QString& s, args)
            {
                m_vars->insert(fea->loopVar(), QStringList(s));
                kDebug(9042) << "looping" << fea->loopVar() << "=" << m_vars->value(fea->loopVar());
                end=walk(fea->content(), fea->line()+1);
                if(m_hitBreak)
                    break;
            }
        } break;
        case ForeachAst::InLists: {
            QStringList args=fea->arguments();
            foreach(const QString& curr, args) {
                QStringList list = m_vars->value(curr);
                foreach(const QString& s, list)
                {
                    m_vars->insert(fea->loopVar(), QStringList(s));
                    kDebug(9042) << "looping" << fea->loopVar() << "=" << m_vars->value(fea->loopVar());
                    end=walk(fea->content(), fea->line()+1);
                    if(m_hitBreak)
                        break;
                }
            }
        }   break;
    }
    
    if(end<0)
        end = toCommandEnd(fea);
    else
        end++;
    
    m_hitBreak=false;
    kDebug(9042) << "EndForeach" << fea->loopVar();
    return end-fea->line();
}

int CMakeProjectVisitor::visit(const StringAst *sast)
{
    kDebug(9042) << "String to" /*<< sast->input()*/ << sast->outputVariable();
    switch(sast->type())
    {
        case StringAst::Regex:
        {
            QStringList res;
            QRegExp rx(sast->regex());
            rx.setPatternSyntax(QRegExp::RegExp2);
            QString totalInput = sast->input().join(QString());
            switch(sast->cmdType())
            {
                case StringAst::Match:
                {
                    int match=rx.indexIn(totalInput);
                    if(match>=0) {
                        res = QStringList(totalInput.mid(match, rx.matchedLength()));
                        break;
                    }
                    break;
                }
                case StringAst::MatchAll:
                {
                    int pos = 0;
                    while( (pos = rx.indexIn( totalInput, pos ) ) != -1 )
                    {
                        res << rx.cap();
                        pos += rx.matchedLength();
                    }
                    break;
                }
                case StringAst::RegexReplace:
                {
                    foreach(const QString& in, sast->input())
                    {
                        // QString() is required to get rid of the const
                        res.append(QString(in).replace(rx, sast->replace()));
                    }
                }
                    break;
                default:
                    kDebug(9032) << "ERROR String: Not a regex. " << sast->cmdType();
                    break;
            }
            for(int i=1; i<rx.captureCount()+1 && i<10; i++) {
                m_vars->insert(QString("CMAKE_MATCH_%1").arg(i), QStringList(rx.cap(i)));
            }
            kDebug() << "regex" << sast->outputVariable() << "=" << sast->regex() << res;
            m_vars->insert(sast->outputVariable(), res);
        }
            break;
        case StringAst::Replace: {
            QStringList out;
            foreach(const QString& _in, sast->input())
            {
                QString in(_in);
                QString aux=in.replace(sast->regex(), sast->replace());
                out += aux.split(';'); //FIXME: HUGE ugly hack
            }
            kDebug(9042) << "string REPLACE" << sast->input() << "=>" << out;
            m_vars->insert(sast->outputVariable(), out);
        }   break;
        case StringAst::Compare:
        {
            QString res;
            switch(sast->cmdType()){
                case StringAst::Equal:
                case StringAst::NotEqual:
                    if(sast->input()[0]==sast->input()[1] && sast->cmdType()==StringAst::Equal)
                        res = "TRUE";
                    else
                        res = "FALSE";
                    break;
                case StringAst::Less:
                case StringAst::Greater:
                    if(sast->input()[0]<sast->input()[1] && sast->cmdType()==StringAst::Less)
                        res = "TRUE";
                    else
                        res = "FALSE";
                    break;
                default:
                    kDebug(9042) << "String: Not a compare. " << sast->cmdType();
            }
            m_vars->insert(sast->outputVariable(), QStringList(res));
        }
            break;
        case StringAst::Ascii: {
            QString res;
            foreach(const QString& ascii, sast->input())
            {
                bool ok;
                res += QChar(ascii.toInt(&ok, 10));
            }

            m_vars->insert(sast->outputVariable(), QStringList(res));
        }   break;
        case StringAst::Configure:
            //This is not up to the cmake support
            kDebug(9032) << "warning! String configure is not supported!" << sast->content()[sast->line()].writeBack();
            break;
        case StringAst::ToUpper:
            m_vars->insert(sast->outputVariable(), QStringList(sast->input()[0].toUpper()));
            break;
        case StringAst::ToLower:
            m_vars->insert(sast->outputVariable(), QStringList(sast->input()[0].toLower()));
            break;
        case StringAst::Length:
            m_vars->insert(sast->outputVariable(), QStringList(QString::number(sast->input()[0].count())));
            break;
        case StringAst::Substring:
        {
            QString res=sast->input()[0];
            res=res.mid(sast->begin(), sast->length());
            m_vars->insert(sast->outputVariable(), QStringList(res));
        }   break;
        case StringAst::Strip:
            m_vars->insert(sast->outputVariable(), QStringList(CMakeFunctionArgument::unescapeValue( sast->string() )));
            break;
        case StringAst::Random: {
            QString alphabet=sast->string(), result;
            for(int i=0; i<sast->length(); i++)
            {
                int randv=qrand() % alphabet.size();
                result += alphabet[randv];
            }
            m_vars->insert(sast->outputVariable(), QStringList(result));
        }   break;
    }
    kDebug(9042) << "String " << m_vars->value(sast->outputVariable());
    return 1;
}


int CMakeProjectVisitor::visit(const GetCMakePropertyAst *past)
{
    QStringList output;
    switch(past->type())
    {
        case GetCMakePropertyAst::Variables:
            kDebug(9042) << "get cmake prop: variables:" << m_vars->size();
            output = m_vars->keys();
            break;
        case GetCMakePropertyAst::CacheVariables:
            output = m_cache->keys();
            break;
        case GetCMakePropertyAst::Commands:      //FIXME: We do not have commands yet
            output = QStringList();
            break;
        case GetCMakePropertyAst::Macros:
            output = m_macros->keys();
            break;
    }
    m_vars->insert(past->variableName(), output);
    return 1;
}

int CMakeProjectVisitor::visit(const CustomCommandAst *ccast)
{
    kDebug(9042) << "CustomCommand" << ccast->outputs();
    if(ccast->isForTarget())
    {
        //TODO: implement me
    }
    else
    {
        foreach(const QString& out, ccast->outputs())
        {
            m_generatedFiles[out] = QStringList(ccast->mainDependency())/*+ccast->otherDependencies()*/;
            kDebug(9042) << "Have to generate:" << out << "with" << m_generatedFiles[out];
        }
    }
    return 1;
}

int CMakeProjectVisitor::visit(const CustomTargetAst *ctar)
{
    kDebug(9042) << "custom_target " << ctar->target() << ctar->dependencies() << ", " << ctar->commandArgs();
    kDebug(9042) << ctar->content()[ctar->line()].writeBack();

    defineTarget(ctar->target(), ctar->dependencies(), Target::Custom);
    return 1;
}

QPair<QString, QString> definition(const QString& param)
{
    QPair<QString, QString> ret;
    if(!param.startsWith("-D"))
        return ret;
    int eq=param.indexOf('=', 2);
    ret.first=param.mid(2, eq-2);
    if(eq>0)
        ret.second=param.mid(eq+1);
    return ret;
}

int CMakeProjectVisitor::visit(const AddDefinitionsAst *addDef)
{
//     kDebug(9042) << "Adding defs: " << addDef->definitions();
    foreach(const QString& def, addDef->definitions())
    {
        if(def.isEmpty())
            continue;
        QPair<QString, QString> definePair=definition(def);
        if(definePair.first.isEmpty())
            kDebug(9042) << "error: definition not matched" << def;

        m_defs[definePair.first]=definePair.second;
        kDebug(9042) << "added definition" << definePair.first << "=" << definePair.second << " from " << def;
    }
    return 1;
}

int CMakeProjectVisitor::visit(const RemoveDefinitionsAst *remDef)
{
    foreach(const QString& def, remDef->definitions())
    {
        if(def.isEmpty())
            continue;
        QPair<QString, QString> definePair=definition(def);
        if(definePair.first.isEmpty())
            kDebug(9042) << "error: definition not matched" << def;

        m_defs.remove(definePair.first);
        kDebug(9042) << "removed definition" << definePair.first << " from " << def;
    }
    return 1;
}

int CMakeProjectVisitor::visit(const MarkAsAdvancedAst *maa)
{
    kDebug(9042) << "Mark As Advanced" << maa->advancedVars();
    return 1;
}

/// @todo Add support for platform-specific argument splitting
/// (UNIX_COMMAND and WINDOWS_COMMAND) introduced in CMake 2.8.
int CMakeProjectVisitor::visit( const SeparateArgumentsAst * separgs )
{
    QString varName=separgs->variableName();
    QStringList res;
    foreach(const QString& value, m_vars->value(varName))
    {
        res += value.split(' ');
    }
    m_vars->insert(varName, res);
    return 1;
}

int CMakeProjectVisitor::visit(const SetPropertyAst* setp)
{
    kDebug() << "setprops" << setp->type() << setp->name() << setp->values();
    if(setp->type()==GlobalProperty)
        m_props[GlobalProperty][QString()][setp->name()]=setp->values();
    else
    {
        CategoryType& cm=m_props[setp->type()];
        if(setp->append()) {
            foreach(const QString &it, setp->args()) {
                cm[it][setp->name()].append(setp->values());
            }
        } else {
            foreach(const QString &it, setp->args())
                cm[it].insert(setp->name(), setp->values());
        }
    }
    return 1;
}

int CMakeProjectVisitor::visit(const GetPropertyAst* getp)
{
    kDebug() << "getprops";
    QStringList retv;
    QString catn;
    if(getp->type()!=GlobalProperty)
    {
        catn=getp->typeName();
    }
    retv=m_props[getp->type()][catn][getp->name()];
    m_vars->insert(getp->outputVariable(), retv);
    return 1;
}

int CMakeProjectVisitor::visit(const GetDirPropertyAst* getdp)
{
    kDebug() << "getprops";
    QStringList retv;
    QString dir=getdp->directory();
    if(dir.isEmpty()) {
        dir=m_vars->value("CMAKE_CURRENT_SOURCE_DIR").join(QString());
    } else if(KUrl::isRelativeUrl(dir)) {
        KUrl u(m_vars->value("CMAKE_CURRENT_SOURCE_DIR").join(QString()));
        u.addPath(dir);
        dir=u.path();
    }
    
    retv=m_props[DirectoryProperty][dir][getdp->propName()];
    m_vars->insert(getdp->outputVariable(), retv);
    
    return 1;
}

int CMakeProjectVisitor::visit( const WhileAst * whileast)
{
    CMakeCondition cond(this);
    bool result=cond.condition(whileast->condition());
    usesForArguments(whileast->condition(), cond.variableArguments(), m_topctx, whileast->content()[whileast->line()]);

    kDebug(9042) << "Visiting While" << whileast->condition() << "?" << result;
    int end = toCommandEnd(whileast);

    if(end<whileast->content().size())
    {
        usesForArguments(whileast->condition(), cond.variableArguments(), m_topctx, whileast->content()[end]);
        
        if(result)
        {
            walk(whileast->content(), whileast->line()+1);
            
            if(m_hitBreak) {
                kDebug() << "break found. leaving loop";
                m_hitBreak=false;
            } else
                walk(whileast->content(), whileast->line());
        }
    }
    
    kDebug(9042) << "endwhile" << whileast->condition() /*<< whileast->content()[end]*/;
    
    return end-whileast->line();
}

CMakeFunctionDesc CMakeProjectVisitor::resolveVariables(const CMakeFunctionDesc & exp)
{
    CMakeFunctionDesc ret=exp;
    ret.arguments.clear();

    foreach(const CMakeFunctionArgument &arg, exp.arguments)
    {
        if(arg.value.contains('$'))
            ret.addArguments(resolveVariable(arg), arg.quoted);
        else
            ret.arguments.append(arg);
    }

    return ret;
}

enum RecursivityType { No, Yes, End, Break };

RecursivityType recursivity(const QString& functionName)
{
    QString upperFunctioName=functionName;
    if(upperFunctioName=="if" || upperFunctioName=="while" ||
       upperFunctioName=="foreach" || upperFunctioName=="macro")
        return Yes;
    else if(upperFunctioName=="else" || upperFunctioName=="elseif" || upperFunctioName.startsWith("end"))
        return End;
    else if(upperFunctioName=="break")
        return Break;
    return No;
}

int CMakeProjectVisitor::walk(const CMakeFileContent & fc, int line, bool isClean)
{
    if(fc.isEmpty())
        return 0;
    
    ReferencedTopDUContext aux=m_topctx;
    KUrl url(fc[0].filePath);
    
    if(!m_topctx || m_topctx->url().toUrl()!=url)
    {
        kDebug(9042) << "Creating a context for" << url;
        m_topctx=createContext(url, aux ? aux : m_parentCtx, fc.last().endLine-1, fc.last().endColumn-1, isClean);
        if(!aux)
            aux=m_topctx;
    }
    VisitorState p;
    p.code = &fc;
    p.context = m_topctx;
    p.line = line;

    m_backtrace.push(p);

    CMakeFileContent::const_iterator it=fc.constBegin()+line, itEnd=fc.constEnd();
    for(; it!=itEnd; )
    {
        Q_ASSERT( line<fc.count() );
        Q_ASSERT( line>=0 );
//         kDebug(9042) << "@" << line;

        Q_ASSERT( *it == fc[line] );
//         kDebug(9042) << "At line" << line << "/" << fc.count();

        RecursivityType r = recursivity(it->name);
        if(r==End || r==Break || m_hitBreak)
        {
//             kDebug(9042) << "Found an end." << func.writeBack();
            m_backtrace.pop();
            m_topctx=aux;
            
            if(r==Break)
                m_hitBreak=true;
            return line;
        }
        
        CMakeAst* element = AstFactory::self()->createAst(it->name);

        if(!element)
            element = new MacroCallAst;

        createUses(*it);
//         kDebug(9042) << "resolving:" << it->writeBack();
            
        CMakeFunctionDesc func = resolveVariables(*it); //FIXME not correct in while case
        bool correct = element->parseFunctionInfo(func);
//         kDebug(9042) << "resolved:" << func.writeBack() << correct;
        if(!correct)
        {
            kDebug(9042) << "error! found an error while processing" << func.writeBack() << "was" << it->writeBack() << endl
                << " at" << func.filePath << ":" << func.line << endl;
            //FIXME: Should avoid to run?
        }
        
        if(element->isDeprecated()) {
            kDebug(9032) << "Warning: Using the function: " << func.name << " which is deprecated by cmake.";
            DUChainWriteLocker lock(DUChain::lock());
            KSharedPtr<Problem> p(new Problem);
            p->setDescription(i18n("%1 is a deprecated command and should not be used", func.name));
            p->setRange(it->nameRange());
            p->setFinalLocation(DocumentRange(IndexedString(url), KDevelop::RangeInRevision(it->nameRange().start, it->nameRange().end).castToSimpleRange()));
            m_topctx->addProblem(p);
        }
        element->setContent(fc, line);

        createDefinitions(element);

        m_vars->insertGlobal("CMAKE_CURRENT_LIST_LINE", QStringList(QString::number(it->line)));
        int lines=element->accept(this);
        line+=lines;
        m_backtrace.top().line = line;
        m_backtrace.top().context = m_topctx;
        delete element;
        
        if(line>fc.count()) {
            KSharedPtr<Problem> p(new Problem);
            p->setDescription(i18n("Unfinished function. "));
            p->setRange(it->nameRange());
            p->setFinalLocation(DocumentRange(IndexedString(url), KDevelop::RangeInRevision(fc.first().range().start, fc.last().range().end).castToSimpleRange()));
            
            DUChainWriteLocker lock(DUChain::lock());
            m_topctx->addProblem(p);
            break;
        }
        
        it+=lines;
    }
    m_backtrace.pop();
    m_topctx=aux;
    kDebug(9042) << "Walk stopped @" << line;
    return line;
}

void CMakeProjectVisitor::createDefinitions(const CMakeAst *ast)
{
    if(!m_topctx)
        return;
    DUChainWriteLocker lock(DUChain::lock());
    foreach(const CMakeFunctionArgument &arg, ast->outputArguments())
    {
        if(!arg.isCorrect())
            continue;
        Identifier id(arg.value);
        
        QList<Declaration*> decls=m_topctx->findDeclarations(id);
        if(decls.isEmpty())
        {
            Declaration *d = new Declaration(arg.range(), m_topctx);
            d->setIdentifier(id);
        }
        else
        {
            int idx=m_topctx->indexForUsedDeclaration(decls.first());
            m_topctx->createUse(idx, arg.range(), 0);
        }
    }
}

void CMakeProjectVisitor::createUses(const CMakeFunctionDesc& desc)
{
    if(!m_topctx)
        return;
    DUChainWriteLocker lock(DUChain::lock());
    foreach(const CMakeFunctionArgument &arg, desc.arguments)
    {
        if(!arg.isCorrect() || !arg.value.contains('$'))
            continue;

        QList<IntPair> var = parseArgument(arg.value);
        QList<IntPair>::const_iterator it, itEnd=var.constEnd();
        for(it=var.constBegin(); it!=itEnd; ++it)
        {
            QString var=arg.value.mid(it->first+1, it->second-it->first-1);
            QList<Declaration*> decls=m_topctx->findDeclarations(Identifier(var));
            
            if(!decls.isEmpty())
            {
                int idx=m_topctx->indexForUsedDeclaration(decls.first());
                m_topctx->createUse(idx, RangeInRevision(arg.line-1, arg.column+it->first, arg.line-1, arg.column+it->second-1), 0);
            }
        }
    }
}

void CMakeProjectVisitor::setCacheValues( CacheValues* cache)
{
    m_cache=cache;
}

void CMakeProjectVisitor::setVariableMap(VariableMap * vars)
{
    m_vars=vars;
}

bool isGenerated(const QString& name)
{
    return name.indexOf("#[")>=0;
}

QStringList CMakeProjectVisitor::dependees(const QString& s) const
{
    QStringList ret;
    if(isGenerated(s))
    {
        foreach(const QString& f, m_generatedFiles[s])
            ret += dependees(f);
    }
    else
    {
        ret += s;
    }
    return ret;
}

QStringList CMakeProjectVisitor::resolveDependencies(const QStringList & files) const
{
    QStringList ret;
    foreach(const QString& s, files)
    {
        if(isGenerated(s))
        {
            kDebug(9042) << "Generated:" << s;
            QStringList gen = dependees(s);
            
            foreach(const QString& file, gen)
            {
                if(!ret.contains(file))
                    ret.append(file);
            }
        }
        else
        {
            ret.append(s);
        }
    }
    return ret;
}

QStringList CMakeProjectVisitor::traverseGlob(const QString& startPath, const QString& expression, bool recursive, bool followSymlinks)
{
    kDebug(9042) << "Starting from (" << startPath << ", " << expression << "," << recursive << ", " << followSymlinks << ")";
    QString expr = expression;
    int firstSlash = expr.indexOf('/');
    int slashShift = 0;
    while (firstSlash == slashShift) //skip trailing slashes
    {
        slashShift++;
        firstSlash = expr.indexOf('/', slashShift);
    }
    expr = expr.mid(slashShift);
    if (firstSlash == -1)
    {
        //We're in place. Lets match files from startPath dir.
        kDebug(9042) << "Matching files in " << startPath << " with glob " << expr;
        QStringList nameFilters;
        nameFilters << expr;
        QStringList dirsToSearch;
        if (recursive)
        {
            QDir::Filters dirFilters = QDir::NoDotAndDotDot | QDir::Dirs;
            bool CMP0009IsSetToNew = true; // TODO: Obey CMP0009 policy when policies are implemented.
            if (!(CMP0009IsSetToNew && followSymlinks))
                dirFilters |= QDir::NoSymLinks;
            QQueue<QString> dirsToExpand;
            dirsToExpand.enqueue(startPath);
            while (!dirsToExpand.empty())
            {
                QString dir = dirsToExpand.dequeue();
                kDebug(9042) << "Enqueueing " << dir;
                dirsToSearch << dir;
                QDir d(dir);
                QStringList dirNames = d.entryList(dirFilters);
                foreach(QString dirName, dirNames)
                {
                    dirsToExpand << d.filePath(dirName);
                }
            }
        }
        else
            dirsToSearch << startPath;
        QStringList filePaths;
        foreach (QString dirToSearch, dirsToSearch)
        {
            QDir dir(dirToSearch);
            QStringList fileNames = dir.entryList(nameFilters, QDir::Files);
            foreach (QString fileName, fileNames)
            {
                filePaths << dir.filePath(fileName);
            }
        }
        return filePaths;
    }
    firstSlash -= slashShift;
    QString dirGlob = expr.left(firstSlash);
    QString rightExpression = expr.mid(firstSlash + 1);
    //Now we must find match for a directory specified in dirGlob
    QStringList matchedDirs;
    if (dirGlob.contains('*') || dirGlob.contains('?') || dirGlob.contains('['))
    {
        kDebug(9042) << "Got a dir glob " << dirGlob;
        if (startPath.isEmpty())
            return QStringList();
        //it's really a glob, not just dir name
        QStringList nameFilters;
        nameFilters << dirGlob;
        matchedDirs = QDir(startPath).entryList(nameFilters, QDir::NoDotAndDotDot | QDir::Dirs);
    }
    else
    {
        //just a directory name. Add it as a match.
        kDebug(9042) << "Got a simple folder " << dirGlob;
        matchedDirs << dirGlob;
    }
    QStringList matches;
    QString path = startPath;
    if (!path.endsWith('/'))
        path += '/';
    foreach(QString dirName, matchedDirs)
    {
        kDebug(9042) << "Going resursive into " << path + dirName << " and glob " << rightExpression;
        matches.append(traverseGlob(path + dirName, rightExpression, recursive, followSymlinks));
    }
    return matches;
}