summaryrefslogtreecommitdiffstats
path: root/src/tools/qdoc/tree.cpp
blob: ac55cb7318ffe525d60f27a480c458765f306080 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

/*
  tree.cpp
*/

#include <QDomDocument>
#include "atom.h"
#include "doc.h"
#include "htmlgenerator.h"
#include "location.h"
#include "node.h"
#include "text.h"
#include "tree.h"
#include <limits.h>
#include <qdebug.h>

QT_BEGIN_NAMESPACE

struct InheritanceBound
{
    Node::Access access;
    QStringList basePath;
    QString dataTypeWithTemplateArgs;
    InnerNode* parent;

    InheritanceBound()
        : access(Node::Public) { }
    InheritanceBound(Node::Access access0,
                     const QStringList& basePath0,
                     const QString& dataTypeWithTemplateArgs0,
                     InnerNode* parent)
        : access(access0), basePath(basePath0),
          dataTypeWithTemplateArgs(dataTypeWithTemplateArgs0),
          parent(parent) { }
};

struct Target
{
    Node* node;
    Atom* atom;
    int priority;
};

typedef QMap<PropertyNode::FunctionRole, QString> RoleMap;
typedef QMap<PropertyNode*, RoleMap> PropertyMap;
typedef QMultiHash<QString, FakeNode*> FakeNodeHash;
typedef QMultiHash<QString, Target> TargetHash;

class TreePrivate
{
public:
    QMap<ClassNode* , QList<InheritanceBound> > unresolvedInheritanceMap;
    PropertyMap unresolvedPropertyMap;
    NodeMultiMap groupMap;
    NodeMultiMap qmlModuleMap;
    QMultiMap<QString, QString> publicGroupMap;
    FakeNodeHash fakeNodesByTitle;
    TargetHash targetHash;
    QList<QPair<ClassNode*,QString> > basesList;
    QList<QPair<FunctionNode*,QString> > relatedList;
};

/*!
  \class Tree

  This class constructs and maintains a tree of instances of
  Node and its many subclasses.
 */

/*!
  The default constructor is the only constructor.
 */
Tree::Tree()
    : roo(0, "")
{
    priv = new TreePrivate;
}

/*!
  The destructor deletes the internal, private tree.
 */
Tree::~Tree()
{
    delete priv;
}

// 1 calls 2
/*!
  Searches the tree for a node that matches the \a path. The
  search begins at \a start but can move up the parent chain
  recursively if no match is found.
 */
const Node* Tree::findNode(const QStringList& path,
                           const Node* start,
                           int findFlags,
                           const Node* self) const
{
    const Node* current = start;
    if (!current)
        current = root();

    /*
      First, search for a node assuming we don't want a QML node.
      If that search fails, search again assuming we do want a
      QML node.
     */
    const Node* n = findNode(path,current,findFlags,self,false);
    if (!n) {
        n = findNode(path,current,findFlags,self,true);
    }
    return n;
}

// 2 is private; it is only called by 1.
/*!
  This overload function was extracted from the one above that has the
  same signature without the last bool parameter, \a qml. This version
  is called only by that other one. It is therefore private.  It can
  be called a second time by that other version, if the first call
  returns null. If \a qml is false, the search will only match a node
  that is not a QML node.  If \a qml is true, the search will only
  match a node that is a QML node.
*/
const Node* Tree::findNode(const QStringList& path,
                           const Node* start,
                           int findFlags,
                           const Node* self,
                           bool qml) const
{
    const Node* current = start;
    do {
        const Node* node = current;
        int i;
        int start_idx = 0;

        /*
          If the path contains one or two double colons ("::"),
          check first to see if the first two path strings refer
          to a QML element. If yes, that reference identifies a
          QML class node.
        */
        if (qml && path.size() >= 2) {
            QmlClassNode* qcn = QmlClassNode::moduleMap.value(path[0]+ "::" +path[1]);
            if (qcn) {
                node = qcn;
                if (path.size() == 2)
                    return node;
                start_idx = 2;
            }
        }

        for (i = start_idx; i < path.size(); ++i) {
            if (node == 0 || !node->isInnerNode())
                break;

            const Node* next = static_cast<const InnerNode*>(node)->findChildNodeByName(path.at(i), qml);

            if (!next && (findFlags & SearchEnumValues) && i == path.size()-1)
                next = static_cast<const InnerNode*>(node)->findEnumNodeForValue(path.at(i));

            if (!next && !qml && node->type() == Node::Class && (findFlags & SearchBaseClasses)) {
                NodeList baseClasses = allBaseClasses(static_cast<const ClassNode*>(node));
                foreach (const Node* baseClass, baseClasses) {
                    next = static_cast<const InnerNode*>(baseClass)->findChildNodeByName(path.at(i));
                    if (!next && (findFlags & SearchEnumValues) && i == path.size() - 1)
                        next = static_cast<const InnerNode*>(baseClass)->findEnumNodeForValue(path.at(i));
                    if (next)
                        break;
                }
            }
            node = next;
        }
        if (node && i == path.size()
                && (!(findFlags & NonFunction) || node->type() != Node::Function
                    || ((FunctionNode*)node)->metaness() == FunctionNode::MacroWithoutParams)) {
            if ((node != self) && (node->subType() != Node::QmlPropertyGroup)) {
                if (node->subType() == Node::Collision) {
                    node = node->applyModuleIdentifier(start);
                }
                return node;
            }
        }
        current = current->parent();
    } while (current);

    return 0;
}

/*!
  Find the QML class node for the specified \a module and \a name
  identifiers. The \a module identifier may be empty. If the module
  identifier is empty, then begin by finding the FakeNode that has
  the specified \a name. If that FakeNode is a QML class, return it.
  If it is a collision node, return its current child, if the current
  child is a QML class. If the collision node does not have a child
  that is a QML class node, return 0.
 */
QmlClassNode* Tree::findQmlClassNode(const QString& module, const QString& name)
{
    if (module.isEmpty()) {
        Node* n = findQmlClassNode(QStringList(name));
        if (n) {
            if (n->subType() == Node::QmlClass)
                return static_cast<QmlClassNode*>(n);
            else if (n->subType() == Node::Collision) {
                NameCollisionNode* ncn;
                ncn = static_cast<NameCollisionNode*>(n);
                return static_cast<QmlClassNode*>(ncn->findAny(Node::Fake,Node::QmlClass));
            }
        }
        return 0;
    }
    return QmlClassNode::moduleMap.value(module + "::" + name);
}

/*!
  First, search for a node with the specified \a name. If a matching
  node is found, if it is a collision node, another collision with
  this name has been found, so return the collision node. If the
  matching node is not a collision node, the first collision for this
  name has been found, so create a NameCollisionNode with the matching
  node as its first child, and return a pointer to the new
  NameCollisionNode. Otherwise return 0.
 */
NameCollisionNode* Tree::checkForCollision(const QString& name) const
{
    Node* n = const_cast<Node*>(findNode(QStringList(name)));
    if (n) {
        if (n->subType() == Node::Collision) {
            NameCollisionNode* ncn = static_cast<NameCollisionNode*>(n);
            return ncn;
        }
        if (n->isInnerNode())
            return new NameCollisionNode(static_cast<InnerNode*>(n));
    }
    return 0;
}

/*!
  This function is like checkForCollision() in that it searches
  for a collision node with the specified \a name. But it doesn't
  create anything. If it finds a match, it returns the pointer.
  Otherwise it returns 0.
 */
NameCollisionNode* Tree::findCollisionNode(const QString& name) const
{
    Node* n = const_cast<Node*>(findNode(QStringList(name)));
    if (n) {
        if (n->subType() == Node::Collision) {
            NameCollisionNode* ncn = static_cast<NameCollisionNode*>(n);
            return ncn;
        }
    }
    return 0;
}

/*!
  This function just calls the const version of the same function
  and returns the function node.
 */
FunctionNode* Tree::findFunctionNode(const QStringList& path,
                                     Node* relative,
                                     int findFlags)
{
    return const_cast<FunctionNode*>
            (const_cast<const Tree*>(this)->findFunctionNode(path,relative,findFlags));
}

/*!
  This function begins searching the tree at \a relative for
  the \l {FunctionNode} {function node} identified by \a path.
  The \a findFlags are used to restrict the search. If a node
  that matches the \a path is found, it is returned. Otherwise,
  0 is returned. If \a relative is 0, the root of the tree is
  used as the starting point.
 */
const FunctionNode* Tree::findFunctionNode(const QStringList& path,
                                           const Node* relative,
                                           int findFlags) const
{
    if (!relative)
        relative = root();

    /*
      If the path contains two double colons ("::"), check
      first to see if it is a reference to a QML method. If
      it is a reference to a QML method, first look up the
      QML class node in the QML module map.
     */
    if (path.size() == 3) {
        QmlClassNode* qcn = QmlClassNode::moduleMap.value(path[0]+ "::" +path[1]);
        if (qcn) {
            return static_cast<const FunctionNode*>(qcn->findFunctionNode(path[2]));
        }
    }

    do {
        const Node* node = relative;
        int i;

        for (i = 0; i < path.size(); ++i) {
            if (node == 0 || !node->isInnerNode())
                break;

            const Node* next;
            if (i == path.size() - 1)
                next = ((InnerNode*) node)->findFunctionNode(path.at(i));
            else
                next = ((InnerNode*) node)->findChildNodeByName(path.at(i));

            if (!next && node->type() == Node::Class && (findFlags & SearchBaseClasses)) {
                NodeList baseClasses = allBaseClasses(static_cast<const ClassNode*>(node));
                foreach (const Node* baseClass, baseClasses) {
                    if (i == path.size() - 1)
                        next = static_cast<const InnerNode*>(baseClass)->findFunctionNode(path.at(i));
                    else
                        next = static_cast<const InnerNode*>(baseClass)->findChildNodeByName(path.at(i));

                    if (next)
                        break;
                }
            }

            node = next;
        }
        if (node && i == path.size() && node->isFunction()) {
            // CppCodeParser::processOtherMetaCommand ensures that reimplemented
            // functions are private.
            const FunctionNode* func = static_cast<const FunctionNode*>(node);
            while (func->access() == Node::Private) {
                const FunctionNode* from = func->reimplementedFrom();
                if (from != 0) {
                    if (from->access() != Node::Private)
                        return from;
                    else
                        func = from;
                }
                else
                    break;
            }
            return func;
        }
        relative = relative->parent();
    } while (relative);

    return 0;
}

/*!
  This function just calls the const version of itself and
  returns the result.
 */
FunctionNode* Tree::findFunctionNode(const QStringList& parentPath,
                                     const FunctionNode* clone,
                                     Node* relative,
                                     int findFlags)
{
    return const_cast<FunctionNode*>(
                const_cast<const Tree*>(this)->findFunctionNode(parentPath,
                                                                clone,
                                                                relative,
                                                                findFlags));
}

/*!
  This function first ignores the \a clone node and searches
  for the node having the \a parentPath by calling the main
  findFunction(\a {parentPath}, \a {relative}, \a {findFlags}).
  If that search is successful, then it searches for the \a clone
  in the found parent node.
 */
const FunctionNode* Tree::findFunctionNode(const QStringList& parentPath,
                                           const FunctionNode* clone,
                                           const Node* relative,
                                           int findFlags) const
{
    const Node* parent = findNode(parentPath, relative, findFlags);
    if (parent == 0 || !parent->isInnerNode()) {
        return 0;
    }
    else {
        return ((InnerNode*)parent)->findFunctionNode(clone);
    }
}
//findNode(parameter.leftType().split("::"), 0, SearchBaseClasses|NonFunction);

static const int NumSuffixes = 3;
static const char*  const suffixes[NumSuffixes] = { "", "s", "es" };

/*!
  This function searches for a node with the specified \a title.
  If \a relative is provided, use it to disambiguate if it has a
  QML module identifier.
 */
const FakeNode* Tree::findFakeNodeByTitle(const QString& title, const Node* relative ) const
{
    for (int pass = 0; pass < NumSuffixes; ++pass) {
        FakeNodeHash::const_iterator i = priv->fakeNodesByTitle.find(Doc::canonicalTitle(title + suffixes[pass]));
        if (i != priv->fakeNodesByTitle.constEnd()) {
            if (relative && !relative->qmlModuleIdentifier().isEmpty()) {
                const FakeNode* fn = i.value();
                InnerNode* parent = fn->parent();
                if (parent && parent->type() == Node::Fake && parent->subType() == Node::Collision) {
                    const NodeList& nl = parent->childNodes();
                    NodeList::ConstIterator it = nl.begin();
                    while (it != nl.end()) {
                        if ((*it)->qmlModuleIdentifier() == relative->qmlModuleIdentifier()) {
                            /*
                              By returning here, we avoid printing all the duplicate
                              header warnings, which are not really duplicates now,
                              because of the QML module identifier being used as a
                              namespace qualifier.
                             */
                            fn = static_cast<const FakeNode*>(*it);
                            return fn;
                        }
                        ++it;
                    }
                }
            }
            /*
              Reporting all these duplicate section titles is probably
              overkill. We should report the duplicate file and let
              that suffice.
             */
            FakeNodeHash::const_iterator j = i;
            ++j;
            if (j != priv->fakeNodesByTitle.constEnd() && j.key() == i.key()) {
                QList<Location> internalLocations;
                while (j != priv->fakeNodesByTitle.constEnd()) {
                    if (j.key() == i.key() && j.value()->url().isEmpty())
                        internalLocations.append(j.value()->doc().location());
                    ++j;
                }
                if (internalLocations.size() > 0) {
                    i.value()->doc().location().warning(
                                tr("Page '%1' defined in more than one location:").arg(title));
                    foreach (const Location &location, internalLocations)
                        location.warning(tr("(defined here)"));
                }
            }
            return i.value();
        }
    }
    return 0;
}

/*!
  This function searches for a \a target anchor node. If it
  finds one, it sets \a atom from the found node and returns
  the found node.
 */
const Node*
Tree::findUnambiguousTarget(const QString& target, Atom *&atom, const Node* relative) const
{
    Target bestTarget = {0, 0, INT_MAX};
    int numBestTargets = 0;
    QList<Target> bestTargetList;

    for (int pass = 0; pass < NumSuffixes; ++pass) {
        TargetHash::const_iterator i = priv->targetHash.find(Doc::canonicalTitle(target + suffixes[pass]));
        if (i != priv->targetHash.constEnd()) {
            TargetHash::const_iterator j = i;
            do {
                const Target& candidate = j.value();
                if (candidate.priority < bestTarget.priority) {
                    bestTarget = candidate;
                    bestTargetList.clear();
                    bestTargetList.append(candidate);
                    numBestTargets = 1;
                } else if (candidate.priority == bestTarget.priority) {
                    bestTargetList.append(candidate);
                    ++numBestTargets;
                }
                ++j;
            } while (j != priv->targetHash.constEnd() && j.key() == i.key());

            if (numBestTargets == 1) {
                atom = bestTarget.atom;
                return bestTarget.node;
            }
            else if (bestTargetList.size() > 1) {
                if (relative && !relative->qmlModuleIdentifier().isEmpty()) {
                    for (int i=0; i<bestTargetList.size(); ++i) {
                        const Node* n = bestTargetList.at(i).node;
                        if (relative->qmlModuleIdentifier() == n->qmlModuleIdentifier()) {
                            atom = bestTargetList.at(i).atom;
                            return n;
                        }
                    }
                }
            }
        }
    }
    return 0;
}

/*!
  This function searches for a node with a canonical title
  constructed from \a target and each of the possible suffixes.
  If the node it finds is \a node, it returns the Atom from that
  node. Otherwise it returns null.
 */
Atom* Tree::findTarget(const QString& target, const Node* node) const
{
    for (int pass = 0; pass < NumSuffixes; ++pass) {
        QString key = Doc::canonicalTitle(target + suffixes[pass]);
        TargetHash::const_iterator i = priv->targetHash.find(key);

        if (i != priv->targetHash.constEnd()) {
            do {
                if (i.value().node == node)
                    return i.value().atom;
                ++i;
            } while (i != priv->targetHash.constEnd() && i.key() == key);
        }
    }
    return 0;
}

/*!
 */
void Tree::addBaseClass(ClassNode* subclass, Node::Access access,
                        const QStringList& basePath,
                        const QString& dataTypeWithTemplateArgs,
                        InnerNode* parent)
{
    priv->unresolvedInheritanceMap[subclass].append(
                InheritanceBound(access,
                                 basePath,
                                 dataTypeWithTemplateArgs,
                                 parent)
                );
}

/*!
 */
void Tree::addPropertyFunction(PropertyNode* property,
                               const QString& funcName,
                               PropertyNode::FunctionRole funcRole)
{
    priv->unresolvedPropertyMap[property].insert(funcRole, funcName);
}

/*!
  This function adds the \a node to the \a group. The group
  can be listed anywhere using the \e{annotated list} command.
 */
void Tree::addToGroup(Node* node, const QString& group)
{
    priv->groupMap.insert(group, node);
}

/*!
  This function adds the \a node to the QML \a module. The QML
  module can be listed anywhere using the \e{annotated list}
  command.
 */
void Tree::addToQmlModule(Node* node, const QString& module)
{
    priv->qmlModuleMap.insert(module, node);
}

/*!
  Returns the group map.
 */
NodeMultiMap Tree::groups() const
{
    return priv->groupMap;
}

/*!
  Returns the QML module map.
 */
NodeMultiMap Tree::qmlModules() const
{
    return priv->qmlModuleMap;
}

/*!
 */
void Tree::addToPublicGroup(Node* node, const QString& group)
{
    priv->publicGroupMap.insert(node->name(), group);
    addToGroup(node, group);
}

/*!
 */
QMultiMap<QString, QString> Tree::publicGroups() const
{
    return priv->publicGroupMap;
}

/*!
 */
void Tree::resolveInheritance(NamespaceNode* rootNode)
{
    if (!rootNode)
        rootNode = root();

    for (int pass = 0; pass < 2; pass++) {
        NodeList::ConstIterator c = rootNode->childNodes().begin();
        while (c != rootNode->childNodes().end()) {
            if ((*c)->type() == Node::Class) {
                resolveInheritance(pass, (ClassNode*)* c);
            }
            else if ((*c)->type() == Node::Namespace) {
                NamespaceNode* ns = static_cast<NamespaceNode*>(*c);
                resolveInheritance(ns);
            }
            ++c;
        }
        if (rootNode == root())
            priv->unresolvedInheritanceMap.clear();
    }
}

/*!
 */
void Tree::resolveProperties()
{
    PropertyMap::ConstIterator propEntry;

    propEntry = priv->unresolvedPropertyMap.begin();
    while (propEntry != priv->unresolvedPropertyMap.end()) {
        PropertyNode* property = propEntry.key();
        InnerNode* parent = property->parent();
        QString getterName = (*propEntry)[PropertyNode::Getter];
        QString setterName = (*propEntry)[PropertyNode::Setter];
        QString resetterName = (*propEntry)[PropertyNode::Resetter];
        QString notifierName = (*propEntry)[PropertyNode::Notifier];

        NodeList::ConstIterator c = parent->childNodes().begin();
        while (c != parent->childNodes().end()) {
            if ((*c)->type() == Node::Function) {
                FunctionNode* function = static_cast<FunctionNode*>(*c);
                if (function->access() == property->access() &&
                        (function->status() == property->status() ||
                         function->doc().isEmpty())) {
                    if (function->name() == getterName) {
                        property->addFunction(function, PropertyNode::Getter);
                    }
                    else if (function->name() == setterName) {
                        property->addFunction(function, PropertyNode::Setter);
                    }
                    else if (function->name() == resetterName) {
                        property->addFunction(function, PropertyNode::Resetter);
                    }
                    else if (function->name() == notifierName) {
                        property->addSignal(function, PropertyNode::Notifier);
                    }
                }
            }
            ++c;
        }
        ++propEntry;
    }

    propEntry = priv->unresolvedPropertyMap.begin();
    while (propEntry != priv->unresolvedPropertyMap.end()) {
        PropertyNode* property = propEntry.key();
        // redo it to set the property functions
        if (property->overriddenFrom())
            property->setOverriddenFrom(property->overriddenFrom());
        ++propEntry;
    }

    priv->unresolvedPropertyMap.clear();
}

/*!
 */
void Tree::resolveInheritance(int pass, ClassNode* classe)
{
    if (pass == 0) {
        QList<InheritanceBound> bounds = priv->unresolvedInheritanceMap[classe];
        QList<InheritanceBound>::ConstIterator b = bounds.begin();
        while (b != bounds.end()) {
            Node* n = findClassNode((*b).basePath);
            if (!n && (*b).parent) {
                n = findClassNode((*b).basePath, (*b).parent);
            }
            if (n) {
                classe->addBaseClass((*b).access, static_cast<ClassNode*>(n), (*b).dataTypeWithTemplateArgs);
            }
            ++b;
        }
    }
    else {
        NodeList::ConstIterator c = classe->childNodes().begin();
        while (c != classe->childNodes().end()) {
            if ((*c)->type() == Node::Function) {
                FunctionNode* func = (FunctionNode*)* c;
                FunctionNode* from = findVirtualFunctionInBaseClasses(classe, func);
                if (from != 0) {
                    if (func->virtualness() == FunctionNode::NonVirtual)
                        func->setVirtualness(FunctionNode::ImpureVirtual);
                    func->setReimplementedFrom(from);
                }
            }
            else if ((*c)->type() == Node::Property) {
                fixPropertyUsingBaseClasses(classe, static_cast<PropertyNode*>(*c));
            }
            ++c;
        }
    }
}

/*!
  For each node in the group map, add the node to the appropriate
  group node.
 */
void Tree::resolveGroups()
{
    NodeMultiMap::const_iterator i;
    for (i = priv->groupMap.constBegin(); i != priv->groupMap.constEnd(); ++i) {
        if (i.value()->access() == Node::Private)
            continue;

        Node* n = findGroupNode(QStringList(i.key()));
        if (n)
            n->addGroupMember(i.value());
    }
}

/*!
  For each node in the QML module map, add the node to the
  appropriate QML module node.
 */
void Tree::resolveQmlModules()
{
    NodeMultiMap::const_iterator i;
    for (i = priv->qmlModuleMap.constBegin(); i != priv->qmlModuleMap.constEnd(); ++i) {
        Node* n = findQmlModuleNode(QStringList(i.key()));
        if (n)
            n->addQmlModuleMember(i.value());
    }
}

/*!
 */
void Tree::resolveTargets(InnerNode* root)
{
    // need recursion

    foreach (Node* child, root->childNodes()) {
        if (child->type() == Node::Fake) {
            FakeNode* node = static_cast<FakeNode*>(child);
            if (!node->title().isEmpty())
                priv->fakeNodesByTitle.insert(Doc::canonicalTitle(node->title()), node);
            if (node->subType() == Node::Collision) {
                resolveTargets(node);
            }
        }

        if (child->doc().hasTableOfContents()) {
            const QList<Atom*>& toc = child->doc().tableOfContents();
            Target target;
            target.node = child;
            target.priority = 3;

            for (int i = 0; i < toc.size(); ++i) {
                target.atom = toc.at(i);
                QString title = Text::sectionHeading(target.atom).toString();
                if (!title.isEmpty())
                    priv->targetHash.insert(Doc::canonicalTitle(title), target);
            }
        }
        if (child->doc().hasKeywords()) {
            const QList<Atom*>& keywords = child->doc().keywords();
            Target target;
            target.node = child;
            target.priority = 1;

            for (int i = 0; i < keywords.size(); ++i) {
                target.atom = keywords.at(i);
                priv->targetHash.insert(Doc::canonicalTitle(target.atom->string()), target);
            }
        }
        if (child->doc().hasTargets()) {
            const QList<Atom*>& toc = child->doc().targets();
            Target target;
            target.node = child;
            target.priority = 2;

            for (int i = 0; i < toc.size(); ++i) {
                target.atom = toc.at(i);
                priv->targetHash.insert(Doc::canonicalTitle(target.atom->string()), target);
            }
        }
    }
}

/*!
  For each QML class node that points to a C++ class node,
  follow its C++ class node pointer and set the C++ class
  node's QML class node pointer back to the QML class node.
 */
void Tree::resolveCppToQmlLinks()
{

    foreach (Node* child, roo.childNodes()) {
        if (child->type() == Node::Fake && child->subType() == Node::QmlClass) {
            QmlClassNode* qcn = static_cast<QmlClassNode*>(child);
            ClassNode* cn = const_cast<ClassNode*>(qcn->classNode());
            if (cn)
                cn->setQmlElement(qcn);
        }
    }
}

/*!
  For each QML class node in the tree, determine whether
  it inherits a QML base class and, if so, which one, and
  store that pointer in the QML class node's state.
 */
void Tree::resolveQmlInheritance()
{

    foreach (Node* child, roo.childNodes()) {
        if (child->type() == Node::Fake) {
            if (child->subType() == Node::QmlClass) {
                QmlClassNode* qcn = static_cast<QmlClassNode*>(child);
                qcn->resolveInheritance(this);
            }
            else if (child->subType() == Node::Collision) {
                NameCollisionNode* ncn = static_cast<NameCollisionNode*>(child);
                foreach (Node* child, ncn->childNodes()) {
                    if (child->type() == Node::Fake) {
                        if (child->subType() == Node::QmlClass) {
                            QmlClassNode* qcn = static_cast<QmlClassNode*>(child);
                            qcn->resolveInheritance(this);
                        }
                    }
                }
            }
        }
    }
}

/*!
 */
void Tree::fixInheritance(NamespaceNode* rootNode)
{
    if (!rootNode)
        rootNode = root();

    NodeList::ConstIterator c = rootNode->childNodes().begin();
    while (c != rootNode->childNodes().end()) {
        if ((*c)->type() == Node::Class)
            static_cast<ClassNode*>(*c)->fixBaseClasses();
        else if ((*c)->type() == Node::Namespace) {
            NamespaceNode* ns = static_cast<NamespaceNode*>(*c);
            fixInheritance(ns);
        }
        ++c;
    }
}

/*!
 */
FunctionNode* Tree::findVirtualFunctionInBaseClasses(ClassNode* classe,
                                                     FunctionNode* clone)
{
    QList<RelatedClass>::ConstIterator r = classe->baseClasses().begin();
    while (r != classe->baseClasses().end()) {
        FunctionNode* func;
        if (((func = findVirtualFunctionInBaseClasses((*r).node, clone)) != 0 ||
             (func = (*r).node->findFunctionNode(clone)) != 0)) {
            if (func->virtualness() != FunctionNode::NonVirtual)
                return func;
        }
        ++r;
    }
    return 0;
}

/*!
 */
void Tree::fixPropertyUsingBaseClasses(ClassNode* classe, PropertyNode* property)
{
    QList<RelatedClass>::const_iterator r = classe->baseClasses().begin();
    while (r != classe->baseClasses().end()) {
        Node* n = r->node->findChildNodeByNameAndType(property->name(), Node::Property);
        if (n) {
            PropertyNode* baseProperty = static_cast<PropertyNode*>(n);
            fixPropertyUsingBaseClasses(r->node, baseProperty);
            property->setOverriddenFrom(baseProperty);
        }
        else {
            fixPropertyUsingBaseClasses(r->node, property);
        }
        ++r;
    }
}

/*!
 */
NodeList Tree::allBaseClasses(const ClassNode* classe) const
{
    NodeList result;
    foreach (const RelatedClass& r, classe->baseClasses()) {
        result += r.node;
        result += allBaseClasses(r.node);
    }
    return result;
}

/*!
 */
void Tree::readIndexes(const QStringList& indexFiles)
{
    foreach (const QString& indexFile, indexFiles)
        readIndexFile(indexFile);
}

/*!
  Read the QDomDocument at \a path and get the index from it.
 */
void Tree::readIndexFile(const QString& path)
{
    QFile file(path);
    if (file.open(QFile::ReadOnly)) {
        QDomDocument document;
        document.setContent(&file);
        file.close();

        QDomElement indexElement = document.documentElement();

        // Generate a relative URL between the install dir and the index file
        // when the -installdir command line option is set.
        QString indexUrl;
        if (Config::installDir.isEmpty()) {
            indexUrl = indexElement.attribute("url", "");
        }
        else {
            QDir installDir(Config::installDir);
            indexUrl = installDir.relativeFilePath(path).section('/', 0, -2);
        }

        priv->basesList.clear();
        priv->relatedList.clear();

        // Scan all elements in the XML file, constructing a map that contains
        // base classes for each class found.

        QDomElement child = indexElement.firstChildElement();
        while (!child.isNull()) {
            readIndexSection(child, root(), indexUrl);
            child = child.nextSiblingElement();
        }

        // Now that all the base classes have been found for this index,
        // arrange them into an inheritance hierarchy.

        resolveIndex();
    }
}

/*!
  Read a <section> element from the index file and create the
  appropriate node(s).
 */
void Tree::readIndexSection(const QDomElement& element,
                            InnerNode* parent,
                            const QString& indexUrl)
{
    QString name = element.attribute("name");
    QString href = element.attribute("href");

    Node* section;
    Location location;

    if (element.nodeName() == "namespace") {
        section = new NamespaceNode(parent, name);

        if (!indexUrl.isEmpty())
            location = Location(indexUrl + QLatin1Char('/') + name.toLower() + ".html");
        else if (!indexUrl.isNull())
            location = Location(name.toLower() + ".html");

    }
    else if (element.nodeName() == "class") {
        section = new ClassNode(parent, name);
        priv->basesList.append(QPair<ClassNode*,QString>(
                                   static_cast<ClassNode*>(section), element.attribute("bases")));

        if (!indexUrl.isEmpty())
            location = Location(indexUrl + QLatin1Char('/') + name.toLower() + ".html");
        else if (!indexUrl.isNull())
            location = Location(name.toLower() + ".html");

    }
    else if ((element.nodeName() == "qmlclass") ||
             ((element.nodeName() == "page") && (element.attribute("subtype") == "qmlclass"))) {
        QmlClassNode* qcn = new QmlClassNode(parent, name, 0);
        qcn->setTitle(element.attribute("title"));
        if (element.hasAttribute("location"))
            name = element.attribute("location", "");
        if (!indexUrl.isEmpty())
            location = Location(indexUrl + QLatin1Char('/') + name);
        else if (!indexUrl.isNull())
            location = Location(name);
        section = qcn;
    }
    else if (element.nodeName() == "qmlbasictype") {
        QmlBasicTypeNode* qbtn = new QmlBasicTypeNode(parent, name);
        qbtn->setTitle(element.attribute("title"));
        if (element.hasAttribute("location"))
            name = element.attribute("location", "");
        if (!indexUrl.isEmpty())
            location = Location(indexUrl + QLatin1Char('/') + name);
        else if (!indexUrl.isNull())
            location = Location(name);
        section = qbtn;
    }
    else if (element.nodeName() == "page") {
        Node::SubType subtype;
        Node::PageType ptype = Node::NoPageType;
        if (element.attribute("subtype") == "example") {
            subtype = Node::Example;
            ptype = Node::ExamplePage;
        }
        else if (element.attribute("subtype") == "header") {
            subtype = Node::HeaderFile;
            ptype = Node::ApiPage;
        }
        else if (element.attribute("subtype") == "file") {
            subtype = Node::File;
            ptype = Node::NoPageType;
        }
        else if (element.attribute("subtype") == "group") {
            subtype = Node::Group;
            ptype = Node::OverviewPage;
        }
        else if (element.attribute("subtype") == "module") {
            subtype = Node::Module;
            ptype = Node::OverviewPage;
        }
        else if (element.attribute("subtype") == "page") {
            subtype = Node::Page;
            ptype = Node::ArticlePage;
        }
        else if (element.attribute("subtype") == "externalpage") {
            subtype = Node::ExternalPage;
            ptype = Node::ArticlePage;
        }
        else if (element.attribute("subtype") == "qmlclass") {
            subtype = Node::QmlClass;
            ptype = Node::ApiPage;
        }
        else if (element.attribute("subtype") == "qmlpropertygroup") {
            subtype = Node::QmlPropertyGroup;
            ptype = Node::ApiPage;
        }
        else if (element.attribute("subtype") == "qmlbasictype") {
            subtype = Node::QmlBasicType;
            ptype = Node::ApiPage;
        }
        else
            return;

        FakeNode* fakeNode = new FakeNode(parent, name, subtype, ptype);
        fakeNode->setTitle(element.attribute("title"));

        if (element.hasAttribute("location"))
            name = element.attribute("location", "");

        if (!indexUrl.isEmpty())
            location = Location(indexUrl + QLatin1Char('/') + name);
        else if (!indexUrl.isNull())
            location = Location(name);

        section = fakeNode;

    }
    else if (element.nodeName() == "enum") {
        EnumNode* enumNode = new EnumNode(parent, name);

        if (!indexUrl.isEmpty())
            location =
                    Location(indexUrl + QLatin1Char('/') + parent->name().toLower() + ".html");
        else if (!indexUrl.isNull())
            location = Location(parent->name().toLower() + ".html");

        QDomElement child = element.firstChildElement("value");
        while (!child.isNull()) {
            EnumItem item(child.attribute("name"), child.attribute("value"));
            enumNode->addItem(item);
            child = child.nextSiblingElement("value");
        }

        section = enumNode;

    } else if (element.nodeName() == "typedef") {
        section = new TypedefNode(parent, name);

        if (!indexUrl.isEmpty())
            location =
                    Location(indexUrl + QLatin1Char('/') + parent->name().toLower() + ".html");
        else if (!indexUrl.isNull())
            location = Location(parent->name().toLower() + ".html");

    }
    else if (element.nodeName() == "property") {
        section = new PropertyNode(parent, name);

        if (!indexUrl.isEmpty())
            location =
                    Location(indexUrl + QLatin1Char('/') + parent->name().toLower() + ".html");
        else if (!indexUrl.isNull())
            location = Location(parent->name().toLower() + ".html");

    } else if (element.nodeName() == "function") {
        FunctionNode::Virtualness virt;
        if (element.attribute("virtual") == "non")
            virt = FunctionNode::NonVirtual;
        else if (element.attribute("virtual") == "impure")
            virt = FunctionNode::ImpureVirtual;
        else if (element.attribute("virtual") == "pure")
            virt = FunctionNode::PureVirtual;
        else
            return;

        FunctionNode::Metaness meta;
        if (element.attribute("meta") == "plain")
            meta = FunctionNode::Plain;
        else if (element.attribute("meta") == "signal")
            meta = FunctionNode::Signal;
        else if (element.attribute("meta") == "slot")
            meta = FunctionNode::Slot;
        else if (element.attribute("meta") == "constructor")
            meta = FunctionNode::Ctor;
        else if (element.attribute("meta") == "destructor")
            meta = FunctionNode::Dtor;
        else if (element.attribute("meta") == "macro")
            meta = FunctionNode::MacroWithParams;
        else if (element.attribute("meta") == "macrowithparams")
            meta = FunctionNode::MacroWithParams;
        else if (element.attribute("meta") == "macrowithoutparams")
            meta = FunctionNode::MacroWithoutParams;
        else
            return;

        FunctionNode* functionNode = new FunctionNode(parent, name);
        functionNode->setReturnType(element.attribute("return"));
        functionNode->setVirtualness(virt);
        functionNode->setMetaness(meta);
        functionNode->setConst(element.attribute("const") == "true");
        functionNode->setStatic(element.attribute("static") == "true");
        functionNode->setOverload(element.attribute("overload") == "true");

        if (element.hasAttribute("relates")
                && element.attribute("relates") != parent->name()) {
            priv->relatedList.append(
                        QPair<FunctionNode*,QString>(functionNode,
                                                     element.attribute("relates")));
        }

        QDomElement child = element.firstChildElement("parameter");
        while (!child.isNull()) {
            // Do not use the default value for the parameter; it is not
            // required, and has been known to cause problems.
            Parameter parameter(child.attribute("left"),
                                child.attribute("right"),
                                child.attribute("name"),
                                ""); // child.attribute("default")
            functionNode->addParameter(parameter);
            child = child.nextSiblingElement("parameter");
        }

        section = functionNode;

        if (!indexUrl.isEmpty())
            location =
                    Location(indexUrl + QLatin1Char('/') + parent->name().toLower() + ".html");
        else if (!indexUrl.isNull())
            location = Location(parent->name().toLower() + ".html");

    }
    else if (element.nodeName() == "variable") {
        section = new VariableNode(parent, name);

        if (!indexUrl.isEmpty())
            location = Location(indexUrl + QLatin1Char('/') + parent->name().toLower() + ".html");
        else if (!indexUrl.isNull())
            location = Location(parent->name().toLower() + ".html");

    }
    else if (element.nodeName() == "keyword") {
        Target target;
        target.node = parent;
        target.priority = 1;
        target.atom = new Atom(Atom::Target, name);
        priv->targetHash.insert(name, target);
        return;

    }
    else if (element.nodeName() == "target") {
        Target target;
        target.node = parent;
        target.priority = 2;
        target.atom = new Atom(Atom::Target, name);
        priv->targetHash.insert(name, target);
        return;

    }
    else if (element.nodeName() == "contents") {
        Target target;
        target.node = parent;
        target.priority = 3;
        target.atom = new Atom(Atom::Target, name);
        priv->targetHash.insert(name, target);
        return;

    }
    else
        return;

    QString access = element.attribute("access");
    if (access == "public")
        section->setAccess(Node::Public);
    else if (access == "protected")
        section->setAccess(Node::Protected);
    else if (access == "private")
        section->setAccess(Node::Private);
    else
        section->setAccess(Node::Public);

    if ((element.nodeName() != "page") &&
            (element.nodeName() != "qmlclass") &&
            (element.nodeName() != "qmlbasictype")) {
        QString threadSafety = element.attribute("threadsafety");
        if (threadSafety == "non-reentrant")
            section->setThreadSafeness(Node::NonReentrant);
        else if (threadSafety == "reentrant")
            section->setThreadSafeness(Node::Reentrant);
        else if (threadSafety == "thread safe")
            section->setThreadSafeness(Node::ThreadSafe);
        else
            section->setThreadSafeness(Node::UnspecifiedSafeness);
    }
    else
        section->setThreadSafeness(Node::UnspecifiedSafeness);

    QString status = element.attribute("status");
    if (status == "compat")
        section->setStatus(Node::Compat);
    else if (status == "obsolete")
        section->setStatus(Node::Obsolete);
    else if (status == "deprecated")
        section->setStatus(Node::Deprecated);
    else if (status == "preliminary")
        section->setStatus(Node::Preliminary);
    else if (status == "commendable")
        section->setStatus(Node::Commendable);
    else if (status == "internal")
        section->setStatus(Node::Internal);
    else if (status == "main")
        section->setStatus(Node::Main);
    else
        section->setStatus(Node::Commendable);

    section->setModuleName(element.attribute("module"));
    if (!indexUrl.isEmpty()) {
        if (indexUrl.startsWith(QLatin1Char('.')))
            section->setUrl(href);
        else
            section->setUrl(indexUrl + QLatin1Char('/') + href);
    }

    // Create some content for the node.
    QSet<QString> emptySet;

    Doc doc(location, location, " ", emptySet); // placeholder
    section->setDoc(doc);
    section->setIndexNodeFlag();

    if (section->isInnerNode()) {
        InnerNode* inner = static_cast<InnerNode*>(section);
        if (inner) {
            QDomElement child = element.firstChildElement();

            while (!child.isNull()) {
                if (element.nodeName() == "class")
                    readIndexSection(child, inner, indexUrl);
                else if (element.nodeName() == "qmlclass")
                    readIndexSection(child, inner, indexUrl);
                else if (element.nodeName() == "page")
                    readIndexSection(child, inner, indexUrl);
                else if (element.nodeName() == "namespace" && !name.isEmpty())
                    // The root node in the index is a namespace with an empty name.
                    readIndexSection(child, inner, indexUrl);
                else
                    readIndexSection(child, parent, indexUrl);

                child = child.nextSiblingElement();
            }
        }
    }
}

/*!
 */
QString Tree::readIndexText(const QDomElement& element)
{
    QString text;
    QDomNode child = element.firstChild();
    while (!child.isNull()) {
        if (child.isText())
            text += child.toText().nodeValue();
        child = child.nextSibling();
    }
    return text;
}

/*!
 */
void Tree::resolveIndex()
{
    QPair<ClassNode*,QString> pair;

    foreach (pair, priv->basesList) {
        foreach (const QString& base, pair.second.split(QLatin1Char(','))) {
            Node* n = root()->findChildNodeByNameAndType(base, Node::Class);
            if (n) {
                pair.first->addBaseClass(Node::Public, static_cast<ClassNode*>(n));
            }
        }
    }

    QPair<FunctionNode*,QString> relatedPair;

    foreach (relatedPair, priv->relatedList) {
        Node* n = root()->findChildNodeByNameAndType(relatedPair.second, Node::Class);
        if (n)
            relatedPair.first->setRelates(static_cast<ClassNode*>(n));
    }
}

/*!
  Generate the index section with the given \a writer for the \a node
  specified, returning true if an element was written; otherwise returns
  false.
 */
bool Tree::generateIndexSection(QXmlStreamWriter& writer,
                                Node* node,
                                bool generateInternalNodes)
{
    if (!node->url().isEmpty())
        return false;

    QString nodeName;
    switch (node->type()) {
    case Node::Namespace:
        nodeName = "namespace";
        break;
    case Node::Class:
        nodeName = "class";
        break;
    case Node::Fake:
        nodeName = "page";
        if (node->subType() == Node::QmlClass)
            nodeName = "qmlclass";
        else if (node->subType() == Node::QmlBasicType)
            nodeName = "qmlbasictype";
        break;
    case Node::Enum:
        nodeName = "enum";
        break;
    case Node::Typedef:
        nodeName = "typedef";
        break;
    case Node::Property:
        nodeName = "property";
        break;
    case Node::Function:
        nodeName = "function";
        break;
    case Node::Variable:
        nodeName = "variable";
        break;
    case Node::QmlProperty:
        nodeName = "qmlproperty";
        break;
    case Node::QmlSignal:
        nodeName = "qmlsignal";
        break;
    case Node::QmlSignalHandler:
        nodeName = "qmlsignalhandler";
        break;
    case Node::QmlMethod:
        nodeName = "qmlmethod";
        break;
    default:
        return false;
    }

    QString access;
    switch (node->access()) {
    case Node::Public:
        access = "public";
        break;
    case Node::Protected:
        access = "protected";
        break;
    case Node::Private:
        // Do not include private non-internal nodes in the index.
        // (Internal public and protected nodes are marked as private
        // by qdoc. We can check their internal status to determine
        // whether they were really private to begin with.)
        if (node->status() == Node::Internal && generateInternalNodes)
            access = "internal";
        else
            return false;
        break;
    default:
        return false;
    }

    QString objName = node->name();

    // Special case: only the root node should have an empty name.
    if (objName.isEmpty() && node != root())
        return false;

    writer.writeStartElement(nodeName);

    QXmlStreamAttributes attributes;
    writer.writeAttribute("access", access);

    if (node->type() != Node::Fake) {
        QString threadSafety;
        switch (node->threadSafeness()) {
        case Node::NonReentrant:
            threadSafety = "non-reentrant";
            break;
        case Node::Reentrant:
            threadSafety = "reentrant";
            break;
        case Node::ThreadSafe:
            threadSafety = "thread safe";
            break;
        case Node::UnspecifiedSafeness:
        default:
            threadSafety = "unspecified";
            break;
        }
        writer.writeAttribute("threadsafety", threadSafety);
    }

    QString status;
    switch (node->status()) {
    case Node::Compat:
        status = "compat";
        break;
    case Node::Obsolete:
        status = "obsolete";
        break;
    case Node::Deprecated:
        status = "deprecated";
        break;
    case Node::Preliminary:
        status = "preliminary";
        break;
    case Node::Commendable:
        status = "commendable";
        break;
    case Node::Internal:
        status = "internal";
        break;
    case Node::Main:
    default:
        status = "main";
        break;
    }
    writer.writeAttribute("status", status);

    writer.writeAttribute("name", objName);
    QString fullName = node->fullDocumentName();
    if (fullName != objName)
        writer.writeAttribute("fullname", fullName);
    QString href = node->outputSubdirectory();
    if (!href.isEmpty())
        href.append(QLatin1Char('/'));
    href.append(Generator::fullDocumentLocation(node));
    writer.writeAttribute("href", href);
    if ((node->type() != Node::Fake) && (!node->isQmlNode()))
        writer.writeAttribute("location", node->location().fileName());

    switch (node->type()) {

    case Node::Class:
    {
        // Classes contain information about their base classes.

        const ClassNode* classNode = static_cast<const ClassNode*>(node);
        QList<RelatedClass> bases = classNode->baseClasses();
        QSet<QString> baseStrings;
        foreach (const RelatedClass& related, bases) {
            ClassNode* baseClassNode = related.node;
            baseStrings.insert(baseClassNode->name());
        }
        writer.writeAttribute("bases", QStringList(baseStrings.toList()).join(","));
        writer.writeAttribute("module", node->moduleName());
    }
        break;

    case Node::Namespace:
        writer.writeAttribute("module", node->moduleName());
        break;

    case Node::Fake:
    {
        /*
              Fake nodes (such as manual pages) contain subtypes,
              titles and other attributes.
            */

        const FakeNode* fakeNode = static_cast<const FakeNode*>(node);
        switch (fakeNode->subType()) {
        case Node::Example:
            writer.writeAttribute("subtype", "example");
            break;
        case Node::HeaderFile:
            writer.writeAttribute("subtype", "header");
            break;
        case Node::File:
            writer.writeAttribute("subtype", "file");
            break;
        case Node::Group:
            writer.writeAttribute("subtype", "group");
            break;
        case Node::Module:
            writer.writeAttribute("subtype", "module");
            break;
        case Node::Page:
            writer.writeAttribute("subtype", "page");
            break;
        case Node::ExternalPage:
            writer.writeAttribute("subtype", "externalpage");
            break;
        case Node::QmlClass:
            //writer.writeAttribute("subtype", "qmlclass");
            break;
        case Node::QmlBasicType:
            //writer.writeAttribute("subtype", "qmlbasictype");
            break;
        default:
            break;
        }
        writer.writeAttribute("title", fakeNode->title());
        writer.writeAttribute("fulltitle", fakeNode->fullTitle());
        writer.writeAttribute("subtitle", fakeNode->subTitle());
        writer.writeAttribute("location", fakeNode->doc().location().fileName());
    }
        break;

    case Node::Function:
    {
        /*
              Function nodes contain information about the type of
              function being described.
            */

        const FunctionNode* functionNode =
                static_cast<const FunctionNode*>(node);

        switch (functionNode->virtualness()) {
        case FunctionNode::NonVirtual:
            writer.writeAttribute("virtual", "non");
            break;
        case FunctionNode::ImpureVirtual:
            writer.writeAttribute("virtual", "impure");
            break;
        case FunctionNode::PureVirtual:
            writer.writeAttribute("virtual", "pure");
            break;
        default:
            break;
        }
        switch (functionNode->metaness()) {
        case FunctionNode::Plain:
            writer.writeAttribute("meta", "plain");
            break;
        case FunctionNode::Signal:
            writer.writeAttribute("meta", "signal");
            break;
        case FunctionNode::Slot:
            writer.writeAttribute("meta", "slot");
            break;
        case FunctionNode::Ctor:
            writer.writeAttribute("meta", "constructor");
            break;
        case FunctionNode::Dtor:
            writer.writeAttribute("meta", "destructor");
            break;
        case FunctionNode::MacroWithParams:
            writer.writeAttribute("meta", "macrowithparams");
            break;
        case FunctionNode::MacroWithoutParams:
            writer.writeAttribute("meta", "macrowithoutparams");
            break;
        default:
            break;
        }
        writer.writeAttribute("const", functionNode->isConst()?"true":"false");
        writer.writeAttribute("static", functionNode->isStatic()?"true":"false");
        writer.writeAttribute("overload", functionNode->isOverload()?"true":"false");
        if (functionNode->isOverload())
            writer.writeAttribute("overload-number", QString::number(functionNode->overloadNumber()));
        if (functionNode->relates())
            writer.writeAttribute("relates", functionNode->relates()->name());
        const PropertyNode* propertyNode = functionNode->associatedProperty();
        if (propertyNode)
            writer.writeAttribute("associated-property", propertyNode->name());
        writer.writeAttribute("type", functionNode->returnType());
    }
        break;

    case Node::QmlProperty:
    {
        QmlPropertyNode* qpn = static_cast<QmlPropertyNode*>(node);
        writer.writeAttribute("type", qpn->dataType());
        writer.writeAttribute("attached", qpn->isAttached() ? "true" : "false");
        writer.writeAttribute("writable", qpn->isWritable(this) ? "true" : "false");
    }
        break;
    case Node::Property:
    {
        const PropertyNode* propertyNode = static_cast<const PropertyNode*>(node);
        writer.writeAttribute("type", propertyNode->dataType());
        foreach (const Node* fnNode, propertyNode->getters()) {
            if (fnNode) {
                const FunctionNode* functionNode = static_cast<const FunctionNode*>(fnNode);
                writer.writeStartElement("getter");
                writer.writeAttribute("name", functionNode->name());
                writer.writeEndElement(); // getter
            }
        }
        foreach (const Node* fnNode, propertyNode->setters()) {
            if (fnNode) {
                const FunctionNode* functionNode = static_cast<const FunctionNode*>(fnNode);
                writer.writeStartElement("setter");
                writer.writeAttribute("name", functionNode->name());
                writer.writeEndElement(); // setter
            }
        }
        foreach (const Node* fnNode, propertyNode->resetters()) {
            if (fnNode) {
                const FunctionNode* functionNode = static_cast<const FunctionNode*>(fnNode);
                writer.writeStartElement("resetter");
                writer.writeAttribute("name", functionNode->name());
                writer.writeEndElement(); // resetter
            }
        }
        foreach (const Node* fnNode, propertyNode->notifiers()) {
            if (fnNode) {
                const FunctionNode* functionNode = static_cast<const FunctionNode*>(fnNode);
                writer.writeStartElement("notifier");
                writer.writeAttribute("name", functionNode->name());
                writer.writeEndElement(); // notifier
            }
        }
    }
        break;

    case Node::Variable:
    {
        const VariableNode* variableNode =
                static_cast<const VariableNode*>(node);
        writer.writeAttribute("type", variableNode->dataType());
        writer.writeAttribute("static",
                              variableNode->isStatic() ? "true" : "false");
    }
        break;
    default:
        break;
    }

    // Inner nodes and function nodes contain child nodes of some sort, either
    // actual child nodes or function parameters. For these, we close the
    // opening tag, create child elements, then add a closing tag for the
    // element. Elements for all other nodes are closed in the opening tag.

    if (node->isInnerNode()) {

        const InnerNode* inner = static_cast<const InnerNode*>(node);

        // For internal pages, we canonicalize the target, keyword and content
        // item names so that they can be used by qdoc for other sets of
        // documentation.
        // The reason we do this here is that we don't want to ruin
        // externally composed indexes, containing non-qdoc-style target names
        // when reading in indexes.

        if (inner->doc().hasTargets()) {
            bool external = false;
            if (inner->type() == Node::Fake) {
                const FakeNode* fakeNode = static_cast<const FakeNode*>(inner);
                if (fakeNode->subType() == Node::ExternalPage)
                    external = true;
            }

            foreach (const Atom* target, inner->doc().targets()) {
                QString targetName = target->string();
                if (!external)
                    targetName = Doc::canonicalTitle(targetName);

                writer.writeStartElement("target");
                writer.writeAttribute("name", targetName);
                writer.writeEndElement(); // target
            }
        }
        if (inner->doc().hasKeywords()) {
            foreach (const Atom* keyword, inner->doc().keywords()) {
                writer.writeStartElement("keyword");
                writer.writeAttribute("name",
                                      Doc::canonicalTitle(keyword->string()));
                writer.writeEndElement(); // keyword
            }
        }
        if (inner->doc().hasTableOfContents()) {
            for (int i = 0; i < inner->doc().tableOfContents().size(); ++i) {
                Atom* item = inner->doc().tableOfContents()[i];
                int level = inner->doc().tableOfContentsLevels()[i];

                QString title = Text::sectionHeading(item).toString();
                writer.writeStartElement("contents");
                writer.writeAttribute("name", Doc::canonicalTitle(title));
                writer.writeAttribute("title", title);
                writer.writeAttribute("level", QString::number(level));
                writer.writeEndElement(); // contents
            }
        }

    }
    else if (node->type() == Node::Function) {

        const FunctionNode* functionNode = static_cast<const FunctionNode*>(node);
        // Write a signature attribute for convenience.
        QStringList signatureList;
        QStringList resolvedParameters;

        foreach (const Parameter& parameter, functionNode->parameters()) {
            QString leftType = parameter.leftType();
            const Node* leftNode = const_cast<Tree*>(this)->findNode(parameter.leftType().split("::"),
                                                      0, SearchBaseClasses|NonFunction);
            if (!leftNode || leftNode->type() != Node::Typedef) {
                leftNode = const_cast<Tree*>(this)->findNode(parameter.leftType().split("::"),
                            node->parent(), SearchBaseClasses|NonFunction);
            }
            if (leftNode && leftNode->type() == Node::Typedef) {
                if (leftNode->type() == Node::Typedef) {
                    const TypedefNode* typedefNode =
                            static_cast<const TypedefNode*>(leftNode);
                    if (typedefNode->associatedEnum()) {
                        leftType = "QFlags<" + typedefNode->associatedEnum()->fullDocumentName() + QLatin1Char('>');
                    }
                }
                else
                    leftType = leftNode->fullDocumentName();
            }
            resolvedParameters.append(leftType);
            signatureList.append(leftType + QLatin1Char(' ') + parameter.name());
        }

        QString signature = functionNode->name()+QLatin1Char('(')+signatureList.join(", ")+QLatin1Char(')');
        if (functionNode->isConst())
            signature += " const";
        writer.writeAttribute("signature", signature);

        for (int i = 0; i < functionNode->parameters().size(); ++i) {
            Parameter parameter = functionNode->parameters()[i];
            writer.writeStartElement("parameter");
            writer.writeAttribute("left", resolvedParameters[i]);
            writer.writeAttribute("right", parameter.rightType());
            writer.writeAttribute("name", parameter.name());
            writer.writeAttribute("default", parameter.defaultValue());
            writer.writeEndElement(); // parameter
        }

    }
    else if (node->type() == Node::Enum) {

        const EnumNode* enumNode = static_cast<const EnumNode*>(node);
        if (enumNode->flagsType()) {
            writer.writeAttribute("typedef",enumNode->flagsType()->fullDocumentName());
        }
        foreach (const EnumItem& item, enumNode->items()) {
            writer.writeStartElement("value");
            writer.writeAttribute("name", item.name());
            writer.writeAttribute("value", item.value());
            writer.writeEndElement(); // value
        }

    }
    else if (node->type() == Node::Typedef) {

        const TypedefNode* typedefNode = static_cast<const TypedefNode*>(node);
        if (typedefNode->associatedEnum()) {
            writer.writeAttribute("enum",typedefNode->associatedEnum()->fullDocumentName());
        }
    }

    return true;
}


/*!
    Returns true if the node \a n1 is less than node \a n2.
    The comparison is performed by comparing properties of the nodes in order
    of increasing complexity.
*/
bool compareNodes(const Node* n1, const Node* n2)
{
    // Private nodes can occur in any order since they won't normally be
    // written to the index.
    if (n1->access() == Node::Private && n2->access() == Node::Private)
        return true;

    if (n1->location().filePath() < n2->location().filePath())
        return true;
    else if (n1->location().filePath() > n2->location().filePath())
        return false;

    if (n1->type() < n2->type())
        return true;
    else if (n1->type() > n2->type())
        return false;

    if (n1->name() < n2->name())
        return true;
    else if (n1->name() > n2->name())
        return false;

    if (n1->access() < n2->access())
        return true;
    else if (n1->access() > n2->access())
        return false;

    if (n1->type() == Node::Function && n2->type() == Node::Function) {
        const FunctionNode* f1 = static_cast<const FunctionNode*>(n1);
        const FunctionNode* f2 = static_cast<const FunctionNode*>(n2);

        if (f1->isConst() < f2->isConst())
            return true;
        else if (f1->isConst() > f2->isConst())
            return false;

        if (f1->signature() < f2->signature())
            return true;
        else if (f1->signature() > f2->signature())
            return false;
    }

    if (n1->type() == Node::Fake && n2->type() == Node::Fake) {
        const FakeNode* f1 = static_cast<const FakeNode*>(n1);
        const FakeNode* f2 = static_cast<const FakeNode*>(n2);
        if (f1->fullTitle() < f2->fullTitle())
            return true;
        else if (f1->fullTitle() > f2->fullTitle())
            return false;
    }

    return false;
}

/*!
    Generate index sections for the child nodes of the given \a node
    using the \a writer specified. If \a generateInternalNodes is true,
    nodes marked as internal will be included in the index; otherwise,
    they will be omitted.
*/
void Tree::generateIndexSections(QXmlStreamWriter& writer,
                                 Node* node,
                                 bool generateInternalNodes)
{
    if (generateIndexSection(writer, node, generateInternalNodes)) {

        if (node->isInnerNode()) {
            const InnerNode* inner = static_cast<const InnerNode*>(node);

            NodeList cnodes = inner->childNodes();
            qSort(cnodes.begin(), cnodes.end(), compareNodes);

            foreach (Node* child, cnodes) {
                /*
                  Don't generate anything for a QML property group node.
                  It is just a place holder for a collection of QML property
                  nodes. Recurse to its children, which are the QML property
                  nodes.
                 */
                if (child->subType() == Node::QmlPropertyGroup) {
                    const InnerNode* pgn = static_cast<const InnerNode*>(child);
                    foreach (Node* c, pgn->childNodes()) {
                        generateIndexSections(writer, c, generateInternalNodes);
                    }
                }
                else
                    generateIndexSections(writer, child, generateInternalNodes);
            }

            /*
            foreach (const Node* child, inner->relatedNodes()) {
                QDomElement childElement = generateIndexSections(document, child);
                element.appendChild(childElement);
            }
*/
        }
        writer.writeEndElement();
    }
}

/*!
  Outputs an index file.
 */
void Tree::generateIndex(const QString& fileName,
                         const QString& url,
                         const QString& title,
                         bool generateInternalNodes)
{
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text))
        return ;

    QXmlStreamWriter writer(&file);
    writer.setAutoFormatting(true);
    writer.writeStartDocument();
    writer.writeDTD("<!DOCTYPE QDOCINDEX>");

    writer.writeStartElement("INDEX");
    writer.writeAttribute("url", url);
    writer.writeAttribute("title", title);
    writer.writeAttribute("version", version());

    generateIndexSections(writer, root(), generateInternalNodes);

    writer.writeEndElement(); // INDEX
    writer.writeEndElement(); // QDOCINDEX
    writer.writeEndDocument();
    file.close();
}

/*!
  Generate the tag file section with the given \a writer for the \a node
  specified, returning true if an element was written; otherwise returns
  false.
 */
void Tree::generateTagFileCompounds(QXmlStreamWriter& writer, const InnerNode* inner)
{
    foreach (const Node* node, inner->childNodes()) {

        if (!node->url().isEmpty())
            continue;

        QString kind;
        switch (node->type()) {
        case Node::Namespace:
            kind = "namespace";
            break;
        case Node::Class:
            kind = "class";
            break;
        case Node::Enum:
        case Node::Typedef:
        case Node::Property:
        case Node::Function:
        case Node::Variable:
        default:
            continue;
        }

        QString access;
        switch (node->access()) {
        case Node::Public:
            access = "public";
            break;
        case Node::Protected:
            access = "protected";
            break;
        case Node::Private:
        default:
            continue;
        }

        QString objName = node->name();

        // Special case: only the root node should have an empty name.
        if (objName.isEmpty() && node != root())
            continue;

        // *** Write the starting tag for the element here. ***
        writer.writeStartElement("compound");
        writer.writeAttribute("kind", kind);

        if (node->type() == Node::Class) {
            writer.writeTextElement("name", node->fullDocumentName());
            writer.writeTextElement("filename", Generator::fullDocumentLocation(node,true));

            // Classes contain information about their base classes.
            const ClassNode* classNode = static_cast<const ClassNode*>(node);
            QList<RelatedClass> bases = classNode->baseClasses();
            foreach (const RelatedClass& related, bases) {
                ClassNode* baseClassNode = related.node;
                writer.writeTextElement("base", baseClassNode->name());
            }

            // Recurse to write all members.
            generateTagFileMembers(writer, static_cast<const InnerNode*>(node));
            writer.writeEndElement();

            // Recurse to write all compounds.
            generateTagFileCompounds(writer, static_cast<const InnerNode*>(node));
        } else {
            writer.writeTextElement("name", node->fullDocumentName());
            writer.writeTextElement("filename", Generator::fullDocumentLocation(node,true));

            // Recurse to write all members.
            generateTagFileMembers(writer, static_cast<const InnerNode*>(node));
            writer.writeEndElement();

            // Recurse to write all compounds.
            generateTagFileCompounds(writer, static_cast<const InnerNode*>(node));
        }
    }
}

/*!
 */
void Tree::generateTagFileMembers(QXmlStreamWriter& writer, const InnerNode* inner)
{
    foreach (const Node* node, inner->childNodes()) {

        if (!node->url().isEmpty())
            continue;

        QString nodeName;
        QString kind;
        switch (node->type()) {
        case Node::Enum:
            nodeName = "member";
            kind = "enum";
            break;
        case Node::Typedef:
            nodeName = "member";
            kind = "typedef";
            break;
        case Node::Property:
            nodeName = "member";
            kind = "property";
            break;
        case Node::Function:
            nodeName = "member";
            kind = "function";
            break;
        case Node::Namespace:
            nodeName = "namespace";
            break;
        case Node::Class:
            nodeName = "class";
            break;
        case Node::Variable:
        default:
            continue;
        }

        QString access;
        switch (node->access()) {
        case Node::Public:
            access = "public";
            break;
        case Node::Protected:
            access = "protected";
            break;
        case Node::Private:
        default:
            continue;
        }

        QString objName = node->name();

        // Special case: only the root node should have an empty name.
        if (objName.isEmpty() && node != root())
            continue;

        // *** Write the starting tag for the element here. ***
        writer.writeStartElement(nodeName);
        if (!kind.isEmpty())
            writer.writeAttribute("kind", kind);

        switch (node->type()) {

        case Node::Class:
            writer.writeCharacters(node->fullDocumentName());
            writer.writeEndElement();
            break;
        case Node::Namespace:
            writer.writeCharacters(node->fullDocumentName());
            writer.writeEndElement();
            break;
        case Node::Function:
        {
            /*
                  Function nodes contain information about
                  the type of function being described.
                */

            const FunctionNode* functionNode =
                    static_cast<const FunctionNode*>(node);
            writer.writeAttribute("protection", access);

            switch (functionNode->virtualness()) {
            case FunctionNode::NonVirtual:
                writer.writeAttribute("virtualness", "non");
                break;
            case FunctionNode::ImpureVirtual:
                writer.writeAttribute("virtualness", "virtual");
                break;
            case FunctionNode::PureVirtual:
                writer.writeAttribute("virtual", "pure");
                break;
            default:
                break;
            }
            writer.writeAttribute("static",
                                  functionNode->isStatic() ? "yes" : "no");

            if (functionNode->virtualness() == FunctionNode::NonVirtual)
                writer.writeTextElement("type", functionNode->returnType());
            else
                writer.writeTextElement("type",
                                        "virtual " + functionNode->returnType());

            writer.writeTextElement("name", objName);
            QStringList pieces = Generator::fullDocumentLocation(node,true).split(QLatin1Char('#'));
            writer.writeTextElement("anchorfile", pieces[0]);
            writer.writeTextElement("anchor", pieces[1]);

            // Write a signature attribute for convenience.
            QStringList signatureList;

            foreach (const Parameter& parameter, functionNode->parameters()) {
                QString leftType = parameter.leftType();
                const Node* leftNode = const_cast<Tree*>(this)->findNode(parameter.leftType().split("::"),
                                                                         0, SearchBaseClasses|NonFunction);
                if (!leftNode || leftNode->type() != Node::Typedef) {
                    leftNode = const_cast<Tree*>(this)->findNode(parameter.leftType().split("::"),
                                                      node->parent(), SearchBaseClasses|NonFunction);
                }
                if (leftNode && leftNode->type() == Node::Typedef) {
                    const TypedefNode* typedefNode = static_cast<const TypedefNode*>(leftNode);
                    if (typedefNode->associatedEnum()) {
                        leftType = "QFlags<" + typedefNode->associatedEnum()->fullDocumentName() + QLatin1Char('>');
                    }
                }
                signatureList.append(leftType + QLatin1Char(' ') + parameter.name());
            }

            QString signature = QLatin1Char('(')+signatureList.join(", ")+QLatin1Char(')');
            if (functionNode->isConst())
                signature += " const";
            if (functionNode->virtualness() == FunctionNode::PureVirtual)
                signature += " = 0";
            writer.writeTextElement("arglist", signature);
        }
            writer.writeEndElement(); // member
            break;

        case Node::Property:
        {
            const PropertyNode* propertyNode = static_cast<const PropertyNode*>(node);
            writer.writeAttribute("type", propertyNode->dataType());
            writer.writeTextElement("name", objName);
            QStringList pieces = Generator::fullDocumentLocation(node,true).split(QLatin1Char('#'));
            writer.writeTextElement("anchorfile", pieces[0]);
            writer.writeTextElement("anchor", pieces[1]);
            writer.writeTextElement("arglist", "");
        }
            writer.writeEndElement(); // member
            break;

        case Node::Enum:
        {
            const EnumNode* enumNode = static_cast<const EnumNode*>(node);
            writer.writeTextElement("name", objName);
            QStringList pieces = Generator::fullDocumentLocation(node).split(QLatin1Char('#'));
            writer.writeTextElement("anchor", pieces[1]);
            writer.writeTextElement("arglist", "");
            writer.writeEndElement(); // member

            for (int i = 0; i < enumNode->items().size(); ++i) {
                EnumItem item = enumNode->items().value(i);
                writer.writeStartElement("member");
                writer.writeAttribute("name", item.name());
                writer.writeTextElement("anchor", pieces[1]);
                writer.writeTextElement("arglist", "");
                writer.writeEndElement(); // member
            }
        }
            break;

        case Node::Typedef:
        {
            const TypedefNode* typedefNode = static_cast<const TypedefNode*>(node);
            if (typedefNode->associatedEnum())
                writer.writeAttribute("type", typedefNode->associatedEnum()->fullDocumentName());
            else
                writer.writeAttribute("type", "");
            writer.writeTextElement("name", objName);
            QStringList pieces = Generator::fullDocumentLocation(node,true).split(QLatin1Char('#'));
            writer.writeTextElement("anchorfile", pieces[0]);
            writer.writeTextElement("anchor", pieces[1]);
            writer.writeTextElement("arglist", "");
        }
            writer.writeEndElement(); // member
            break;

        case Node::Variable:
        default:
            break;
        }
    }
}

/*!
  Writes a tag file named \a fileName.
 */
void Tree::generateTagFile(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text))
        return ;

    QXmlStreamWriter writer(&file);
    writer.setAutoFormatting(true);
    writer.writeStartDocument();

    writer.writeStartElement("tagfile");

    generateTagFileCompounds(writer, root());

    writer.writeEndElement(); // tagfile
    writer.writeEndDocument();
    file.close();
}

/*!
 */
void Tree::addExternalLink(const QString& url, const Node* relative)
{
    FakeNode* fakeNode = new FakeNode(root(), url, Node::ExternalPage, Node::ArticlePage);
    fakeNode->setAccess(Node::Public);

    // Create some content for the node.
    QSet<QString> emptySet;
    Location location(relative->doc().location());
    Doc doc(location, location, " ", emptySet); // placeholder
    fakeNode->setDoc(doc);
}

/*!
  Find the node with the specified \a path name that is of
  the specified \a type and \a subtype. Begin the search at
  the \a start node. If the \a start node is 0, begin the
  search at the tree root. \a subtype is not used unless
  \a type is \c{Fake}.
 */
Node* Tree::findNodeByNameAndType(const QStringList& path,
                                  Node::Type type,
                                  Node::SubType subtype,
                                  Node* start,
                                  bool acceptCollision)
{
    if (!start)
        start = const_cast<NamespaceNode*>(root());
    Node* result = findNodeRecursive(path, 0, start, type, subtype, acceptCollision);
    return result;
}

#if 0
    if (result)
        qDebug() << "FOUND:" << path << Node::nodeTypeString(type)
                 << Node::nodeSubtypeString(subtype);
    else
        qDebug() << "NOT FOUND:" << path << Node::nodeTypeString(type)
                 << Node::nodeSubtypeString(subtype);
#endif

/*!
  Recursive search for a node identified by \a path. Each
  path element is a name. \a pathIndex specifies the index
  of the name in \a path to try to match. \a start is the
  node whose children shoulod be searched for one that has
  that name. Each time a match is found, increment the
  \a pathIndex and call this function recursively.

  If the end of the path is reached (i.e. if a matching
  node is found for each name in the \a path), the \a type
  must match the type of the last matching node, and if the
  type is \e{Fake}, the \a subtype must match as well.

  If the algorithm is successful, the pointer to the final
  node is returned. Otherwise 0 is returned.
 */
Node* Tree::findNodeRecursive(const QStringList& path,
                              int pathIndex,
                              Node* start,
                              Node::Type type,
                              Node::SubType subtype,
                              bool acceptCollision)
{
    if (!start || path.isEmpty())
        return 0; // no place to start, or nothing to search for.
    if (start->isLeaf()) {
        if (pathIndex >= path.size())
            return start; // found a match.
        return 0; // premature leaf
    }
    if (pathIndex >= path.size())
        return 0; // end of search path.

    InnerNode* current = static_cast<InnerNode*>(start);
    const NodeList& children = current->childNodes();
    const QString& name = path.at(pathIndex);
    for (int i=0; i<children.size(); ++i) {
        Node* n = children.at(i);
        if (!n)
            continue;
        if (n->isQmlPropertyGroup()) {
            if (type == Node::QmlProperty) {
                n = findNodeRecursive(path, pathIndex, n, type, subtype);
                if (n)
                    return n;
            }
        }
        else if (n->name() == name) {
            if (pathIndex+1 >= path.size()) {
                if (n->type() == type) {
                    if (type == Node::Fake) {
                        if (n->subType() == subtype)
                            return n;
                        else if (n->subType() == Node::Collision && acceptCollision)
                            return n;
                        else if (subtype == Node::NoSubType)
                            return n; // don't care what subtype is.
                        return 0;
                    }
                    else
                        return n;
                }
                else if (n->isCollisionNode()) {
                    if (acceptCollision)
                        return n;
                    return findNodeRecursive(path, pathIndex, n, type, subtype);
                }
                else
                    return 0;
            }
            else { // Not at the end of the path.
                n = findNodeRecursive(path, pathIndex+1, n, type, subtype);
                if (n)
                    return n;
            }
        }
    }
    return 0;
}

/*!
  Find the Enum type node named \a path. Begin the search at the
  \a start node. If the \a start node is 0, begin the search
  at the root of the tree. Only an Enum type node named \a path is
  acceptible. If one is not found, 0 is returned.
 */
EnumNode* Tree::findEnumNode(const QStringList& path, Node* start)
{
    if (!start)
        start = const_cast<NamespaceNode*>(root());
    return static_cast<EnumNode*>(findNodeRecursive(path, 0, start, Node::Enum, Node::NoSubType));
}

/*!
  Find the C++ class node named \a path. Begin the search at the
  \a start node. If the \a start node is 0, begin the search
  at the root of the tree. Only a C++ class node named \a path is
  acceptible. If one is not found, 0 is returned.
 */
ClassNode* Tree::findClassNode(const QStringList& path, Node* start)
{
    if (!start)
        start = const_cast<NamespaceNode*>(root());
    return static_cast<ClassNode*>(findNodeRecursive(path, 0, start, Node::Class, Node::NoSubType));
}

/*!
  Find the Qml class node named \a path. Begin the search at the
  \a start node. If the \a start node is 0, begin the search
  at the root of the tree. Only a Qml class node named \a path is
  acceptible. If one is not found, 0 is returned.
 */
QmlClassNode* Tree::findQmlClassNode(const QStringList& path, Node* start)
{
    /*
      If the path contains one or two double colons ("::"),
      check first to see if the first two path strings refer
      to a QML element. If yes, that reference identifies a
      QML class node.
    */
    if (path.size() >= 2) {
        QmlClassNode* qcn = QmlClassNode::moduleMap.value(path[0]+ "::" +path[1]);
        if (qcn)
            return qcn;
    }

    if (!start)
        start = const_cast<NamespaceNode*>(root());
    return static_cast<QmlClassNode*>(findNodeRecursive(path, 0, start, Node::Fake, Node::QmlClass));
}

/*!
  Find the Namespace node named \a path. Begin the search at the
  \a start node. If the \a start node is 0, begin the search
  at the root of the tree. Only a Namespace node named \a path is
  acceptible. If one is not found, 0 is returned.
 */
NamespaceNode* Tree::findNamespaceNode(const QStringList& path, Node* start)
{
    if (!start)
        start = const_cast<NamespaceNode*>(root());
    return static_cast<NamespaceNode*>(findNodeRecursive(path, 0, start, Node::Namespace, Node::NoSubType));
}

/*!
  Find the Group node named \a path. Begin the search at the
  \a start node. If the \a start node is 0, begin the search
  at the root of the tree. Only a Group node named \a path is
  acceptible. If one is not found, 0 is returned.
 */
FakeNode* Tree::findGroupNode(const QStringList& path, Node* start)
{
    if (!start)
        start = const_cast<NamespaceNode*>(root());
    return static_cast<FakeNode*>(findNodeRecursive(path, 0, start, Node::Fake, Node::Group));
}

/*!
  Find the Qml module node named \a path. Begin the search at the
  \a start node. If the \a start node is 0, begin the search
  at the root of the tree. Only a Qml module node named \a path is
  acceptible. If one is not found, 0 is returned.
 */
FakeNode* Tree::findQmlModuleNode(const QStringList& path, Node* start)
{
    if (!start)
        start = const_cast<NamespaceNode*>(root());
    return static_cast<FakeNode*>(findNodeRecursive(path, 0, start, Node::Fake, Node::QmlModule));
}

QT_END_NAMESPACE

#if 0
const Node* Tree::findNodeXXX(const QStringList& path, bool qml) const
{
    const Node* current = root();
    do {
        const Node* node = current;
        int i;
        int start_idx = 0;

        /*
          If the path contains one or two double colons ("::"),
          check first to see if the first two path strings refer
          to a QML element. If yes, that reference identifies a
          QML class node.
        */
        if (qml && path.size() >= 2) {
            QmlClassNode* qcn = QmlClassNode::moduleMap.value(path[0]+ "::" +path[1]);
            if (qcn) {
                node = qcn;
                if (path.size() == 2)
                    return node;
                start_idx = 2;
            }
        }

        for (i = start_idx; i < path.size(); ++i) {
            if (node == 0 || !node->isInnerNode())
                break;

            const Node* next = static_cast<const InnerNode*>(node)->findChildNodeByName(path.at(i), qml);
            node = next;
        }
        if (node && i == path.size()) {
            if (node->subType() != Node::QmlPropertyGroup) {
                if (node->subType() == Node::Collision) {
                    node = node->applyModuleIdentifier(start);
                }
                return node;
            }
        }
        current = current->parent();
    } while (current);

    return 0;
}
#endif