summaryrefslogtreecommitdiffstats
path: root/tools/linguist/lupdate/cpp.cpp
blob: ac8abf6fc5429c17cb4b1569b513d32964faa70d (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
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "lupdate.h"

#include <translator.h>

#include <QtCore/QBitArray>
#include <QtCore/QDebug>
#include <QtCore/QFileInfo>
#include <QtCore/QStack>
#include <QtCore/QString>
#include <QtCore/QTextCodec>
#include <QtCore/QTextStream>
#include <QtCore/QCoreApplication>

#include <iostream>

#include <ctype.h>              // for isXXX()

QT_BEGIN_NAMESPACE

class LU {
    Q_DECLARE_TR_FUNCTIONS(LUpdate)
};

/* qmake ignore Q_OBJECT */

static QString MagicComment(QLatin1String("TRANSLATOR"));

#define STRING(s) static QString str##s(QLatin1String(#s))

//#define DIAGNOSE_RETRANSLATABILITY // FIXME: should make a runtime option of this

class HashString {
public:
    HashString() : m_hash(0x80000000) {}
    explicit HashString(const QString &str) : m_str(str), m_hash(0x80000000) {}
    void setValue(const QString &str) { m_str = str; m_hash = 0x80000000; }
    const QString &value() const { return m_str; }
    bool operator==(const HashString &other) const { return m_str == other.m_str; }
private:
    QString m_str;
    // qHash() of a QString is only 28 bits wide, so we can use
    // the highest bit(s) as the "hash valid" flag.
    mutable uint m_hash;
    friend uint qHash(const HashString &str);
};

uint qHash(const HashString &str)
{
    if (str.m_hash & 0x80000000)
        str.m_hash = qHash(str.m_str);
    return str.m_hash;
}

class HashStringList {
public:
    explicit HashStringList(const QList<HashString> &list) : m_list(list), m_hash(0x80000000) {}
    const QList<HashString> &value() const { return m_list; }
    bool operator==(const HashStringList &other) const { return m_list == other.m_list; }
private:
    QList<HashString> m_list;
    mutable uint m_hash;
    friend uint qHash(const HashStringList &list);
};

uint qHash(const HashStringList &list)
{
    if (list.m_hash & 0x80000000) {
        uint hash = 0;
        foreach (const HashString &qs, list.m_list) {
            hash ^= qHash(qs) ^ 0x0ad9f526;
            hash = ((hash << 13) & 0x0fffffff) | (hash >> 15);
        }
        list.m_hash = hash;
    }
    return list.m_hash;
}

typedef QList<HashString> NamespaceList;

struct Namespace {

    Namespace() :
            classDef(this),
            hasTrFunctions(false), complained(false)
    {}
    ~Namespace()
    {
        qDeleteAll(children);
    }

    QHash<HashString, Namespace *> children;
    QHash<HashString, NamespaceList> aliases;
    QList<HashStringList> usings;

    // Class declarations set no flags and create no namespaces, so they are ignored.
    // Class definitions may appear multiple times - but only because we are trying to
    // "compile" all sources irrespective of build configuration.
    // Nested classes may be forward-declared inside a definition, and defined in another file.
    // The latter will detach the class' child list, so clones need a backlink to the original
    // definition (either one in case of multiple definitions).
    // Namespaces can have tr() functions as well, so we need to track parent definitions for
    // them as well. The complication is that we may have to deal with a forrest instead of
    // a tree - in that case the parent will be arbitrary. However, it seem likely that
    // Q_DECLARE_TR_FUNCTIONS would be used either in "class-like" namespaces with a central
    // header or only locally in a file.
    Namespace *classDef;

    QString trQualification;

    bool hasTrFunctions;
    bool complained; // ... that tr functions are missing.
};

static int nextFileId;

class VisitRecorder {
public:
    VisitRecorder()
    {
        m_ba.resize(nextFileId);
    }
    bool tryVisit(int fileId)
    {
        if (m_ba.at(fileId))
            return false;
        m_ba[fileId] = true;
        return true;
    }
private:
    QBitArray m_ba;
};

struct ParseResults {
    int fileId;
    Namespace rootNamespace;
    QSet<const ParseResults *> includes;
};

typedef QHash<QString, const ParseResults *> ParseResultHash;
typedef QHash<QString, const Translator *> TranslatorHash;

class CppFiles {

public:
    static const ParseResults *getResults(const QString &cleanFile);
    static void setResults(const QString &cleanFile, const ParseResults *results);
    static const Translator *getTranslator(const QString &cleanFile);
    static void setTranslator(const QString &cleanFile, const Translator *results);
    static bool isBlacklisted(const QString &cleanFile);
    static void setBlacklisted(const QString &cleanFile);

private:
    static ParseResultHash &parsedFiles();
    static TranslatorHash &translatedFiles();
    static QSet<QString> &blacklistedFiles();
};

class CppParser {

public:
    CppParser(ParseResults *results = 0);
    void setInput(const QString &in);
    void setInput(QTextStream &ts, const QString &fileName);
    void setTranslator(Translator *_tor) { tor = _tor; }
    void parse(const QString &initialContext, ConversionData &cd, QSet<QString> &inclusions);
    void parseInternal(ConversionData &cd, QSet<QString> &inclusions);
    const ParseResults *recordResults(bool isHeader);
    void deleteResults() { delete results; }

    struct SavedState {
        NamespaceList namespaces;
        QStack<int> namespaceDepths;
        NamespaceList functionContext;
        QString functionContextUnresolved;
        QString pendingContext;
    };

private:
    struct IfdefState {
        IfdefState() {}
        IfdefState(int _bracketDepth, int _braceDepth, int _parenDepth) :
            bracketDepth(_bracketDepth),
            braceDepth(_braceDepth),
            parenDepth(_parenDepth),
            elseLine(-1)
        {}

        SavedState state;
        int bracketDepth, bracketDepth1st;
        int braceDepth, braceDepth1st;
        int parenDepth, parenDepth1st;
        int elseLine;
    };

    std::ostream &yyMsg(int line = 0);

    uint getChar();
    uint getToken();
    bool getMacroArgs();
    bool match(uint t);
    bool matchString(QString *s);
    bool matchEncoding(bool *utf8);
    bool matchStringOrNull(QString *s);
    bool matchExpression();

    QString transcode(const QString &str, bool utf8);
    void recordMessage(
        int line, const QString &context, const QString &text, const QString &comment,
        const QString &extracomment, const QString &msgid, const TranslatorMessage::ExtraData &extra,
        bool utf8, bool plural);

    void processInclude(const QString &file, ConversionData &cd,
                        QSet<QString> &inclusions);

    void saveState(SavedState *state);
    void loadState(const SavedState *state);

    static QString stringifyNamespace(const NamespaceList &namespaces);
    static QStringList stringListifyNamespace(const NamespaceList &namespaces);
    typedef bool (CppParser::*VisitNamespaceCallback)(const Namespace *ns, void *context) const;
    bool visitNamespace(const NamespaceList &namespaces, int nsCount,
                        VisitNamespaceCallback callback, void *context,
                        VisitRecorder &vr, const ParseResults *rslt) const;
    bool visitNamespace(const NamespaceList &namespaces, int nsCount,
                        VisitNamespaceCallback callback, void *context) const;
    static QStringList stringListifySegments(const QList<HashString> &namespaces);
    bool qualifyOneCallbackOwn(const Namespace *ns, void *context) const;
    bool qualifyOneCallbackUsing(const Namespace *ns, void *context) const;
    bool qualifyOne(const NamespaceList &namespaces, int nsCnt, const HashString &segment,
                    NamespaceList *resolved, QSet<HashStringList> *visitedUsings) const;
    bool qualifyOne(const NamespaceList &namespaces, int nsCnt, const HashString &segment,
                    NamespaceList *resolved) const;
    bool fullyQualify(const NamespaceList &namespaces, int nsCnt,
                      const QList<HashString> &segments, bool isDeclaration,
                      NamespaceList *resolved, QStringList *unresolved) const;
    bool fullyQualify(const NamespaceList &namespaces,
                      const QList<HashString> &segments, bool isDeclaration,
                      NamespaceList *resolved, QStringList *unresolved) const;
    bool fullyQualify(const NamespaceList &namespaces,
                      const QString &segments, bool isDeclaration,
                      NamespaceList *resolved, QStringList *unresolved) const;
    bool findNamespaceCallback(const Namespace *ns, void *context) const;
    const Namespace *findNamespace(const NamespaceList &namespaces, int nsCount = -1) const;
    void enterNamespace(NamespaceList *namespaces, const HashString &name);
    void truncateNamespaces(NamespaceList *namespaces, int lenght);
    Namespace *modifyNamespace(NamespaceList *namespaces, bool haveLast = true);

    enum {
        Tok_Eof, Tok_class, Tok_friend, Tok_namespace, Tok_using, Tok_return,
        Tok_tr, Tok_trUtf8, Tok_translate, Tok_translateUtf8, Tok_trid,
        Tok_Q_OBJECT, Tok_Q_DECLARE_TR_FUNCTIONS,
        Tok_Ident, Tok_Comment, Tok_String, Tok_Arrow, Tok_Colon, Tok_ColonColon,
        Tok_Equals, Tok_LeftBracket, Tok_RightBracket,
        Tok_LeftBrace, Tok_RightBrace, Tok_LeftParen, Tok_RightParen, Tok_Comma, Tok_Semicolon,
        Tok_Null, Tok_Integer,
        Tok_QuotedInclude, Tok_AngledInclude,
        Tok_Other
    };

    // Tokenizer state
    QString yyFileName;
    int yyCh;
    bool yyAtNewline;
    bool yyCodecIsUtf8;
    bool yyForceUtf8;
    QString yyWord;
    qlonglong yyInteger;
    QStack<IfdefState> yyIfdefStack;
    int yyBracketDepth;
    int yyBraceDepth;
    int yyParenDepth;
    int yyLineNo;
    int yyCurLineNo;
    int yyBracketLineNo;
    int yyBraceLineNo;
    int yyParenLineNo;

    // the string to read from and current position in the string
    QTextCodec *yySourceCodec;
    QString yyInStr;
    const ushort *yyInPtr;

    // Parser state
    uint yyTok;

    NamespaceList namespaces;
    QStack<int> namespaceDepths;
    NamespaceList functionContext;
    QString functionContextUnresolved;
    QString prospectiveContext;
    QString pendingContext;
    ParseResults *results;
    Translator *tor;
    bool directInclude;

    SavedState savedState;
    int yyMinBraceDepth;
    bool inDefine;
};

CppParser::CppParser(ParseResults *_results)
{
    tor = 0;
    if (_results) {
        results = _results;
        directInclude = true;
    } else {
        results = new ParseResults;
        directInclude = false;
    }
    yyBracketDepth = 0;
    yyBraceDepth = 0;
    yyParenDepth = 0;
    yyCurLineNo = 1;
    yyBracketLineNo = 1;
    yyBraceLineNo = 1;
    yyParenLineNo = 1;
    yyAtNewline = true;
    yyMinBraceDepth = 0;
    inDefine = false;
}


std::ostream &CppParser::yyMsg(int line)
{
    return std::cerr << qPrintable(yyFileName) << ':' << (line ? line : yyLineNo) << ": ";
}

void CppParser::setInput(const QString &in)
{
    yyInStr = in;
    yyFileName = QString();
    yySourceCodec = 0;
    yyForceUtf8 = true;
}

void CppParser::setInput(QTextStream &ts, const QString &fileName)
{
    yyInStr = ts.readAll();
    yyFileName = fileName;
    yySourceCodec = ts.codec();
    yyForceUtf8 = false;
}

/*
  The first part of this source file is the C++ tokenizer.  We skip
  most of C++; the only tokens that interest us are defined here.
  Thus, the code fragment

      int main()
      {
          printf("Hello, world!\n");
          return 0;
      }

  is broken down into the following tokens (Tok_ omitted):

      Ident Ident LeftParen RightParen
      LeftBrace
          Ident LeftParen String RightParen Semicolon
          return Semicolon
      RightBrace.

  The 0 doesn't produce any token.
*/

uint CppParser::getChar()
{
    const ushort *uc = yyInPtr;
    forever {
        ushort c = *uc;
        if (!c) {
            yyInPtr = uc;
            return EOF;
        }
        ++uc;
        if (c == '\\') {
            ushort cc = *uc;
            if (cc == '\n') {
                ++yyCurLineNo;
                ++uc;
                continue;
            }
            if (cc == '\r') {
                ++yyCurLineNo;
                ++uc;
                if (*uc == '\n')
                    ++uc;
                continue;
            }
        }
        if (c == '\r') {
            if (*uc == '\n')
                ++uc;
            c = '\n';
            ++yyCurLineNo;
            yyAtNewline = true;
        } else if (c == '\n') {
            ++yyCurLineNo;
            yyAtNewline = true;
        } else if (c != ' ' && c != '\t' && c != '#') {
            yyAtNewline = false;
        }
        yyInPtr = uc;
        return c;
    }
}

// This ignores commas, parens and comments.
// IOW, it understands only a single, simple argument.
bool CppParser::getMacroArgs()
{
    // Failing this assertion would mean losing the preallocated buffer.
    Q_ASSERT(yyWord.isDetached());
    yyWord.resize(0);

    while (isspace(yyCh))
        yyCh = getChar();
    if (yyCh != '(')
        return false;
    do {
        yyCh = getChar();
    } while (isspace(yyCh));
    ushort *ptr = (ushort *)yyWord.unicode();
    while (yyCh != ')') {
        if (yyCh == EOF)
            return false;
        *ptr++ = yyCh;
        yyCh = getChar();
    }
    yyCh = getChar();
    for (; ptr != (ushort *)yyWord.unicode() && isspace(*(ptr - 1)); --ptr) ;
    yyWord.resize(ptr - (ushort *)yyWord.unicode());
    return true;
}

STRING(Q_OBJECT);
STRING(Q_DECLARE_TR_FUNCTIONS);
STRING(QT_TR_NOOP);
STRING(QT_TRID_NOOP);
STRING(QT_TRANSLATE_NOOP);
STRING(QT_TRANSLATE_NOOP3);
STRING(QT_TR_NOOP_UTF8);
STRING(QT_TRANSLATE_NOOP_UTF8);
STRING(QT_TRANSLATE_NOOP3_UTF8);
STRING(class);
// QTranslator::findMessage() has the same parameters as QApplication::translate()
STRING(findMessage);
STRING(friend);
STRING(namespace);
STRING(operator);
STRING(qtTrId);
STRING(return);
STRING(struct);
STRING(TR);
STRING(Tr);
STRING(tr);
STRING(trUtf8);
STRING(translate);
STRING(using);

uint CppParser::getToken()
{
  restart:
    // Failing this assertion would mean losing the preallocated buffer.
    Q_ASSERT(yyWord.isDetached());
    yyWord.resize(0);

    while (yyCh != EOF) {
        yyLineNo = yyCurLineNo;

        if (yyCh == '#' && yyAtNewline) {
            /*
              Early versions of lupdate complained about
              unbalanced braces in the following code:

                  #ifdef ALPHA
                      while (beta) {
                  #else
                      while (gamma) {
                  #endif
                          delta;
                      }

              The code contains, indeed, two opening braces for
              one closing brace; yet there's no reason to panic.

              The solution is to remember yyBraceDepth as it was
              when #if, #ifdef or #ifndef was met, and to set
              yyBraceDepth to that value when meeting #elif or
              #else.
            */
            do {
                yyCh = getChar();
            } while (isspace(yyCh) && yyCh != '\n');

            switch (yyCh) {
            case 'd': // define
                // Skip over the name of the define to avoid it being interpreted as c++ code
                do { // Rest of "define"
                    yyCh = getChar();
                    if (yyCh == EOF)
                        return Tok_Eof;
                    if (yyCh == '\n')
                        goto restart;
                } while (!isspace(yyCh));
                do { // Space beween "define" and macro name
                    yyCh = getChar();
                    if (yyCh == EOF)
                        return Tok_Eof;
                    if (yyCh == '\n')
                        goto restart;
                } while (isspace(yyCh));
                do { // Macro name
                    if (yyCh == '(') {
                        // Argument list. Follows the name without a space, and no
                        // paren nesting is possible.
                        do {
                            yyCh = getChar();
                            if (yyCh == EOF)
                                return Tok_Eof;
                            if (yyCh == '\n')
                                goto restart;
                        } while (yyCh != ')');
                        break;
                    }
                    yyCh = getChar();
                    if (yyCh == EOF)
                        return Tok_Eof;
                    if (yyCh == '\n')
                        goto restart;
                } while (!isspace(yyCh));
                do { // Shortcut the immediate newline case if no comments follow.
                    yyCh = getChar();
                    if (yyCh == EOF)
                        return Tok_Eof;
                    if (yyCh == '\n')
                        goto restart;
                } while (isspace(yyCh));

                saveState(&savedState);
                yyMinBraceDepth = yyBraceDepth;
                inDefine = true;
                goto restart;
            case 'i':
                yyCh = getChar();
                if (yyCh == 'f') {
                    // if, ifdef, ifndef
                    yyIfdefStack.push(IfdefState(yyBracketDepth, yyBraceDepth, yyParenDepth));
                    yyCh = getChar();
                } else if (yyCh == 'n') {
                    // include
                    do {
                        yyCh = getChar();
                    } while (yyCh != EOF && !isspace(yyCh));
                    do {
                        yyCh = getChar();
                    } while (isspace(yyCh));
                    int tChar;
                    if (yyCh == '"')
                        tChar = '"';
                    else if (yyCh == '<')
                        tChar = '>';
                    else
                        break;
                    ushort *ptr = (ushort *)yyWord.unicode();
                    forever {
                        yyCh = getChar();
                        if (yyCh == EOF || yyCh == '\n')
                            break;
                        if (yyCh == tChar) {
                            yyCh = getChar();
                            break;
                        }
                        *ptr++ = yyCh;
                    }
                    yyWord.resize(ptr - (ushort *)yyWord.unicode());
                    return (tChar == '"') ? Tok_QuotedInclude : Tok_AngledInclude;
                }
                break;
            case 'e':
                yyCh = getChar();
                if (yyCh == 'l') {
                    // elif, else
                    if (!yyIfdefStack.isEmpty()) {
                        IfdefState &is = yyIfdefStack.top();
                        if (is.elseLine != -1) {
                            if (yyBracketDepth != is.bracketDepth1st
                                || yyBraceDepth != is.braceDepth1st
                                || yyParenDepth != is.parenDepth1st)
                                yyMsg(is.elseLine)
                                    << qPrintable(LU::tr("Parenthesis/bracket/brace mismatch between "
                                                         "#if and #else branches; using #if branch\n"));
                        } else {
                            is.bracketDepth1st = yyBracketDepth;
                            is.braceDepth1st = yyBraceDepth;
                            is.parenDepth1st = yyParenDepth;
                            saveState(&is.state);
                        }
                        is.elseLine = yyLineNo;
                        yyBracketDepth = is.bracketDepth;
                        yyBraceDepth = is.braceDepth;
                        yyParenDepth = is.parenDepth;
                    }
                    yyCh = getChar();
                } else if (yyCh == 'n') {
                    // endif
                    if (!yyIfdefStack.isEmpty()) {
                        IfdefState is = yyIfdefStack.pop();
                        if (is.elseLine != -1) {
                            if (yyBracketDepth != is.bracketDepth1st
                                || yyBraceDepth != is.braceDepth1st
                                || yyParenDepth != is.parenDepth1st)
                                yyMsg(is.elseLine)
                                    << qPrintable(LU::tr("Parenthesis/brace mismatch between "
                                                         "#if and #else branches; using #if branch\n"));
                            yyBracketDepth = is.bracketDepth1st;
                            yyBraceDepth = is.braceDepth1st;
                            yyParenDepth = is.parenDepth1st;
                            loadState(&is.state);
                        }
                    }
                    yyCh = getChar();
                }
                break;
            }
            // Optimization: skip over rest of preprocessor directive
            do {
                if (yyCh == '/') {
                    yyCh = getChar();
                    if (yyCh == '/') {
                        do {
                            yyCh = getChar();
                        } while (yyCh != EOF && yyCh != '\n');
                        break;
                    } else if (yyCh == '*') {
                        bool metAster = false;

                        forever {
                            yyCh = getChar();
                            if (yyCh == EOF) {
                                yyMsg() << qPrintable(LU::tr("Unterminated C++ comment\n"));
                                break;
                            }

                            if (yyCh == '*') {
                                metAster = true;
                            } else if (metAster && yyCh == '/') {
                                yyCh = getChar();
                                break;
                            } else {
                                metAster = false;
                            }
                        }
                    }
                } else {
                    yyCh = getChar();
                }
            } while (yyCh != '\n' && yyCh != EOF);
            yyCh = getChar();
        } else if ((yyCh >= 'A' && yyCh <= 'Z') || (yyCh >= 'a' && yyCh <= 'z') || yyCh == '_') {
            ushort *ptr = (ushort *)yyWord.unicode();
            do {
                *ptr++ = yyCh;
                yyCh = getChar();
            } while ((yyCh >= 'A' && yyCh <= 'Z') || (yyCh >= 'a' && yyCh <= 'z')
                     || (yyCh >= '0' && yyCh <= '9') || yyCh == '_');
            yyWord.resize(ptr - (ushort *)yyWord.unicode());

            //qDebug() << "IDENT: " << yyWord;

            switch (yyWord.unicode()[0].unicode()) {
            case 'Q':
                if (yyWord == strQ_OBJECT)
                    return Tok_Q_OBJECT;
                if (yyWord == strQ_DECLARE_TR_FUNCTIONS)
                    return Tok_Q_DECLARE_TR_FUNCTIONS;
                if (yyWord == strQT_TR_NOOP)
                    return Tok_tr;
                if (yyWord == strQT_TRID_NOOP)
                    return Tok_trid;
                if (yyWord == strQT_TRANSLATE_NOOP)
                    return Tok_translate;
                if (yyWord == strQT_TRANSLATE_NOOP3)
                    return Tok_translate;
                if (yyWord == strQT_TR_NOOP_UTF8)
                    return Tok_trUtf8;
                if (yyWord == strQT_TRANSLATE_NOOP_UTF8)
                    return Tok_translateUtf8;
                if (yyWord == strQT_TRANSLATE_NOOP3_UTF8)
                    return Tok_translateUtf8;
                break;
            case 'T':
                // TR() for when all else fails
                if (yyWord == strTR || yyWord == strTr)
                    return Tok_tr;
                break;
            case 'c':
                if (yyWord == strclass)
                    return Tok_class;
                break;
            case 'f':
                /*
                  QTranslator::findMessage() has the same parameters as
                  QApplication::translate().
                */
                if (yyWord == strfindMessage)
                    return Tok_translate;
                if (yyWord == strfriend)
                    return Tok_friend;
                break;
            case 'n':
                if (yyWord == strnamespace)
                    return Tok_namespace;
                break;
            case 'o':
                if (yyWord == stroperator) {
                    // Operator overload declaration/definition.
                    // We need to prevent those characters from confusing the followup
                    // parsing. Actually using them does not add value, so just eat them.
                    while (isspace(yyCh))
                       yyCh = getChar();
                    while (yyCh == '+' || yyCh == '-' || yyCh == '*' || yyCh == '/' || yyCh == '%'
                           || yyCh == '=' || yyCh == '<' || yyCh == '>' || yyCh == '!'
                           || yyCh == '&' || yyCh == '|' || yyCh == '~' || yyCh == '^'
                           || yyCh == '[' || yyCh == ']')
                        yyCh = getChar();
                }
                break;
            case 'q':
                if (yyWord == strqtTrId)
                    return Tok_trid;
                break;
            case 'r':
                if (yyWord == strreturn)
                    return Tok_return;
                break;
            case 's':
                if (yyWord == strstruct)
                    return Tok_class;
                break;
            case 't':
                if (yyWord == strtr)
                    return Tok_tr;
                if (yyWord == strtrUtf8)
                    return Tok_trUtf8;
                if (yyWord == strtranslate)
                    return Tok_translate;
                break;
            case 'u':
                if (yyWord == strusing)
                    return Tok_using;
                break;
            }
            return Tok_Ident;
        } else {
            switch (yyCh) {
            case '\n':
                if (inDefine) {
                    loadState(&savedState);
                    prospectiveContext.clear();
                    yyBraceDepth = yyMinBraceDepth;
                    yyMinBraceDepth = 0;
                    inDefine = false;
                }
                yyCh = getChar();
                break;
            case '/':
                yyCh = getChar();
                if (yyCh == '/') {
                    ushort *ptr = (ushort *)yyWord.unicode() + yyWord.length();
                    do {
                        yyCh = getChar();
                        if (yyCh == EOF)
                            break;
                        *ptr++ = yyCh;
                    } while (yyCh != '\n');
                    yyWord.resize(ptr - (ushort *)yyWord.unicode());
                } else if (yyCh == '*') {
                    bool metAster = false;
                    ushort *ptr = (ushort *)yyWord.unicode() + yyWord.length();

                    forever {
                        yyCh = getChar();
                        if (yyCh == EOF) {
                            yyMsg() << qPrintable(LU::tr("Unterminated C++ comment\n"));
                            break;
                        }
                        *ptr++ = yyCh;

                        if (yyCh == '*')
                            metAster = true;
                        else if (metAster && yyCh == '/')
                            break;
                        else
                            metAster = false;
                    }
                    yyWord.resize(ptr - (ushort *)yyWord.unicode() - 2);

                    yyCh = getChar();
                }
                return Tok_Comment;
            case '"': {
                ushort *ptr = (ushort *)yyWord.unicode() + yyWord.length();
                yyCh = getChar();
                while (yyCh != EOF && yyCh != '\n' && yyCh != '"') {
                    if (yyCh == '\\') {
                        yyCh = getChar();
                        if (yyCh == EOF || yyCh == '\n')
                            break;
                        *ptr++ = '\\';
                    }
                    *ptr++ = yyCh;
                    yyCh = getChar();
                }
                yyWord.resize(ptr - (ushort *)yyWord.unicode());

                if (yyCh != '"')
                    yyMsg() << qPrintable(LU::tr("Unterminated C++ string\n"));
                else
                    yyCh = getChar();
                return Tok_String;
            }
            case '-':
                yyCh = getChar();
                if (yyCh == '>') {
                    yyCh = getChar();
                    return Tok_Arrow;
                }
                break;
            case ':':
                yyCh = getChar();
                if (yyCh == ':') {
                    yyCh = getChar();
                    return Tok_ColonColon;
                }
                return Tok_Colon;
            // Incomplete: '<' might be part of '<=' or of template syntax.
            // The main intent of not completely ignoring it is to break
            // parsing of things like   std::cout << QObject::tr()  as
            // context std::cout::QObject (see Task 161106)
            case '=':
                yyCh = getChar();
                return Tok_Equals;
            case '>':
            case '<':
                yyCh = getChar();
                return Tok_Other;
            case '\'':
                yyCh = getChar();
                if (yyCh == '\\')
                    yyCh = getChar();

                forever {
                    if (yyCh == EOF || yyCh == '\n') {
                        yyMsg() << "Unterminated C++ character\n";
                        break;
                    }
                    yyCh = getChar();
                    if (yyCh == '\'') {
                        yyCh = getChar();
                        break;
                    }
                }
                break;
            case '{':
                if (yyBraceDepth == 0)
                    yyBraceLineNo = yyCurLineNo;
                yyBraceDepth++;
                yyCh = getChar();
                return Tok_LeftBrace;
            case '}':
                if (yyBraceDepth == yyMinBraceDepth) {
                    if (!inDefine)
                        yyMsg(yyCurLineNo)
                            << qPrintable(LU::tr("Excess closing brace in C++ code"
                                                 " (or abuse of the C++ preprocessor)\n"));
                    // Avoid things getting messed up even more
                    yyCh = getChar();
                    return Tok_Semicolon;
                }
                yyBraceDepth--;
                yyCh = getChar();
                return Tok_RightBrace;
            case '(':
                if (yyParenDepth == 0)
                    yyParenLineNo = yyCurLineNo;
                yyParenDepth++;
                yyCh = getChar();
                return Tok_LeftParen;
            case ')':
                if (yyParenDepth == 0)
                    yyMsg(yyCurLineNo)
                        << qPrintable(LU::tr("Excess closing parenthesis in C++ code"
                                             " (or abuse of the C++ preprocessor)\n"));
                else
                    yyParenDepth--;
                yyCh = getChar();
                return Tok_RightParen;
            case '[':
                if (yyBracketDepth == 0)
                    yyBracketLineNo = yyCurLineNo;
                yyBracketDepth++;
                yyCh = getChar();
                return Tok_LeftBracket;
            case ']':
                if (yyBracketDepth == 0)
                    yyMsg(yyCurLineNo)
                        << qPrintable(LU::tr("Excess closing bracket in C++ code"
                                             " (or abuse of the C++ preprocessor)\n"));
                else
                    yyBracketDepth--;
                yyCh = getChar();
                return Tok_RightBracket;
            case ',':
                yyCh = getChar();
                return Tok_Comma;
            case ';':
                yyCh = getChar();
                return Tok_Semicolon;
            case '0':
                yyCh = getChar();
                if (yyCh == 'x') {
                    do {
                        yyCh = getChar();
                    } while ((yyCh >= '0' && yyCh <= '9')
                             || (yyCh >= 'a' && yyCh <= 'f') || (yyCh >= 'A' && yyCh <= 'F'));
                    return Tok_Integer;
                }
                if (yyCh < '0' || yyCh > '9')
                    return Tok_Null;
                // Fallthrough
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                do {
                    yyCh = getChar();
                } while (yyCh >= '0' && yyCh <= '9');
                return Tok_Integer;
            default:
                yyCh = getChar();
                break;
            }
        }
    }
    return Tok_Eof;
}

/*
  The second part of this source file are namespace/class related
  utilities for the third part.
*/

void CppParser::saveState(SavedState *state)
{
    state->namespaces = namespaces;
    state->namespaceDepths = namespaceDepths;
    state->functionContext = functionContext;
    state->functionContextUnresolved = functionContextUnresolved;
    state->pendingContext = pendingContext;
}

void CppParser::loadState(const SavedState *state)
{
    namespaces = state->namespaces;
    namespaceDepths = state->namespaceDepths;
    functionContext = state->functionContext;
    functionContextUnresolved = state->functionContextUnresolved;
    pendingContext = state->pendingContext;
}

Namespace *CppParser::modifyNamespace(NamespaceList *namespaces, bool haveLast)
{
    Namespace *pns, *ns = &results->rootNamespace;
    for (int i = 1; i < namespaces->count(); ++i) {
        pns = ns;
        if (!(ns = pns->children.value(namespaces->at(i)))) {
            do {
                ns = new Namespace;
                if (haveLast || i < namespaces->count() - 1)
                    if (const Namespace *ons = findNamespace(*namespaces, i + 1))
                        ns->classDef = ons->classDef;
                pns->children.insert(namespaces->at(i), ns);
                pns = ns;
            } while (++i < namespaces->count());
            break;
        }
    }
    return ns;
}

QString CppParser::stringifyNamespace(const NamespaceList &namespaces)
{
    QString ret;
    for (int i = 1; i < namespaces.count(); ++i) {
        if (i > 1)
            ret += QLatin1String("::");
        ret += namespaces.at(i).value();
    }
    return ret;
}

QStringList CppParser::stringListifyNamespace(const NamespaceList &namespaces)
{
    QStringList ret;
    for (int i = 1; i < namespaces.count(); ++i)
        ret << namespaces.at(i).value();
    return ret;
}

bool CppParser::visitNamespace(const NamespaceList &namespaces, int nsCount,
                               VisitNamespaceCallback callback, void *context,
                               VisitRecorder &vr, const ParseResults *rslt) const
{
    const Namespace *ns = &rslt->rootNamespace;
    for (int i = 1; i < nsCount; ++i)
        if (!(ns = ns->children.value(namespaces.at(i))))
            goto supers;
    if ((this->*callback)(ns, context))
        return true;
supers:
    foreach (const ParseResults *sup, rslt->includes)
        if (vr.tryVisit(sup->fileId)
            && visitNamespace(namespaces, nsCount, callback, context, vr, sup))
            return true;
    return false;
}

bool CppParser::visitNamespace(const NamespaceList &namespaces, int nsCount,
                               VisitNamespaceCallback callback, void *context) const
{
    VisitRecorder vr;
    return visitNamespace(namespaces, nsCount, callback, context, vr, results);
}

QStringList CppParser::stringListifySegments(const QList<HashString> &segments)
{
    QStringList ret;
    for (int i = 0; i < segments.count(); ++i)
        ret << segments.at(i).value();
    return ret;
}

struct QualifyOneData {
    QualifyOneData(const NamespaceList &ns, int nsc, const HashString &seg, NamespaceList *rslvd,
                   QSet<HashStringList> *visited)
        : namespaces(ns), nsCount(nsc), segment(seg), resolved(rslvd), visitedUsings(visited)
    {}

    const NamespaceList &namespaces;
    int nsCount;
    const HashString &segment;
    NamespaceList *resolved;
    QSet<HashStringList> *visitedUsings;
};

bool CppParser::qualifyOneCallbackOwn(const Namespace *ns, void *context) const
{
    QualifyOneData *data = (QualifyOneData *)context;
    if (ns->children.contains(data->segment)) {
        *data->resolved = data->namespaces.mid(0, data->nsCount);
        *data->resolved << data->segment;
        return true;
    }
    QHash<HashString, NamespaceList>::ConstIterator nsai = ns->aliases.constFind(data->segment);
    if (nsai != ns->aliases.constEnd()) {
        const NamespaceList &nsl = *nsai;
        if (nsl.last().value().isEmpty()) { // Delayed alias resolution
            NamespaceList &nslIn = *const_cast<NamespaceList *>(&nsl);
            nslIn.removeLast();
            NamespaceList nslOut;
            if (!fullyQualify(data->namespaces, data->nsCount, nslIn, false, &nslOut, 0)) {
                const_cast<Namespace *>(ns)->aliases.remove(data->segment);
                return false;
            }
            nslIn = nslOut;
        }
        *data->resolved = nsl;
        return true;
    }
    return false;
}

bool CppParser::qualifyOneCallbackUsing(const Namespace *ns, void *context) const
{
    QualifyOneData *data = (QualifyOneData *)context;
    foreach (const HashStringList &use, ns->usings)
        if (!data->visitedUsings->contains(use)) {
            data->visitedUsings->insert(use);
            if (qualifyOne(use.value(), use.value().count(), data->segment, data->resolved,
                           data->visitedUsings))
                return true;
        }
    return false;
}

bool CppParser::qualifyOne(const NamespaceList &namespaces, int nsCnt, const HashString &segment,
                           NamespaceList *resolved, QSet<HashStringList> *visitedUsings) const
{
    QualifyOneData data(namespaces, nsCnt, segment, resolved, visitedUsings);

    if (visitNamespace(namespaces, nsCnt, &CppParser::qualifyOneCallbackOwn, &data))
        return true;

    return visitNamespace(namespaces, nsCnt, &CppParser::qualifyOneCallbackUsing, &data);
}

bool CppParser::qualifyOne(const NamespaceList &namespaces, int nsCnt, const HashString &segment,
                           NamespaceList *resolved) const
{
    QSet<HashStringList> visitedUsings;

    return qualifyOne(namespaces, nsCnt, segment, resolved, &visitedUsings);
}

bool CppParser::fullyQualify(const NamespaceList &namespaces, int nsCnt,
                             const QList<HashString> &segments, bool isDeclaration,
                             NamespaceList *resolved, QStringList *unresolved) const
{
    int nsIdx;
    int initSegIdx;

    if (segments.first().value().isEmpty()) {
        // fully qualified
        if (segments.count() == 1) {
            resolved->clear();
            *resolved << HashString(QString());
            return true;
        }
        initSegIdx = 1;
        nsIdx = 0;
    } else {
        initSegIdx = 0;
        nsIdx = nsCnt - 1;
    }

    do {
        if (qualifyOne(namespaces, nsIdx + 1, segments[initSegIdx], resolved)) {
            int segIdx = initSegIdx;
            while (++segIdx < segments.count()) {
                if (!qualifyOne(*resolved, resolved->count(), segments[segIdx], resolved)) {
                    if (unresolved)
                        *unresolved = stringListifySegments(segments.mid(segIdx));
                    return false;
                }
            }
            return true;
        }
    } while (!isDeclaration && --nsIdx >= 0);
    resolved->clear();
    *resolved << HashString(QString());
    if (unresolved)
        *unresolved = stringListifySegments(segments.mid(initSegIdx));
    return false;
}

bool CppParser::fullyQualify(const NamespaceList &namespaces,
                             const QList<HashString> &segments, bool isDeclaration,
                             NamespaceList *resolved, QStringList *unresolved) const
{
    return fullyQualify(namespaces, namespaces.count(),
                        segments, isDeclaration, resolved, unresolved);
}

bool CppParser::fullyQualify(const NamespaceList &namespaces,
                             const QString &quali, bool isDeclaration,
                             NamespaceList *resolved, QStringList *unresolved) const
{
    static QString strColons(QLatin1String("::"));

    QList<HashString> segments;
    foreach (const QString &str, quali.split(strColons)) // XXX slow, but needs to be fast(?)
        segments << HashString(str);
    return fullyQualify(namespaces, segments, isDeclaration, resolved, unresolved);
}

bool CppParser::findNamespaceCallback(const Namespace *ns, void *context) const
{
    *((const Namespace **)context) = ns;
    return true;
}

const Namespace *CppParser::findNamespace(const NamespaceList &namespaces, int nsCount) const
{
    const Namespace *ns = 0;
    if (nsCount == -1)
        nsCount = namespaces.count();
    visitNamespace(namespaces, nsCount, &CppParser::findNamespaceCallback, &ns);
    return ns;
}

void CppParser::enterNamespace(NamespaceList *namespaces, const HashString &name)
{
    *namespaces << name;
    if (!findNamespace(*namespaces))
        modifyNamespace(namespaces, false);
}

void CppParser::truncateNamespaces(NamespaceList *namespaces, int length)
{
    if (namespaces->count() > length)
        namespaces->erase(namespaces->begin() + length, namespaces->end());
}

/*
  Functions for processing include files.
*/

ParseResultHash &CppFiles::parsedFiles()
{
    static ParseResultHash parsed;

    return parsed;
}

TranslatorHash &CppFiles::translatedFiles()
{
    static TranslatorHash tors;

    return tors;
}

QSet<QString> &CppFiles::blacklistedFiles()
{
    static QSet<QString> blacklisted;

    return blacklisted;
}

const ParseResults *CppFiles::getResults(const QString &cleanFile)
{
    return parsedFiles().value(cleanFile);
}

void CppFiles::setResults(const QString &cleanFile, const ParseResults *results)
{
    parsedFiles().insert(cleanFile, results);
}

const Translator *CppFiles::getTranslator(const QString &cleanFile)
{
    return translatedFiles().value(cleanFile);
}

void CppFiles::setTranslator(const QString &cleanFile, const Translator *tor)
{
    translatedFiles().insert(cleanFile, tor);
}

bool CppFiles::isBlacklisted(const QString &cleanFile)
{
    return blacklistedFiles().contains(cleanFile);
}

void CppFiles::setBlacklisted(const QString &cleanFile)
{
    blacklistedFiles().insert(cleanFile);
}

static bool isHeader(const QString &name)
{
    QString fileExt = QFileInfo(name).suffix();
    return fileExt.isEmpty() || fileExt.startsWith(QLatin1Char('h'), Qt::CaseInsensitive);
}

void CppParser::processInclude(const QString &file, ConversionData &cd,
                               QSet<QString> &inclusions)
{
    QString cleanFile = QDir::cleanPath(file);

    if (inclusions.contains(cleanFile)) {
        yyMsg() << qPrintable(LU::tr("circular inclusion of %1\n").arg(cleanFile));
        return;
    }

    // If the #include is in any kind of namespace, has been blacklisted previously,
    // or is not a header file (stdc++ extensionless or *.h*), then really include
    // it. Otherwise it is safe to process it stand-alone and re-use the parsed
    // namespace data for inclusion into other files.
    bool isIndirect = false;
    if (namespaces.count() == 1 && functionContext.count() == 1
        && functionContextUnresolved.isEmpty() && pendingContext.isEmpty()
        && !CppFiles::isBlacklisted(cleanFile)
        && isHeader(cleanFile)) {

        if (const ParseResults *res = CppFiles::getResults(cleanFile)) {
            results->includes.insert(res);
            return;
        }

        isIndirect = true;
    }

    QFile f(cleanFile);
    if (!f.open(QIODevice::ReadOnly)) {
        yyMsg() << qPrintable(LU::tr("Cannot open %1: %2\n").arg(cleanFile, f.errorString()));
        return;
    }

    QTextStream ts(&f);
    ts.setCodec(yySourceCodec);
    ts.setAutoDetectUnicode(true);

    inclusions.insert(cleanFile);
    if (isIndirect) {
        CppParser parser;
        foreach (const QString &projectRoot, cd.m_projectRoots)
            if (cleanFile.startsWith(projectRoot)) {
                parser.setTranslator(new Translator);
                break;
            }
        parser.setInput(ts, cleanFile);
        parser.parse(cd.m_defaultContext, cd, inclusions);
        results->includes.insert(parser.recordResults(true));
    } else {
        CppParser parser(results);
        parser.namespaces = namespaces;
        parser.functionContext = functionContext;
        parser.functionContextUnresolved = functionContextUnresolved;
        parser.pendingContext = pendingContext;
        parser.setInput(ts, cleanFile);
        parser.parseInternal(cd, inclusions);
        // Avoid that messages obtained by direct scanning are used
        CppFiles::setBlacklisted(cleanFile);
    }
    inclusions.remove(cleanFile);
}

/*
  The third part of this source file is the parser. It accomplishes
  a very easy task: It finds all strings inside a tr() or translate()
  call, and possibly finds out the context of the call. It supports
  three cases: (1) the context is specified, as in
  FunnyDialog::tr("Hello") or translate("FunnyDialog", "Hello");
  (2) the call appears within an inlined function; (3) the call
  appears within a function defined outside the class definition.
*/

bool CppParser::match(uint t)
{
    bool matches = (yyTok == t);
    if (matches)
        yyTok = getToken();
    return matches;
}

bool CppParser::matchString(QString *s)
{
    bool matches = false;
    s->clear();
    forever {
        while (yyTok == Tok_Comment)
            yyTok = getToken();
        if (yyTok != Tok_String)
            return matches;
        matches = true;
        *s += yyWord;
        s->detach();
        yyTok = getToken();
    }
}

STRING(QApplication);
STRING(QCoreApplication);
STRING(UnicodeUTF8);
STRING(DefaultCodec);
STRING(CodecForTr);

bool CppParser::matchEncoding(bool *utf8)
{
    if (yyTok != Tok_Ident)
        return false;
    if (yyWord == strQApplication || yyWord == strQCoreApplication) {
        yyTok = getToken();
        if (yyTok == Tok_ColonColon)
            yyTok = getToken();
    }
    if (yyWord == strUnicodeUTF8) {
        *utf8 = true;
        yyTok = getToken();
        return true;
    }
    if (yyWord == strDefaultCodec || yyWord == strCodecForTr) {
        *utf8 = false;
        yyTok = getToken();
        return true;
    }
    return false;
}

bool CppParser::matchStringOrNull(QString *s)
{
    return matchString(s) || match(Tok_Null);
}

/*
 * match any expression that can return a number, which can be
 * 1. Literal number (e.g. '11')
 * 2. simple identifier (e.g. 'm_count')
 * 3. simple function call (e.g. 'size()' )
 * 4. function call on an object (e.g. 'list.size()')
 * 5. function call on an object (e.g. 'list->size()')
 *
 * Other cases:
 * size(2,4)
 * list().size()
 * list(a,b).size(2,4)
 * etc...
 */
bool CppParser::matchExpression()
{
    if (match(Tok_Null) || match(Tok_Integer))
        return true;

    int parenlevel = 0;
    while (match(Tok_Ident) || parenlevel > 0) {
        if (yyTok == Tok_RightParen) {
            if (parenlevel == 0) break;
            --parenlevel;
            yyTok = getToken();
        } else if (yyTok == Tok_LeftParen) {
            yyTok = getToken();
            if (yyTok == Tok_RightParen) {
                yyTok = getToken();
            } else {
                ++parenlevel;
            }
        } else if (yyTok == Tok_Ident) {
            continue;
        } else if (yyTok == Tok_Arrow) {
            yyTok = getToken();
        } else if (parenlevel == 0) {
            return false;
        }
    }
    return true;
}

QString CppParser::transcode(const QString &str, bool utf8)
{
    static const char tab[] = "abfnrtv";
    static const char backTab[] = "\a\b\f\n\r\t\v";
    // This function has to convert back to bytes, as C's \0* sequences work at that level.
    const QByteArray in = yyForceUtf8 ? str.toUtf8() : tor->codec()->fromUnicode(str);
    QByteArray out;

    out.reserve(in.length());
    for (int i = 0; i < in.length();) {
        uchar c = in[i++];
        if (c == '\\') {
            if (i >= in.length())
                break;
            c = in[i++];

            if (c == '\n')
                continue;

            if (c == 'x') {
                QByteArray hex;
                while (i < in.length() && isxdigit((c = in[i]))) {
                    hex += c;
                    i++;
                }
                out += hex.toUInt(0, 16);
            } else if (c >= '0' && c < '8') {
                QByteArray oct;
                int n = 0;
                oct += c;
                while (n < 2 && i < in.length() && (c = in[i]) >= '0' && c < '8') {
                    i++;
                    n++;
                    oct += c;
                }
                out += oct.toUInt(0, 8);
            } else {
                const char *p = strchr(tab, c);
                out += !p ? c : backTab[p - tab];
            }
        } else {
            out += c;
        }
    }
    return (utf8 || yyForceUtf8) ? QString::fromUtf8(out.constData(), out.length())
                                 : tor->codec()->toUnicode(out);
}

void CppParser::recordMessage(
    int line, const QString &context, const QString &text, const QString &comment,
    const QString &extracomment, const QString &msgid, const TranslatorMessage::ExtraData &extra,
    bool utf8, bool plural)
{
    TranslatorMessage msg(
        transcode(context, utf8), transcode(text, utf8), transcode(comment, utf8), QString(),
        yyFileName, line, QStringList(),
        TranslatorMessage::Unfinished, plural);
    msg.setExtraComment(transcode(extracomment.simplified(), utf8));
    msg.setId(msgid);
    msg.setExtras(extra);
    if ((utf8 || yyForceUtf8) && !yyCodecIsUtf8 && msg.needs8Bit())
        msg.setUtf8(true);
    tor->append(msg);
}

void CppParser::parse(const QString &initialContext, ConversionData &cd,
                      QSet<QString> &inclusions)
{
    if (tor)
        yyCodecIsUtf8 = (tor->codecName() == "UTF-8");

    namespaces << HashString();
    functionContext = namespaces;
    functionContextUnresolved = initialContext;

    parseInternal(cd, inclusions);
}

void CppParser::parseInternal(ConversionData &cd, QSet<QString> &inclusions)
{
    static QString strColons(QLatin1String("::"));

    QString context;
    QString text;
    QString comment;
    QString extracomment;
    QString msgid;
    QString sourcetext;
    TranslatorMessage::ExtraData extra;
    QString prefix;
#ifdef DIAGNOSE_RETRANSLATABILITY
    QString functionName;
#endif
    int line;
    bool utf8;
    bool yyTokColonSeen = false; // Start of c'tor's initializer list

    yyWord.reserve(yyInStr.size()); // Rather insane. That's because we do no length checking.
    yyInPtr = (const ushort *)yyInStr.unicode();
    yyCh = getChar();
    yyTok = getToken();
    while (yyTok != Tok_Eof) {
        // these are array indexing operations. we ignore them entirely
        // so they don't confuse our scoping of static initializers.
        // we enter the loop by either reading a left bracket or by an
        // #else popping the state.
        while (yyBracketDepth)
            yyTok = getToken();
        //qDebug() << "TOKEN: " << yyTok;
        switch (yyTok) {
        case Tok_QuotedInclude: {
            text = QDir(QFileInfo(yyFileName).absolutePath()).absoluteFilePath(yyWord);
            text.detach();
            if (QFileInfo(text).isFile()) {
                processInclude(text, cd, inclusions);
                yyTok = getToken();
                break;
            }
        }
        /* fall through */
        case Tok_AngledInclude: {
            QStringList cSources = cd.m_allCSources.values(yyWord);
            if (!cSources.isEmpty()) {
                foreach (const QString &cSource, cSources)
                    processInclude(cSource, cd, inclusions);
                goto incOk;
            }
            foreach (const QString &incPath, cd.m_includePath) {
                text = QDir(incPath).absoluteFilePath(yyWord);
                text.detach();
                if (QFileInfo(text).isFile()) {
                    processInclude(text, cd, inclusions);
                    goto incOk;
                }
            }
          incOk:
            yyTok = getToken();
            break;
        }
        case Tok_friend:
            yyTok = getToken();
            // These are forward declarations, so ignore them.
            if (yyTok == Tok_class)
                yyTok = getToken();
            break;
        case Tok_class:
            yyTokColonSeen = false;
            /*
              Partial support for inlined functions.
            */
            yyTok = getToken();
            if (yyBraceDepth == namespaceDepths.count() && yyParenDepth == 0) {
                QList<HashString> quali;
                HashString fct;
                do {
                    /*
                      This code should execute only once, but we play
                      safe with impure definitions such as
                      'class Q_EXPORT QMessageBox', in which case
                      'QMessageBox' is the class name, not 'Q_EXPORT'.
                    */
                    text = yyWord;
                    text.detach();
                    fct.setValue(text);
                    yyTok = getToken();
                } while (yyTok == Tok_Ident);
                while (yyTok == Tok_ColonColon) {
                    yyTok = getToken();
                    if (yyTok != Tok_Ident)
                        break; // Oops ...
                    quali << fct;
                    text = yyWord;
                    text.detach();
                    fct.setValue(text);
                    yyTok = getToken();
                }
                while (yyTok == Tok_Comment)
                    yyTok = getToken();
                if (yyTok == Tok_Colon) {
                    // Skip any token until '{' since we might do things wrong if we find
                    // a '::' token here.
                    do {
                        yyTok = getToken();
                    } while (yyTok != Tok_LeftBrace && yyTok != Tok_Eof);
                } else {
                    if (yyTok != Tok_LeftBrace) {
                        // Obviously a forward declaration. We skip those, as they
                        // don't create actually usable namespaces.
                        break;
                    }
                }

                if (!quali.isEmpty()) {
                    // Forward-declared class definitions can be namespaced.
                    NamespaceList nsl;
                    if (!fullyQualify(namespaces, quali, true, &nsl, 0)) {
                        yyMsg() << "Ignoring definition of undeclared qualified class\n";
                        break;
                    }
                    namespaceDepths.push(namespaces.count());
                    namespaces = nsl;
                } else {
                    namespaceDepths.push(namespaces.count());
                }
                enterNamespace(&namespaces, fct);

                functionContext = namespaces;
                functionContextUnresolved.clear(); // Pointless
                prospectiveContext.clear();
                pendingContext.clear();

                yyTok = getToken();
            }
            break;
        case Tok_namespace:
            yyTokColonSeen = false;
            yyTok = getToken();
            if (yyTok == Tok_Ident) {
                text = yyWord;
                text.detach();
                HashString ns = HashString(text);
                yyTok = getToken();
                if (yyTok == Tok_LeftBrace) {
                    namespaceDepths.push(namespaces.count());
                    enterNamespace(&namespaces, ns);

                    functionContext = namespaces;
                    functionContextUnresolved.clear();
                    prospectiveContext.clear();
                    pendingContext.clear();
                    yyTok = getToken();
                } else if (yyTok == Tok_Equals) {
                    // e.g. namespace Is = OuterSpace::InnerSpace;
                    QList<HashString> fullName;
                    yyTok = getToken();
                    if (yyTok == Tok_ColonColon)
                        fullName.append(HashString(QString()));
                    while (yyTok == Tok_ColonColon || yyTok == Tok_Ident) {
                        if (yyTok == Tok_Ident) {
                            text = yyWord;
                            text.detach();
                            fullName.append(HashString(text));
                        }
                        yyTok = getToken();
                    }
                    if (fullName.isEmpty())
                        break;
                    fullName.append(HashString(QString())); // Mark as unresolved
                    modifyNamespace(&namespaces)->aliases[ns] = fullName;
                }
            } else if (yyTok == Tok_LeftBrace) {
                // Anonymous namespace
                namespaceDepths.push(namespaces.count());
                yyTok = getToken();
            }
            break;
        case Tok_using:
            yyTok = getToken();
            // XXX this should affect only the current scope, not the entire current namespace
            if (yyTok == Tok_namespace) {
                QList<HashString> fullName;
                yyTok = getToken();
                if (yyTok == Tok_ColonColon)
                    fullName.append(HashString(QString()));
                while (yyTok == Tok_ColonColon || yyTok == Tok_Ident) {
                    if (yyTok == Tok_Ident) {
                        text = yyWord;
                        text.detach();
                        fullName.append(HashString(text));
                    }
                    yyTok = getToken();
                }
                NamespaceList nsl;
                if (fullyQualify(namespaces, fullName, false, &nsl, 0))
                    modifyNamespace(&namespaces)->usings << HashStringList(nsl);
            } else {
                QList<HashString> fullName;
                if (yyTok == Tok_ColonColon)
                    fullName.append(HashString(QString()));
                while (yyTok == Tok_ColonColon || yyTok == Tok_Ident) {
                    if (yyTok == Tok_Ident) {
                        text = yyWord;
                        text.detach();
                        fullName.append(HashString(text));
                    }
                    yyTok = getToken();
                }
                if (fullName.isEmpty())
                    break;
                // using-declarations cannot rename classes, so the last element of
                // fullName is already the resolved name we actually want.
                // As we do no resolution here, we'll collect useless usings of data
                // members and methods as well. This is no big deal.
                HashString &ns = fullName.last();
                fullName.append(HashString(QString())); // Mark as unresolved
                modifyNamespace(&namespaces)->aliases[ns] = fullName;
            }
            break;
        case Tok_tr:
        case Tok_trUtf8:
            if (!tor)
                goto case_default;
            if (!sourcetext.isEmpty())
                yyMsg() << qPrintable(LU::tr("//% cannot be used with tr() / QT_TR_NOOP(). Ignoring\n"));
            utf8 = (yyTok == Tok_trUtf8);
            line = yyLineNo;
            yyTok = getToken();
            if (match(Tok_LeftParen) && matchString(&text) && !text.isEmpty()) {
                comment.clear();
                bool plural = false;

                if (match(Tok_RightParen)) {
                    // no comment
                } else if (match(Tok_Comma) && matchStringOrNull(&comment)) {   //comment
                    if (match(Tok_RightParen)) {
                        // ok,
                    } else if (match(Tok_Comma)) {
                        plural = true;
                    }
                }
                if (!pendingContext.isEmpty() && !prefix.startsWith(strColons)) {
                    QStringList unresolved;
                    if (!fullyQualify(namespaces, pendingContext, true, &functionContext, &unresolved)) {
                        functionContextUnresolved = unresolved.join(strColons);
                        yyMsg() << qPrintable(LU::tr("Qualifying with unknown namespace/class %1::%2\n")
                                              .arg(stringifyNamespace(functionContext)).arg(unresolved.first()));
                    }
                    pendingContext.clear();
                }
                if (prefix.isEmpty()) {
                    if (functionContextUnresolved.isEmpty()) {
                        int idx = functionContext.length();
                        if (idx < 2) {
                            yyMsg() << qPrintable(LU::tr("tr() cannot be called without context\n"));
                            break;
                        }
                        Namespace *fctx;
                        while (!(fctx = findNamespace(functionContext, idx)->classDef)->hasTrFunctions) {
                            if (idx == 1) {
                                context = stringifyNamespace(functionContext);
                                fctx = findNamespace(functionContext)->classDef;
                                if (!fctx->complained) {
                                    yyMsg() << qPrintable(LU::tr("Class '%1' lacks Q_OBJECT macro\n")
                                                         .arg(context));
                                    fctx->complained = true;
                                }
                                goto gotctx;
                            }
                            --idx;
                        }
                        if (fctx->trQualification.isEmpty()) {
                            context.clear();
                            for (int i = 1;;) {
                                context += functionContext.at(i).value();
                                if (++i == idx)
                                    break;
                                context += strColons;
                            }
                            fctx->trQualification = context;
                        } else {
                            context = fctx->trQualification;
                        }
                    } else {
                        context = (stringListifyNamespace(functionContext)
                                   << functionContextUnresolved).join(strColons);
                    }
                } else {
#ifdef DIAGNOSE_RETRANSLATABILITY
                    int last = prefix.lastIndexOf(strColons);
                    QString className = prefix.mid(last == -1 ? 0 : last + 2);
                    if (!className.isEmpty() && className == functionName) {
                        yyMsg() << qPrintable(LU::tr("It is not recommended to call tr() from within a constructor '%1::%2'\n")
                                .arg(className).arg(functionName));
                    }
#endif
                    prefix.chop(2);
                    NamespaceList nsl;
                    QStringList unresolved;
                    if (fullyQualify(functionContext, prefix, false, &nsl, &unresolved)) {
                        Namespace *fctx = findNamespace(nsl)->classDef;
                        if (fctx->trQualification.isEmpty()) {
                            context = stringifyNamespace(nsl);
                            fctx->trQualification = context;
                        } else {
                            context = fctx->trQualification;
                        }
                        if (!fctx->hasTrFunctions && !fctx->complained) {
                            yyMsg() << qPrintable(LU::tr("Class '%1' lacks Q_OBJECT macro\n").arg(context));
                            fctx->complained = true;
                        }
                    } else {
                        context = (stringListifyNamespace(nsl) + unresolved).join(strColons);
                    }
                    prefix.clear();
                }

              gotctx:
                recordMessage(line, context, text, comment, extracomment, msgid, extra, utf8, plural);
            }
            sourcetext.clear(); // Will have warned about that already
            extracomment.clear();
            msgid.clear();
            extra.clear();
            break;
        case Tok_translateUtf8:
        case Tok_translate:
            if (!tor)
                goto case_default;
            if (!sourcetext.isEmpty())
                yyMsg() << qPrintable(LU::tr("//% cannot be used with translate() / QT_TRANSLATE_NOOP(). Ignoring\n"));
            utf8 = (yyTok == Tok_translateUtf8);
            line = yyLineNo;
            yyTok = getToken();
            if (match(Tok_LeftParen)
                && matchString(&context)
                && match(Tok_Comma)
                && matchString(&text) && !text.isEmpty())
            {
                comment.clear();
                bool plural = false;
                if (!match(Tok_RightParen)) {
                    // look for comment
                    if (match(Tok_Comma) && matchStringOrNull(&comment)) {
                        if (!match(Tok_RightParen)) {
                            // look for encoding
                            if (match(Tok_Comma)) {
                                if (matchEncoding(&utf8)) {
                                    if (!match(Tok_RightParen)) {
                                        // look for the plural quantifier,
                                        // this can be a number, an identifier or
                                        // a function call,
                                        // so for simplicity we mark it as plural if
                                        // we know we have a comma instead of an
                                        // right parentheses.
                                        plural = match(Tok_Comma);
                                    }
                                } else {
                                    // This can be a QTranslator::translate("context",
                                    // "source", "comment", n) plural translation
                                    if (matchExpression() && match(Tok_RightParen)) {
                                        plural = true;
                                    } else {
                                        break;
                                    }
                                }
                            } else {
                                break;
                            }
                        }
                    } else {
                        break;
                    }
                }
                recordMessage(line, context, text, comment, extracomment, msgid, extra, utf8, plural);
            }
            sourcetext.clear(); // Will have warned about that already
            extracomment.clear();
            msgid.clear();
            extra.clear();
            break;
        case Tok_trid:
            if (!tor)
                goto case_default;
            if (!msgid.isEmpty())
                yyMsg() << qPrintable(LU::tr("//= cannot be used with qtTrId() / QT_TRID_NOOP(). Ignoring\n"));
            //utf8 = false; // Maybe use //%% or something like that
            line = yyLineNo;
            yyTok = getToken();
            if (match(Tok_LeftParen) && matchString(&msgid) && !msgid.isEmpty()) {
                bool plural = match(Tok_Comma);
                recordMessage(line, QString(), sourcetext, QString(), extracomment,
                              msgid, extra, false, plural);
            }
            sourcetext.clear();
            extracomment.clear();
            msgid.clear();
            extra.clear();
            break;
        case Tok_Q_DECLARE_TR_FUNCTIONS:
            if (getMacroArgs()) {
                Namespace *ns = modifyNamespace(&namespaces);
                ns->hasTrFunctions = true;
                ns->trQualification = yyWord;
                ns->trQualification.detach();
            }
            yyTok = getToken();
            break;
        case Tok_Q_OBJECT:
            modifyNamespace(&namespaces)->hasTrFunctions = true;
            yyTok = getToken();
            break;
        case Tok_Ident:
            prefix += yyWord;
            prefix.detach();
            yyTok = getToken();
            if (yyTok != Tok_ColonColon) {
                prefix.clear();
                if (yyTok == Tok_Ident && !yyParenDepth)
                    prospectiveContext.clear();
            }
            break;
        case Tok_Comment: {
            if (!tor)
                goto case_default;
            const QChar *ptr = yyWord.unicode();
            if (*ptr == QLatin1Char(':') && ptr[1].isSpace()) {
                yyWord.remove(0, 2);
                extracomment += yyWord;
                extracomment.detach();
            } else if (*ptr == QLatin1Char('=') && ptr[1].isSpace()) {
                yyWord.remove(0, 2);
                msgid = yyWord.simplified();
                msgid.detach();
            } else if (*ptr == QLatin1Char('~') && ptr[1].isSpace()) {
                yyWord.remove(0, 2);
                text = yyWord.trimmed();
                int k = text.indexOf(QLatin1Char(' '));
                if (k > -1)
                    extra.insert(text.left(k), text.mid(k + 1).trimmed());
                text.clear();
            } else if (*ptr == QLatin1Char('%') && ptr[1].isSpace()) {
                sourcetext.reserve(sourcetext.length() + yyWord.length() - 2);
                ushort *ptr = (ushort *)sourcetext.data() + sourcetext.length();
                int p = 2, c;
                forever {
                    if (p >= yyWord.length())
                        break;
                    c = yyWord.unicode()[p++].unicode();
                    if (isspace(c))
                        continue;
                    if (c != '"') {
                        yyMsg() << qPrintable(LU::tr("Unexpected character in meta string\n"));
                        break;
                    }
                    forever {
                        if (p >= yyWord.length()) {
                          whoops:
                            yyMsg() << qPrintable(LU::tr("Unterminated meta string\n"));
                            break;
                        }
                        c = yyWord.unicode()[p++].unicode();
                        if (c == '"')
                            break;
                        if (c == '\\') {
                            if (p >= yyWord.length())
                                goto whoops;
                            c = yyWord.unicode()[p++].unicode();
                            if (c == '\n')
                                goto whoops;
                            *ptr++ = '\\';
                        }
                        *ptr++ = c;
                    }
                }
                sourcetext.resize(ptr - (ushort *)sourcetext.data());
            } else {
                const ushort *uc = (const ushort *)yyWord.unicode(); // Is zero-terminated
                int idx = 0;
                ushort c;
                while ((c = uc[idx]) == ' ' || c == '\t' || c == '\n')
                    ++idx;
                if (!memcmp(uc + idx, MagicComment.unicode(), MagicComment.length() * 2)) {
                    idx += MagicComment.length();
                    comment = QString::fromRawData(yyWord.unicode() + idx,
                                                   yyWord.length() - idx).simplified();
                    int k = comment.indexOf(QLatin1Char(' '));
                    if (k == -1) {
                        context = comment;
                    } else {
                        context = comment.left(k);
                        comment.remove(0, k + 1);
                        TranslatorMessage msg(
                                transcode(context, false), QString(),
                                transcode(comment, false), QString(),
                                yyFileName, yyLineNo, QStringList(),
                                TranslatorMessage::Finished, false);
                        msg.setExtraComment(transcode(extracomment.simplified(), false));
                        extracomment.clear();
                        tor->append(msg);
                        tor->setExtras(extra);
                        extra.clear();
                    }
                }
            }
            yyTok = getToken();
            break;
        }
        case Tok_Arrow:
            yyTok = getToken();
            if (yyTok == Tok_tr || yyTok == Tok_trUtf8)
                yyMsg() << qPrintable(LU::tr("Cannot invoke tr() like this\n"));
            break;
        case Tok_ColonColon:
            if (yyBraceDepth == namespaceDepths.count() && yyParenDepth == 0 && !yyTokColonSeen)
                prospectiveContext = prefix;
            prefix += strColons;
            yyTok = getToken();
#ifdef DIAGNOSE_RETRANSLATABILITY
            if (yyTok == Tok_Ident && yyBraceDepth == namespaceDepths.count() && yyParenDepth == 0) {
                functionName = yyWord;
                functionName.detach();
            }
#endif
            break;
        case Tok_RightBrace:
            if (yyBraceDepth + 1 == namespaceDepths.count()) // class or namespace
                truncateNamespaces(&namespaces, namespaceDepths.pop());
            if (yyBraceDepth == namespaceDepths.count()) {
                // function, class or namespace
                if (!yyBraceDepth && !directInclude) {
                    truncateNamespaces(&functionContext, 1);
                    functionContextUnresolved = cd.m_defaultContext;
                } else {
                    functionContext = namespaces;
                    functionContextUnresolved.clear();
                }
                pendingContext.clear();
            }
            // fallthrough
        case Tok_Semicolon:
            prospectiveContext.clear();
            prefix.clear();
            if (!sourcetext.isEmpty() || !extracomment.isEmpty() || !msgid.isEmpty() || !extra.isEmpty()) {
                yyMsg() << qPrintable(LU::tr("Discarding unconsumed meta data\n"));
                sourcetext.clear();
                extracomment.clear();
                msgid.clear();
                extra.clear();
            }
            yyTokColonSeen = false;
            yyTok = getToken();
            break;
        case Tok_Colon:
            if (!prospectiveContext.isEmpty()
                && yyBraceDepth == namespaceDepths.count() && yyParenDepth == 0)
                pendingContext = prospectiveContext;
            yyTokColonSeen = true;
            yyTok = getToken();
            break;
        case Tok_LeftBrace:
            if (!prospectiveContext.isEmpty()
                && yyBraceDepth == namespaceDepths.count() + 1 && yyParenDepth == 0)
                pendingContext = prospectiveContext;
            // fallthrough
        case Tok_LeftParen:
        case Tok_RightParen:
            yyTokColonSeen = false;
            yyTok = getToken();
            break;
        default:
            if (!yyParenDepth)
                prospectiveContext.clear();
            // fallthrough
        case Tok_Equals: // for static initializers; other cases make no difference
        case Tok_RightBracket: // ignoring indexing; same reason
        case_default:
            yyTok = getToken();
            break;
        }
    }

    if (yyBraceDepth != 0)
        yyMsg(yyBraceLineNo)
            << qPrintable(LU::tr("Unbalanced opening brace in C++ code"
                                 " (or abuse of the C++ preprocessor)\n"));
    else if (yyParenDepth != 0)
        yyMsg(yyParenLineNo)
            << qPrintable(LU::tr("Unbalanced opening parenthesis in C++ code"
                                 " (or abuse of the C++ preprocessor)\n"));
    else if (yyBracketDepth != 0)
        yyMsg(yyBracketLineNo)
            << qPrintable(LU::tr("Unbalanced opening bracket in C++ code"
                                 " (or abuse of the C++ preprocessor)\n"));
}

const ParseResults *CppParser::recordResults(bool isHeader)
{
    if (tor) {
        if (tor->messageCount()) {
            CppFiles::setTranslator(yyFileName, tor);
        } else {
            delete tor;
            tor = 0;
        }
    }
    if (isHeader) {
        const ParseResults *pr;
        if (!tor && results->includes.count() == 1
            && results->rootNamespace.children.isEmpty()
            && results->rootNamespace.aliases.isEmpty()
            && results->rootNamespace.usings.isEmpty()) {
            // This is a forwarding header. Slash it.
            pr = *results->includes.begin();
            delete results;
        } else {
            results->fileId = nextFileId++;
            pr = results;
        }
        CppFiles::setResults(yyFileName, pr);
        return pr;
    } else {
        delete results;
        return 0;
    }
}

/*
  Fetches tr() calls in C++ code in UI files (inside "<function>"
  tag). This mechanism is obsolete.
*/
void fetchtrInlinedCpp(const QString &in, Translator &translator, const QString &context)
{
    CppParser parser;
    parser.setInput(in);
    ConversionData cd;
    QSet<QString> inclusions;
    parser.setTranslator(&translator);
    parser.parse(context, cd, inclusions);
    parser.deleteResults();
}

void loadCPP(Translator &translator, const QStringList &filenames, ConversionData &cd)
{
    QByteArray codecName = cd.m_codecForSource.isEmpty()
                            ? translator.codecName() : cd.m_codecForSource;
    QTextCodec *codec = QTextCodec::codecForName(codecName);

    foreach (const QString &filename, filenames) {
        if (CppFiles::getResults(filename) || CppFiles::isBlacklisted(filename))
            continue;

        QFile file(filename);
        if (!file.open(QIODevice::ReadOnly)) {
            cd.appendError(LU::tr("Cannot open %1: %2").arg(filename, file.errorString()));
            continue;
        }

        CppParser parser;
        QTextStream ts(&file);
        ts.setCodec(codec);
        ts.setAutoDetectUnicode(true);
        parser.setInput(ts, filename);
        if (cd.m_outputCodec.isEmpty() && ts.codec()->name() == "UTF-16")
            translator.setCodecName("System");
        Translator *tor = new Translator;
        tor->setCodecName(translator.codecName());
        parser.setTranslator(tor);
        QSet<QString> inclusions;
        parser.parse(cd.m_defaultContext, cd, inclusions);
        parser.recordResults(isHeader(filename));
    }

    foreach (const QString &filename, filenames)
        if (!CppFiles::isBlacklisted(filename))
            if (const Translator *tor = CppFiles::getTranslator(filename))
                foreach (const TranslatorMessage &msg, tor->messages())
                    translator.extend(msg);
}

QT_END_NAMESPACE