tst_preprocessor.cpp 53.2 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
Bill King's avatar
Bill King committed
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
Bill King's avatar
Bill King committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
Bill King's avatar
Bill King committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
Bill King's avatar
Bill King committed
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
Bill King's avatar
Bill King committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
Bill King's avatar
Bill King committed
29

30
31
#include <cplusplus/pp.h>

32
#include <QtTest>
Leandro Melo's avatar
Leandro Melo committed
33
#include <QHash>
34

35
//TESTED_COMPONENT=src/libs/cplusplus
36
using namespace CPlusPlus;
37

38
39
40
41
42
#define DUMP_OUTPUT(x)     {QByteArray b(x);qDebug("output: [[%s]]", b.replace("\n", "<<\n").constData());}


QByteArray loadSource(const QString &fileName)
{
43
    QFile inf(QLatin1String(SRCDIR) + QLatin1Char('/') + fileName);
44
45
46
47
48
49
50
51
52
53
54
55
56
    if (!inf.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug("Cannot open \"%s\"", fileName.toUtf8().constData());
        return QByteArray();
    }

    QTextStream ins(&inf);
    QString source = ins.readAll();
    inf.close();
    return source.toUtf8();
}

void saveData(const QByteArray &data, const QString &fileName)
{
57
    QFile inf(QLatin1String(SRCDIR) + QLatin1Char('/') + fileName);
58
59
60
61
62
63
64
65
66
    if (!inf.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug("Cannot open \"%s\"", fileName.toUtf8().constData());
        return;
    }

    inf.write(data);
    inf.close();
}

Erik Verbruggen's avatar
Erik Verbruggen committed
67
68
69
70
71
72
73
74
75
76
struct Include
{
    Include(const QString &fileName, Client::IncludeType type, unsigned line)
        : fileName(fileName), type(type), line(line)
    {}

    QString fileName;
    Client::IncludeType type;
    unsigned line;
};
77
78
79

QDebug &operator<<(QDebug& d, const Include &i)
{
Erik Verbruggen's avatar
Erik Verbruggen committed
80
    d << '[' << i.fileName
81
82
      << ',' << (i.type == Client::IncludeGlobal ? "Global"
            : (i.type == Client::IncludeLocal ? "Local" : "Unknown"))
Erik Verbruggen's avatar
Erik Verbruggen committed
83
84
85
86
87
      << ',' << i.line
      << ']';
    return d;
}

88
class MockClient : public Client
89
90
91
{
public:
    struct Block {
92
93
        Block() : start(0), end(0) {}
        Block(unsigned start) : start(start), end(0) {}
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

        unsigned start;
        unsigned end;
    };

public:
    MockClient(Environment *env, QByteArray *output)
        : m_env(env)
        , m_output(output)
        , m_pp(this, env)
        , m_includeDepth(0)
    {}

    virtual ~MockClient() {}

109
110
111
112
113
    virtual void macroAdded(const Macro & macro)
    {
        m_definedMacros.append(macro.name());
        m_definedMacrosLine.append(macro.line());
    }
114

115
116
117
    virtual void passedMacroDefinitionCheck(unsigned /*offset*/,
                                            unsigned /*line*/,
                                            const Macro &/*macro*/) {}
118
    virtual void failedMacroDefinitionCheck(unsigned /*offset*/, const ByteArrayRef &/*name*/) {}
119

120
121
122
123
124
125
    virtual void notifyMacroReference(unsigned offset, unsigned line, const Macro &macro)
    {
        m_macroUsesLine[macro.name()].append(line);
        m_expandedMacrosOffset.append(offset);
    }

126
    virtual void startExpandingMacro(unsigned offset,
127
                                     unsigned line,
Leandro Melo's avatar
Leandro Melo committed
128
                                     const Macro &macro,
129
130
                                     const QVector<MacroArgumentReference> &actuals
                                            = QVector<MacroArgumentReference>())
131
    {
132
        m_expandedMacros.append(macro.name());
133
        m_expandedMacrosOffset.append(offset);
134
        m_macroUsesLine[macro.name()].append(line);
135
        m_macroArgsCount.append(actuals.size());
136
    }
137

138
    virtual void stopExpandingMacro(unsigned /*offset*/, const Macro &/*macro*/) {}
139
140
141
142
143
144
145

    virtual void startSkippingBlocks(unsigned offset)
    { m_skippedBlocks.append(Block(offset)); }

    virtual void stopSkippingBlocks(unsigned offset)
    { m_skippedBlocks.last().end = offset; }

146
    virtual void sourceNeeded(unsigned line, const QString &includedFileName, IncludeType mode)
147
    {
Erik Verbruggen's avatar
Erik Verbruggen committed
148
149
#if 1
        m_recordedIncludes.append(Include(includedFileName, mode, line));
150
151
        Q_UNUSED(m_env);
        Q_UNUSED(m_includeDepth);
Erik Verbruggen's avatar
Erik Verbruggen committed
152
153
154
#else
        Q_UNUSED(line);

155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        QString resolvedFileName;
        if (mode == IncludeLocal)
            resolvedFileName = resolveLocally(m_env->currentFile, includedFileName);
        else
            resolvedFileName = resolveGlobally(includedFileName);

    //    qDebug("resolved [[%s]] to [[%s]] from [[%s]] (%s)\n",
    //           includedFileName.toUtf8().constData(),
    //           resolvedFileName.toUtf8().constData(),
    //           currentFileName.toUtf8().constData(),
    //           (mode == IncludeLocal) ? "locally" : "globally");

        if (resolvedFileName.isEmpty())
            return;

        ++m_includeDepth;
        //    qDebug("%5d %s %s", m_includeDepth, QByteArray(m_includeDepth, '+').constData(), resolvedFileName.toUtf8().constData());
        sourceNeeded(resolvedFileName);
        --m_includeDepth;
Erik Verbruggen's avatar
Erik Verbruggen committed
174
#endif
175
176
177
    }

    QString resolveLocally(const QString &currentFileName,
178
                           const QString &includedFileName) const
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
    {
        QDir dir;
        if (currentFileName.isEmpty())
            dir = QDir::current();
        else
            dir = QFileInfo(currentFileName).dir();
        const QFileInfo inc(dir, includedFileName);
        if (inc.exists()) {
            const QString resolved = inc.filePath();
            return resolved.toUtf8().constData();
        } else {
    //        std::cerr<<"Cannot find " << inc.fileName().toUtf8().constData()<<std::endl;
            return QString();
        }
    }

    QString resolveGlobally(const QString &currentFileName) const
    {
        foreach (const QDir &dir, m_includePaths) {
            QFileInfo f(dir, currentFileName);
            if (f.exists())
                return f.filePath();
        }

        return QString();
    }

    void setIncludePaths(const QStringList &includePaths)
    {
        foreach (const QString &path, includePaths) {
            QDir dir(path);
            if (dir.exists())
                m_includePaths.append(dir);
        }
    }

215
    void sourceNeeded(const QString &fileName, bool nolines)
216
217
218
    {
        QByteArray src = loadSource(fileName);
        QVERIFY(!src.isEmpty());
219
        *m_output = m_pp.run(fileName, src, nolines, true);
220
221
    }

222
223
224
225
226
227
    virtual void markAsIncludeGuard(const QByteArray &macroName)
    { m_includeGuardMacro = macroName; }

    QByteArray includeGuard() const
    { return m_includeGuardMacro; }

228
229
230
    QList<Block> skippedBlocks() const
    { return m_skippedBlocks; }

Erik Verbruggen's avatar
Erik Verbruggen committed
231
232
233
    QList<Include> recordedIncludes() const
    { return m_recordedIncludes; }

234
235
236
    QList<QByteArray> expandedMacros() const
    { return m_expandedMacros; }

237
238
239
    QList<unsigned> expandedMacrosOffset() const
    { return m_expandedMacrosOffset; }

240
241
242
243
244
245
    QList<QByteArray> definedMacros() const
    { return m_definedMacros; }

    QList<unsigned> definedMacrosLine() const
    { return m_definedMacrosLine; }

246
    QHash<QByteArray, QList<unsigned> > macroUsesLine() const
Leandro Melo's avatar
Leandro Melo committed
247
248
    { return m_macroUsesLine; }

249
250
251
    const QList<int> macroArgsCount() const
    { return m_macroArgsCount; }

252
253
254
255
256
257
private:
    Environment *m_env;
    QByteArray *m_output;
    Preprocessor m_pp;
    QList<QDir> m_includePaths;
    unsigned m_includeDepth;
258
    QByteArray m_includeGuardMacro;
259
    QList<Block> m_skippedBlocks;
Erik Verbruggen's avatar
Erik Verbruggen committed
260
    QList<Include> m_recordedIncludes;
261
    QList<QByteArray> m_expandedMacros;
262
    QList<unsigned> m_expandedMacrosOffset;
263
264
    QList<QByteArray> m_definedMacros;
    QList<unsigned> m_definedMacrosLine;
265
    QHash<QByteArray, QList<unsigned> > m_macroUsesLine;
266
    QList<int> m_macroArgsCount;
267
268
};

hjk's avatar
hjk committed
269
QT_BEGIN_NAMESPACE
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
namespace QTest {
    template<> char *toString(const QList<unsigned> &list)
    {
        QByteArray ba = "QList<unsigned>(";
        foreach (const unsigned& item, list) {
            ba += QTest::toString(item);
            ba += ',';
        }
        if (!list.isEmpty())
            ba[ba.size() - 1] = ')';
        return qstrdup(ba.data());
    }
    template<> char *toString(const QList<QByteArray> &list)
    {
        QByteArray ba = "QList<QByteArray>(";
        foreach (const QByteArray& item, list) {
            ba += QTest::toString(item);
            ba += ',';
        }
        if (!list.isEmpty())
            ba[ba.size() - 1] = ')';
        return qstrdup(ba.data());
    }
}
hjk's avatar
hjk committed
294
QT_END_NAMESPACE
295

296
297
298
299
300
QDebug &operator<<(QDebug& d, const MockClient::Block &b)
{
    d << '[' << b.start << ',' << b.end << ']';
    return d;
}
301

302
class tst_Preprocessor : public QObject
303
{
304
305
306
    Q_OBJECT

protected:
307
    QByteArray preprocess(const QString &fileName, QByteArray * /*errors*/, bool nolines) {
308
309
310
311
        //### TODO: hook up errors
        QByteArray output;
        Environment env;
        MockClient client(&env, &output);
312
        client.sourceNeeded("data/" + fileName, nolines);
313
314
        return output;
    }
315
    static QString simplified(QByteArray buf);
316

317
private:
318
    void compare_input_output(bool keepComments = false);
319

320
private slots:
321
322
    void va_args();
    void named_va_args();
323
    void extra_va_args();
324
325
    void defined();
    void defined_data();
326
327
    void empty_macro_args();
    void macro_args_count();
328
    void invalid_param_count();
329
    void objmacro_expanding_as_fnmacro_notification();
330
    void macro_uses();
Leandro Melo's avatar
Leandro Melo committed
331
    void macro_uses_lines();
332
    void macro_arguments_notificatin();
333
    void unfinished_function_like_macro_call();
Erik Verbruggen's avatar
Erik Verbruggen committed
334
    void nasty_macro_expansion();
335
336
    void glib_attribute();
    void builtin__FILE__();
337
    void blockSkipping();
Erik Verbruggen's avatar
Erik Verbruggen committed
338
    void includes_1();
339
340
    void dont_eagerly_expand();
    void dont_eagerly_expand_data();
341
342
    void comparisons_data();
    void comparisons();
343
    void comments_before_args();
344
345
    void comments_within();
    void comments_within_data();
346
347
    void comments_within2();
    void comments_within2_data();
348
349
    void multitokens_argument();
    void multitokens_argument_data();
350
351
    void multiline_strings();
    void multiline_strings_data();
352
353
    void skip_unknown_directives();
    void skip_unknown_directives_data();
354
355
    void include_guard();
    void include_guard_data();
356
357
};

358
359
360
361
362
363
364
// Remove all #... lines, and 'simplify' string, to allow easily comparing the result
// Also, remove all unneeded spaces: keep only to ensure identifiers are separated.
// NOTE: may not correctly handle underscore in identifiers
QString tst_Preprocessor::simplified(QByteArray buf)
{
    QString out;
    QList<QByteArray> lines = buf.split('\n');
365
    foreach (const QByteArray &line, lines) {
366
367
368
369
        if (!line.startsWith('#')) {
            out.append(' ');
            out.append(line);
        }
370
    }
371
372

    out = out.simplified();
373
374
375
376
    for (int i = 1; i < out.length() - 1; ) {
        if (out.at(i).isSpace()
                && !(out.at(i-1).isLetterOrNumber()
                && out.at(i+1).isLetterOrNumber()))
377
378
379
380
381
382
383
384
            out.remove(i,1);
        else
            i++;
    }

    return out;
}

385
386
387
388
389
390
void tst_Preprocessor::va_args()
{
    Client *client = 0; // no client.
    Environment env;

    Preprocessor preprocess(client, &env);
391
392
393
394
395
396
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
                                                "#define foo(...) int f(__VA_ARGS__);\n"
                                                "\nfoo(  )\n"
                                                "\nfoo(int a)\n"
                                                "\nfoo(int a,int b)\n",
                                             true, false);
397

398
399
    preprocessed = preprocessed.simplified();
//    DUMP_OUTPUT(preprocessed);
400
    QCOMPARE(simplified(preprocessed), QString("int f();int f(int a);int f(int a,int b);"));
401
402
403
404
405
406
407
408
}

void tst_Preprocessor::named_va_args()
{
    Client *client = 0; // no client.
    Environment env;

    Preprocessor preprocess(client, &env);
409
410
411
412
413
414
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
                                                "\n#define foo(ARGS...) int f(ARGS);"
                                                "\nfoo(  )\n"
                                                "\nfoo(int a)\n"
                                                "\nfoo(int a,int b)\n",
                                             true, false);
415

416
    preprocessed = preprocessed.simplified();
417
    QCOMPARE(simplified(preprocessed), QString("int f();int f(int a);int f(int a,int b);"));
418
419
}

420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
void tst_Preprocessor::extra_va_args()
{
    Client *client = 0; // no client.
    Environment env;

    Preprocessor preprocess(client, &env);
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
                                                "#define foo(ret, ...) ret f(__VA_ARGS__);\n"
                                                "\nfoo(int)\n"
                                                "\nfoo(float,int b)\n"
                                                "\nfoo(long,int b,int c)\n",
                                             true, false);

    preprocessed = preprocessed.simplified();
    QCOMPARE(simplified(preprocessed), QString("int f();float f(int b);long f(int b,int c);"));
}

437
void tst_Preprocessor::empty_macro_args()
438
439
440
441
442
{
    Client *client = 0; // no client.
    Environment env;

    Preprocessor preprocess(client, &env);
443
444
445
446
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
                                                "\n#define foo(a,b) a int b;"
                                                "\nfoo(const,cVal)\n"
                                                "\nfoo(,Val)\n"
447
448
449
                                                "\nfoo( ,Val2)\n"
                                                "\nfoo(,)\n"
                                                "\nfoo(, )\n",
450
                                             true, false);
451

452
453
    preprocessed = preprocessed.simplified();
//    DUMP_OUTPUT(preprocessed);
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
    QCOMPARE(simplified(preprocessed),
             QString("const int cVal;int Val;int Val2;int;int;"));
}

void tst_Preprocessor::macro_args_count()
{
    Environment env;
    QByteArray output;
    MockClient client(&env, &output);
    Preprocessor preprocess(&client, &env);
    preprocess.run(QLatin1String("<stdin>"),
                   "#define foo(a,b) a int b;\n"
                   "foo(const,cVal)\n"
                   "foo(, i)\n"
                   "foo(,Val)\n"
                   "foo( ,Val2)\n"
                   "foo(,)\n"
                   "foo(, )\n"
                   "#define bar(a)\n"
                   "bar()\n"
                   "bar(i)\n",
                   true, false);

    QCOMPARE(client.macroArgsCount(),
             QList<int>() << 2 // foo(const,cVal)
                          << 2 // foo(, i)
                          << 2 // foo(,Val)
                          << 2 // foo( , Val2)
                          << 2 // foo(,)
                          << 2 // foo(, )
                          << 1 // bar()
                          << 1 // bar(i)
            );

488
489
}

490
void tst_Preprocessor::invalid_param_count()
491
{
492
    Environment env;
493
494
495
496
497
498
499
500
501
502
503
    QByteArray output;
    MockClient client(&env, &output);
    Preprocessor preprocess(&client, &env);
    // The following are illegal, but shouldn't crash the preprocessor.
    preprocess.run(QLatin1String("<stdin>"),
                   "\n#define foo(a,b) int f(a,b);"
                   "\n#define ARGS(t)  t a,t b"
                   "\nfoo(ARGS(int))"
                   "\nfoo()"
                   "\nfoo(int a, int b, int c)",
                   true, false);
504

505
506
    // Output is not that relevant but check that nothing triggered expansion.
    QCOMPARE(client.macroArgsCount(), QList<int>());
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
}

void tst_Preprocessor::macro_uses()
{
    QByteArray buffer = QByteArray("\n#define FOO 8"
                                   "\n#define BAR 9"
                                   "\nvoid test(){"
                                   "\n\tint x=FOO;"
                                   "\n\tint y=BAR;"
                                   "\n}");

    QByteArray output;
    Environment env;
    MockClient client(&env, &output);

    Preprocessor preprocess(&client, &env);
523
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"), buffer);
524
525
526
    QCOMPARE(simplified(preprocessed), QString("void test(){int x=8;int y=9;}"));
    QCOMPARE(client.expandedMacros(), QList<QByteArray>() << QByteArray("FOO") << QByteArray("BAR"));
    QCOMPARE(client.expandedMacrosOffset(), QList<unsigned>() << buffer.indexOf("FOO;") << buffer.indexOf("BAR;"));
527
528
    QCOMPARE(client.definedMacros(), QList<QByteArray>() << QByteArray("FOO") << QByteArray("BAR"));
    QCOMPARE(client.definedMacrosLine(), QList<unsigned>() << 2 << 3);
529
530
}

Leandro Melo's avatar
Leandro Melo committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
void tst_Preprocessor::macro_uses_lines()
{
    QByteArray buffer("#define FOO\n"
                      "FOO\n"
                      "\n"
                      "#define HEADER <test>\n"
                      "#include HEADER\n"
                      "\n"
                      "#define DECLARE(C, V) struct C {}; C V;\n"
                      "#define ABC X\n"
                      "DECLARE(Test, test)\n"
                      "\n"
                      "int abc;\n"
                      "#define NOTHING(C)\n"
                      "NOTHING(abc)\n"
                      "\n"
                      "#define ENABLE(FEATURE) (defined ENABLE_##FEATURE && ENABLE_##FEATURE)\n"
                      "#define ENABLE_COOL 1\n"
                      "void fill();\n"
                      "#if ENABLE(COOL)\n"
                      "class Cool {};\n"
                      "#endif\n"
553
554
555
                      "int cool = ENABLE_COOL;\n"
                      "#define OTHER_ENABLE(FEATURE) ENABLE(FEATURE)\n"
                      "#define MORE(LESS) FOO ENABLE(LESS)\n");
Leandro Melo's avatar
Leandro Melo committed
556
557
558
559
560
561
562

    QByteArray output;
    Environment env;
    MockClient client(&env, &output);
    Preprocessor preprocess(&client, &env);
    preprocess.run(QLatin1String("<stdin>"), buffer);

563
564
565
566
567
568
    QCOMPARE(client.macroUsesLine().value("FOO"), QList<unsigned>() << 2U << 23U);
    QCOMPARE(client.macroUsesLine().value("HEADER"), QList<unsigned>() << 5U);
    QCOMPARE(client.macroUsesLine().value("DECLARE"), QList<unsigned>() << 9U);
    QCOMPARE(client.macroUsesLine().value("NOTHING"), QList<unsigned>() << 13U);
    QCOMPARE(client.macroUsesLine().value("ENABLE"), QList<unsigned>() << 18U << 22U << 23U);
    QCOMPARE(client.macroUsesLine().value("ENABLE_COOL"), QList<unsigned>() << 21U);
Leandro Melo's avatar
Leandro Melo committed
569
    QCOMPARE(client.expandedMacrosOffset(), QList<unsigned>()
570
             << buffer.lastIndexOf("FOO\n")
Leandro Melo's avatar
Leandro Melo committed
571
572
573
574
             << buffer.lastIndexOf("HEADER")
             << buffer.lastIndexOf("DECLARE")
             << buffer.lastIndexOf("NOTHING")
             << buffer.lastIndexOf("ENABLE(COOL)")
575
576
577
578
             << buffer.lastIndexOf("ENABLE_COOL")
             << buffer.lastIndexOf("ENABLE(FEATURE)")
             << buffer.lastIndexOf("FOO ")
             << buffer.lastIndexOf("ENABLE(LESS)"));
Leandro Melo's avatar
Leandro Melo committed
579
580
}

581
void tst_Preprocessor::multitokens_argument_data()
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
    QTest::addColumn<QByteArray>("input");
    QTest::addColumn<QByteArray>("output");

    QByteArray original;
    QByteArray expected;

    original =
            "#define foo(ARGS) int f(ARGS)\n"
            "foo(int a);\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "# expansion begin 30,3 ~3 2:4 2:8 ~1\n"
            "int f(int a)\n"
            "# expansion end\n"
            "# 2 \"<stdin>\"\n"
            "          ;\n";
    QTest::newRow("case 1") << original << expected;

    original =
            "#define foo(ARGS) int f(ARGS)\n"
            "foo(int   \n"
            "    a);\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "# expansion begin 30,3 ~3 2:4 3:4 ~1\n"
            "int f(int a)\n"
            "# expansion end\n"
            "# 3 \"<stdin>\"\n"
            "      ;\n";
    QTest::newRow("case 2") << original << expected;

    original =
            "#define foo(ARGS) int f(ARGS)\n"
            "foo(int a = 0);\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "# expansion begin 30,3 ~3 2:4 2:8 2:10 2:12 ~1\n"
            "int f(int a = 0)\n"
            "# expansion end\n"
            "# 2 \"<stdin>\"\n"
            "              ;\n";
    QTest::newRow("case 3") << original << expected;

    original =
            "#define foo(X) int f(X = 0)\n"
            "foo(int \n"
            "    a);\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "# expansion begin 28,3 ~3 2:4 3:4 ~3\n"
            "int f(int a = 0)\n"
            "# expansion end\n"
            "# 3 \"<stdin>\"\n"
            "      ;\n";
    QTest::newRow("case 4") << original << expected;
}

void tst_Preprocessor::multitokens_argument()
{
    compare_input_output();
647
648
}

649
650
651
652
653
654
655
void tst_Preprocessor::objmacro_expanding_as_fnmacro_notification()
{
    QByteArray output;
    Environment env;
    MockClient client(&env, &output);

    Preprocessor preprocess(&client, &env);
656
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
657
658
659
660
661
662
663
664
665
666
667
668
669
670
                                         QByteArray("\n#define bar(a,b) a + b"
                                                    "\n#define foo bar"
                                                    "\nfoo(1, 2)\n"));

    QVERIFY(client.expandedMacros() == (QList<QByteArray>() << QByteArray("foo")));
}

void tst_Preprocessor::macro_arguments_notificatin()
{
    QByteArray output;
    Environment env;
    MockClient client(&env, &output);

    Preprocessor preprocess(&client, &env);
671
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
672
673
674
675
676
677
678
679
680
681
                                         QByteArray("\n#define foo(a,b) a + b"
                                                    "\n#define arg(a) a"
                                                    "\n#define value  2"
                                                    "\nfoo(arg(1), value)\n"));

    QVERIFY(client.expandedMacros() == (QList<QByteArray>() << QByteArray("foo")
                                                            << QByteArray("arg")
                                                            << QByteArray("value")));
}

682
683
684
685
686
687
void tst_Preprocessor::unfinished_function_like_macro_call()
{
    Client *client = 0; // no client.
    Environment env;

    Preprocessor preprocess(client, &env);
688
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
689
690
691
692
693
694
695
696
697
698
699
                                             QByteArray("\n"
                                                        "#define foo(a,b) a + b\n"
                                                        "foo(1, 2\n"));
    QByteArray expected__("# 1 \"<stdin>\"\n"
                          "\n"
                          "\n"
                          "# expansion begin 24,3 3:4 ~1 3:7\n"
                          "1 + 2\n"
                          "# expansion end\n"
                          "# 4 \"<stdin>\"\n");

700
//    DUMP_OUTPUT(preprocessed);
701
    QCOMPARE(preprocessed, expected__);
702
703
}

Erik Verbruggen's avatar
Erik Verbruggen committed
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
void tst_Preprocessor::nasty_macro_expansion()
{
    QByteArray input("\n"
                     "#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))\n"
                     "#define is_power_of_two(x)      ( !((x) & ((x)-1)) )\n"
                     "#define low_bit_mask(x)         ( ((x)-1) & ~(x) )\n"
                     "#define is_valid_mask(x)        is_power_of_two(1LU + (x) + low_bit_mask(x))\n"
                     "#define compile_ffs2(__x) \\\n"
                     "        __builtin_choose_expr(((__x) & 0x1), 0, 1)\n"
                     "#define compile_ffs4(__x) \\\n"
                     "        __builtin_choose_expr(((__x) & 0x3), \\\n"
                     "                              (compile_ffs2((__x))), \\\n"
                     "                              (compile_ffs2((__x) >> 2) + 2))\n"
                     "#define compile_ffs8(__x) \\\n"
                     "        __builtin_choose_expr(((__x) & 0xf), \\\n"
                     "                              (compile_ffs4((__x))), \\\n"
                     "                              (compile_ffs4((__x) >> 4) + 4))\n"
                     "#define compile_ffs16(__x) \\\n"
                     "        __builtin_choose_expr(((__x) & 0xff), \\\n"
                     "                              (compile_ffs8((__x))), \\\n"
                     "                              (compile_ffs8((__x) >> 8) + 8))\n"
                     "#define compile_ffs32(__x) \\\n"
                     "        __builtin_choose_expr(((__x) & 0xffff), \\\n"
                     "                              (compile_ffs16((__x))), \\\n"
                     "                              (compile_ffs16((__x) >> 16) + 16))\n"
                     "#define FIELD_CHECK(__mask, __type)                     \\\n"
                     "        BUILD_BUG_ON(!(__mask) ||                       \\\n"
                     "                     !is_valid_mask(__mask) ||          \\\n"
                     "                     (__mask) != (__type)(__mask))      \\\n"
                     "\n"
                     "#define FIELD32(__mask)                         \\\n"
                     "({                                              \\\n"
                     "        FIELD_CHECK(__mask, u32);               \\\n"
                     "        (struct rt2x00_field32) {               \\\n"
                     "                compile_ffs32(__mask), (__mask) \\\n"
                     "        };                                      \\\n"
                     "})\n"
                     "#define BBPCSR                          0x00f0\n"
                     "#define BBPCSR_BUSY                     FIELD32(0x00008000)\n"
                     "#define WAIT_FOR_BBP(__dev, __reg)  \\\n"
                     "        rt2x00pci_regbusy_read((__dev), BBPCSR, BBPCSR_BUSY, (__reg))\n"
                     "if (WAIT_FOR_BBP(rt2x00dev, &reg)) {}\n"
                     );

    Client *client = 0; // no client.
    Environment env;

    Preprocessor preprocess(client, &env);
752
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"), input);
Erik Verbruggen's avatar
Erik Verbruggen committed
753
754
755
756

    QVERIFY(!preprocessed.contains("FIELD32"));
}

757
void tst_Preprocessor::glib_attribute()
758
759
{
    Environment env;
760
    Preprocessor preprocess(0, &env);
761
    QByteArray preprocessed = preprocess.run(
762
763
764
765
766
767
                QLatin1String("<stdin>"),
                QByteArray("\n"
                           "# define _GLIBCXX_VISIBILITY(V) __attribute__ ((__visibility__ (#V)))\n"
                           "namespace std _GLIBCXX_VISIBILITY(default) {\n"
                           "}\n"
                           ));
768
769
770
771
    const QByteArray result____ =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
772
            "namespace std\n"
773
774
775
            "# expansion begin 85,19 ~9\n"
            "__attribute__ ((__visibility__ (\"default\")))\n"
            "# expansion end\n"
Erik Verbruggen's avatar
Erik Verbruggen committed
776
777
            "# 3 \"<stdin>\"\n"
            "                                           {\n"
778
779
            "}\n";

780
//    DUMP_OUTPUT(preprocessed);
781
782
783
    QCOMPARE(preprocessed, result____);
}

784
void tst_Preprocessor::builtin__FILE__()
785
786
787
788
789
{
    Client *client = 0; // no client.
    Environment env;

    Preprocessor preprocess(client, &env);
790
    QByteArray preprocessed = preprocess.run(
791
792
793
794
                QLatin1String("some-file.c"),
                QByteArray("const char *f = __FILE__\n"
                           ));
    const QByteArray result____ =
795
            "# 1 \"some-file.c\"\n"
796
797
            "const char *f = \"some-file.c\"\n";

798
799
800
801
802
803
804
805
806
807
    QCOMPARE(preprocessed, result____);
}

void tst_Preprocessor::comparisons_data()
{
    QTest::addColumn<QString>("infile");
    QTest::addColumn<QString>("outfile");
    QTest::addColumn<QString>("errorfile");

    QTest::newRow("do nothing") << "noPP.1.cpp" << "noPP.1.cpp" << "";
808
    QTest::newRow("no PP 2") << "noPP.2.cpp" << "noPP.2.cpp" << "";
809
810
811
812
813
814
815
816
817
818
    QTest::newRow("identifier-expansion 1")
        << "identifier-expansion.1.cpp" << "identifier-expansion.1.out.cpp" << "";
    QTest::newRow("identifier-expansion 2")
        << "identifier-expansion.2.cpp" << "identifier-expansion.2.out.cpp" << "";
    QTest::newRow("identifier-expansion 3")
        << "identifier-expansion.3.cpp" << "identifier-expansion.3.out.cpp" << "";
    QTest::newRow("identifier-expansion 4")
        << "identifier-expansion.4.cpp" << "identifier-expansion.4.out.cpp" << "";
    QTest::newRow("identifier-expansion 5")
        << "identifier-expansion.5.cpp" << "identifier-expansion.5.out.cpp" << "";
hjk's avatar
hjk committed
819
820
821
822
823
824
825
826
    QTest::newRow("reserved 1")
        << "reserved.1.cpp" << "reserved.1.out.cpp" << "";
    QTest::newRow("recursive 1")
        << "recursive.1.cpp" << "recursive.1.out.cpp" << "";
    QTest::newRow("macro_pounder_fn")
        << "macro_pounder_fn.c" << "" << "";
    QTest::newRow("macro_expand")
        << "macro_expand.c" << "macro_expand.out.c" << "";
827
828
    QTest::newRow("macro_expand_1")
        << "macro_expand_1.cpp" << "macro_expand_1.out.cpp" << "";
hjk's avatar
hjk committed
829
830
831
832
833
834
    QTest::newRow("macro-test")
        << "macro-test.cpp" << "macro-test.out.cpp" << "";
    QTest::newRow("empty-macro")
        << "empty-macro.cpp" << "empty-macro.out.cpp" << "";
    QTest::newRow("empty-macro 2")
        << "empty-macro.2.cpp" << "empty-macro.2.out.cpp" << "";
835
836
    QTest::newRow("poundpound 1")
        << "poundpound.1.cpp" << "poundpound.1.out.cpp" << "";
837
838
839
840
841
842
843
844
845
}

void tst_Preprocessor::comparisons()
{
    QFETCH(QString, infile);
    QFETCH(QString, outfile);
    QFETCH(QString, errorfile);

    QByteArray errors;
846
    QByteArray preprocessed = preprocess(infile, &errors, infile == outfile);
847

848

hjk's avatar
hjk committed
849
    // DUMP_OUTPUT(preprocessed);
850
851

    if (!outfile.isEmpty()) {
hjk's avatar
hjk committed
852
853
854
        // These weird underscores are here to make the name as long as
        // "preprocessed", so the QCOMPARE error messages are nicely aligned.
        QByteArray output____ = loadSource("data/" + outfile);
855
        //    QCOMPARE(preprocessed, output____);
hjk's avatar
hjk committed
856
857
        QCOMPARE(QString::fromUtf8(preprocessed.constData()),
                 QString::fromUtf8(output____.constData()));
858
859
860
    }

    if (!errorfile.isEmpty()) {
hjk's avatar
hjk committed
861
862
863
        QByteArray errorFileContents = loadSource("data/" + errorfile);
        QCOMPARE(QString::fromUtf8(errors.constData()),
                 QString::fromUtf8(errorFileContents.constData()));
864
865
866
867
868
869
870
871
872
    }
}

void tst_Preprocessor::blockSkipping()
{
    QByteArray output;
    Environment env;
    MockClient client(&env, &output);
    Preprocessor pp(&client, &env);
873
    /*QByteArray preprocessed =*/ pp.run(
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
                QLatin1String("<stdin>"),
                QByteArray("#if 0\n"
                           "\n"
                           "int yes;\n"
                           "\n"
                           "#elif 0\n"
                           "\n"
                           "int no;\n"
                           "\n"
                           "#else // foobar\n"
                           "\n"
                           "void also_not;\n"
                           "\n"
                           "#endif\n"
                           ));
Erik Verbruggen's avatar
Erik Verbruggen committed
889

890
891
892
893
894
    QList<MockClient::Block> blocks = client.skippedBlocks();
    QCOMPARE(blocks.size(), 1);
    MockClient::Block b = blocks.at(0);
    QCOMPARE(b.start, 6U);
    QCOMPARE(b.end, 34U);
895
896
}

Erik Verbruggen's avatar
Erik Verbruggen committed
897
898
899
900
901
902
void tst_Preprocessor::includes_1()
{
    QByteArray output;
    Environment env;
    MockClient client(&env, &output);
    Preprocessor pp(&client, &env);
903
    /*QByteArray preprocessed =*/ pp.run(
Erik Verbruggen's avatar
Erik Verbruggen committed
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
                QLatin1String("<stdin>"),
                QByteArray("#define FOO <foo.h>\n"
                           "#define BAR \"bar.h\"\n"
                           "\n"
                           "#include FOO\n"
                           "#include BAR\n"
                           "\n"
                           "#include <zoo.h>\n"
                           "#include \"mooze.h\"\n"
                           ));

    QList<Include> incs = client.recordedIncludes();
//    qDebug()<<incs;
    QCOMPARE(incs.size(), 4);
    QCOMPARE(incs.at(0).fileName, QLatin1String("foo.h"));
    QCOMPARE(incs.at(0).type, Client::IncludeGlobal);
    QCOMPARE(incs.at(0).line, 4U);
    QCOMPARE(incs.at(1).fileName, QLatin1String("bar.h"));
    QCOMPARE(incs.at(1).type, Client::IncludeLocal);
    QCOMPARE(incs.at(1).line, 5U);
    QCOMPARE(incs.at(2).fileName, QLatin1String("zoo.h"));
    QCOMPARE(incs.at(2).type, Client::IncludeGlobal);
    QCOMPARE(incs.at(2).line, 7U);
    QCOMPARE(incs.at(3).fileName, QLatin1String("mooze.h"));
    QCOMPARE(incs.at(3).type, Client::IncludeLocal);
    QCOMPARE(incs.at(3).line, 8U);
}

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
void tst_Preprocessor::defined()
{
    QFETCH(bool, xdefined);
    QFETCH(bool, ydefined);
    QFETCH(QString, input);
    QByteArray output;
    Environment env;
    MockClient client(&env, &output);
    Preprocessor pp(&client, &env);
    pp.run(QLatin1String("<stdin>"), input.toLatin1(), false, true);
    QList<QByteArray> expected;
    if (xdefined)
        expected.append("X");
    if (ydefined)
        expected.append("Y");
    if (client.definedMacros() != expected)
        qWarning() << "\nSource: " << input.replace('\n', "    ");
    QCOMPARE(client.definedMacros(), expected);
}

void tst_Preprocessor::defined_data()
{
    QTest::addColumn<bool>("xdefined");
    QTest::addColumn<bool>("ydefined");
    QTest::addColumn<QString>("input");

    QTest::newRow("1a") << true << true <<
        "#define X\n#if defined(X)\n#define Y\n#endif";
    QTest::newRow("1b") << true << true <<
        "#define X\n#if defined X \n#define Y\n#endif";
    QTest::newRow("1c") << true << true <<
        "#define X\n#ifdef X \n#define Y\n#endif";

    QTest::newRow("2a") << false << false <<
        "#if defined(X)\n#define Y\n#endif";
    QTest::newRow("2b") << false << false <<
        "#if defined X \n#define Y\n#endif";
    QTest::newRow("2c") << false << false <<
        "#ifdef X \n#define Y\n#endif";

    QTest::newRow("3a") << true << false <<
        "#define X\n#if !defined(X)\n#define Y\n#endif";
    QTest::newRow("3b") << true << false <<
        "#define X\n#if !defined X \n#define Y\n#endif";
    QTest::newRow("3c") << true << false <<
        "#define X\n#ifndef X \n#define Y\n#endif";

    QTest::newRow("4a") << false << true <<
        "#if !defined(X)\n#define Y\n#endif";
    QTest::newRow("4b") << false << true <<
        "#if !defined X \n#define Y\n#endif";
    QTest::newRow("4c") << false << true <<
        "#ifndef X \n#define Y\n#endif";
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005

    QTest::newRow("5a") << false << false <<
        "#if !defined(X) && (defined(Y))\n"
        "#define X\n"
        "#endif\n";
    QTest::newRow("5b") << false << false <<
        "#if !defined(X) && defined(Y)\n"
        "#define X\n"
        "#endif\n";
    QTest::newRow("5c") << false << false <<
        "#if !defined(X) && 0"
        "#define X\n"
        "#endif\n";
    QTest::newRow("5d") << false << false <<
        "#if (!defined(X)) && defined(Y)\n"
        "#define X\n"
        "#endif\n";
    QTest::newRow("5d") << false << false <<
        "#if (define(Y))\n"
        "#define X\n"
        "#endif\n";
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

    QTest::newRow("6a") << true << true <<
        "#define X 0x040500\n"
        "#if X > 0x040000\n"
        "#define Y 1\n"
        "#endif\n";
    QTest::newRow("6b") << true << true <<
        "#define X 0x040500\n"
        "#if X >= 0x040000\n"
        "#define Y 1\n"
        "#endif\n";
    QTest::newRow("6c") << true << false <<
        "#define X 0x040500\n"
        "#if X == 0x040000\n"
        "#define Y 1\n"
        "#endif\n";
    QTest::newRow("6d") << true << true <<
        "#define X 0x040500\n"
        "#if X == 0x040500\n"
        "#define Y 1\n"
        "#endif\n";
    QTest::newRow("6e") << true << false <<
        "#define X 0x040500\n"
        "#if X < 0x040000\n"
        "#define Y 1\n"
        "#endif\n";
    QTest::newRow("6f") << true << false <<
        "#define X 0x040500\n"
        "#if X <= 0x040000\n"
        "#define Y 1\n"
        "#endif\n";
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056

    QTest::newRow("incomplete defined 1") << true << true <<
        "#define X 0x040500\n"
        "#if defined(X\n"
        "#define Y 1\n"
        "#endif\n";
    QTest::newRow("incomplete defined 2") << false << false <<
        "#if defined(X\n"
        "#define Y 1\n"
        "#endif\n";
    QTest::newRow("complete defined 1") << true << true <<
        "#define X 0x040500\n"
        "#if defined(X )\n"
        "#define Y 1\n"
        "#endif\n";
    QTest::newRow("complete defined 2") << true << true <<
        "#define X 0x040500\n"
        "#if defined(X/*xxx*/)\n"
        "#define Y 1\n"
        "#endif\n";
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
void tst_Preprocessor::dont_eagerly_expand_data()
{
    QTest::addColumn<QByteArray>("input");
    QTest::addColumn<QByteArray>("output");

    QByteArray original;
    QByteArray expected;

    // Expansion must be processed upon invocation of the macro. Therefore a particular
    // identifier within a define must not be expanded (in the case it matches an
    // already known macro) during the processor directive handling, but only when
    // it's actually "used". Naturally, if it's still not replaced after an invocation
    // it should then be expanded. This is consistent with clang and gcc for example.

    original = "#define T int\n"
               "#define FOO(T) T\n"
               "FOO(double)\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "# expansion begin 31,3 3:4\n"
            "double\n"
            "# expansion end\n"
            "# 4 \"<stdin>\"\n";
    QTest::newRow("case 1") << original << expected;

    original = "#define T int\n"
               "#define FOO(X) T\n"
               "FOO(double)\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "# expansion begin 31,3 ~1\n"
            "int\n"
            "# expansion end\n"
            "# 4 \"<stdin>\"\n";
    QTest::newRow("case 2") << original << expected;
}

void tst_Preprocessor::dont_eagerly_expand()
{
    compare_input_output();
}

void tst_Preprocessor::comments_within()
{
    compare_input_output();
}
void tst_Preprocessor::comments_within_data()
{
    QTest::addColumn<QByteArray>("input");
    QTest::addColumn<QByteArray>("output");

    QByteArray original;
    QByteArray expected;

    original = "#define FOO int x;\n"
               "\n"
               "   // comment\n"
               "   // comment\n"
               "   // comment\n"
               "   // comment\n"
               "FOO\n"
               "x = 10\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "# expansion begin 76,3 ~3\n"
            "int x;\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n"
            "x = 10\n";
    QTest::newRow("case 1") << original << expected;


    original = "#define FOO int x;\n"
               "\n"
               "   /* comment\n"
               "      comment\n"
               "      comment\n"
               "      comment */\n"
               "FOO\n"
               "x = 10\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "# expansion begin 79,3 ~3\n"
            "int x;\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n"
            "x = 10\n";
    QTest::newRow("case 2") << original << expected;


    original = "#define FOO int x;\n"
               "\n"
               "   // comment\n"
               "   // comment\n"
               "   // comment\n"
               "   // comment\n"
               "FOO\n"
               "// test\n"
               "// test again\n"
               "x = 10\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "# expansion begin 76,3 ~3\n"
            "int x;\n"
            "# expansion end\n"
            "# 10 \"<stdin>\"\n"
            "x = 10\n";
    QTest::newRow("case 3") << original << expected;


    original = "#define FOO int x;\n"
               "\n"
               "   /* comment\n"
               "      comment\n"
               "      comment\n"
               "      comment */\n"
               "FOO\n"
               "/*  \n"
               "*/\n"
               "x = 10\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "# expansion begin 79,3 ~3\n"
            "int x;\n"
            "# expansion end\n"
            "# 10 \"<stdin>\"\n"
            "x = 10\n";
    QTest::newRow("case 4") << original << expected;
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

    original = "#define FOO(x, y) { (void)x; (void)y; }\n"
               "\n"
               "void foo() {\n"
               "   FOO(10,\n"
               "       //comment\n"
               "       12\n"
               "}\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "void foo() {\n"
            "# expansion begin 57,3 ~4 4:7 ~4 6:7 7:0 ~2\n"
            "{ (void)10; (void)12}; }\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n";
    QTest::newRow("case 5") << original << expected;

    original = "#define FOO(x, y) { (void)x; (void)y; }\n"
               "\n"
               "void foo() {\n"
               "   FOO(10,\n"
               "       //tricky*/comment\n"
               "       12\n"
               "}\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "void foo() {\n"
            "# expansion begin 57,3 ~4 4:7 ~4 6:7 7:0 ~2\n"
            "{ (void)10; (void)12}; }\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n";
    QTest::newRow("case 6") << original << expected;
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270

    original =
            "#define FOO 0 //coment\n"
            "#define BAR (1 == FOO)\n"
            "void foo() {\n"
            "    if (BAR) {}\n"
            "}\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "void foo() {\n"
            "    if (\n"
            "# expansion begin 67,3 ~5\n"
            "(1 == 0)\n"
            "# expansion end\n"
            "# 4 \"<stdin>\"\n"
            "           ) {}\n"
            "}\n";
    QTest::newRow("case 7") << original << expected;
1271
1272
}

1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
void tst_Preprocessor::comments_before_args()
{
    Client *client = 0; // no client.
    Environment env;

    Preprocessor preprocess(client, &env);
    preprocess.setKeepComments(true);
    QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
                                                "\n#define foo(a,b) int a = b;"
                                                "\nfoo/*C comment*/(a,1)\n"
                                                "\nfoo/**Doxygen comment*/(b,2)\n"
                                                "\nfoo//C++ comment\n(c,3)\n"
                                                "\nfoo///Doxygen C++ comment\n(d,4)\n"
                                                "\nfoo/*multiple*///comments\n/**as well*/(e,5)\n",
                                             true, false);

    preprocessed = preprocessed.simplified();
//    DUMP_OUTPUT(preprocessed);
    QCOMPARE(simplified(preprocessed),
             QString("int a=1;int b=2;int c=3;int d=4;int e=5;"));
}

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
void tst_Preprocessor::comments_within2()
{
    compare_input_output(true);
}

void tst_Preprocessor::comments_within2_data()
{
    QTest::addColumn<QByteArray>("input");
    QTest::addColumn<QByteArray>("output");

    QByteArray original;
    QByteArray expected;

    original = "#define FOO int x;\n"
               "\n"
               "   // comment\n"
               "   // comment\n"
               "   // comment\n"
               "   // comment\n"
               "FOO\n"
               "x = 10\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "   // comment\n"
            "   // comment\n"
            "   // comment\n"
            "   // comment\n"
            "# expansion begin 76,3 ~3\n"
            "int x;\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n"
            "x = 10\n";
    QTest::newRow("case 1") << original << expected;


    original = "#define FOO int x;\n"
               "\n"
               "   /* comment\n"
               "      comment\n"
               "      comment\n"
               "      comment */\n"
               "FOO\n"
               "x = 10\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "   /* comment\n"
            "      comment\n"
            "      comment\n"
            "      comment */\n"
            "# expansion begin 79,3 ~3\n"
            "int x;\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n"
            "x = 10\n";
    QTest::newRow("case 2") << original << expected;


    original = "#define FOO int x;\n"
               "\n"
               "   // comment\n"
               "   // comment\n"
               "   // comment\n"
               "   // comment\n"
               "FOO\n"
               "// test\n"
               "// test again\n"
               "x = 10\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "   // comment\n"
            "   // comment\n"
            "   // comment\n"
            "   // comment\n"
            "# expansion begin 76,3 ~3\n"
            "int x;\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n"
            "// test\n"
            "// test again\n"
            "x = 10\n";
    QTest::newRow("case 3") << original << expected;


    original = "#define FOO int x;\n"
               "\n"
               "void foo() {   /* comment\n"
               "      comment\n"
               "      comment\n"
               "      comment */\n"
               "FOO\n"
               "/*  \n"
               "*/\n"
               "x = 10\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "void foo() {   /* comment\n"
            "      comment\n"
            "      comment\n"
            "      comment */\n"
            "# expansion begin 91,3 ~3\n"
            "int x;\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n"
            "/*  \n"
            "*/\n"
            "x = 10\n";
    QTest::newRow("case 4") << original << expected;
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


    original = "#define FOO(x, y) { (void)x; (void)y; }\n"
               "\n"
               "void foo() {\n"
               "   FOO(10,\n"
               "       //comment\n"
               "       12\n"
               "}\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "void foo() {\n"
            "# expansion begin 57,3 ~4 4:7 ~5 6:7 7:0 ~2\n"
            "{ (void)10; (void)/*comment*/ 12}; }\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n";
    QTest::newRow("case 5") << original << expected;

    original = "#define FOO(x, y) { (void)x; (void)y; }\n"
               "\n"
               "void foo() {\n"
               "   FOO(10,\n"
               "       //tricky*/comment\n"
               "       12\n"
               "}\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "void foo() {\n"
            "# expansion begin 57,3 ~4 4:7 ~5 6:7 7:0 ~2\n"
            "{ (void)10; (void)/*tricky*|comment*/ 12}; }\n"
            "# expansion end\n"
            "# 8 \"<stdin>\"\n";
    QTest::newRow("case 6") << original << expected;
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466

    original =
            "#define FOO 0 //coment\n"
            "#define BAR (1 == FOO)\n"
            "void foo() {\n"
            "    if (BAR) {}\n"
            "}\n";
    expected =
            "# 1 \"<stdin>\"\n"
            "\n"
            "\n"
            "void foo() {\n"
            "    if (\n"
            "# expansion begin 67,3 ~5\n"
            "(1 == 0)\n"
            "# expansion end\n"
            "# 4 \"<stdin>\"\n"
            "           ) {}\n"
            "}\n";
    QTest::newRow("case 7") << original << expected;
1467
1468
}

1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
void tst_Preprocessor::multiline_strings()
{
    compare_input_output();
}

void tst_Preprocessor::multiline_strings_data()
{
    QTest::addColumn<QByteArray>("input");
    QTest::addColumn<QByteArray>("output");

    QByteArray original;
    QByteArray expected;

    original = "const char *s = \"abc\\\n"
               "xyz\";\n";
    expected = "# 1 \"<stdin>\"\n"
               "const char *s = \"abc\\\n"
               "xyz\";\n";
    QTest::newRow("case 1") << original << expected;
}

1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
void tst_Preprocessor::skip_unknown_directives()
{
    compare_input_output();
}

void tst_Preprocessor::skip_unknown_directives_data()
{
    QTest::addColumn<QByteArray>("input");
    QTest::addColumn<QByteArray>("output");

    QByteArray original;
    QByteArray expected;

    // We should skip "weird" things when preprocessing. Particularly useful when we preprocess
    // a particular expression from a document which has already been processed.

    original = "# foo\n"
               "# 10 \"file.cpp\"\n"
               "# ()\n"
               "#\n";
    expected = "# 1 \"<stdin>\"\n";
    QTest::newRow("case 1") << original << expected;
}

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
void tst_Preprocessor::include_guard()
{
    QFETCH(QString, includeGuard);
    QFETCH(QString, input);

    QByteArray output;
    Environment env;
    MockClient client(&env, &output);
    Preprocessor preprocess(&client, &env);
    preprocess.setKeepComments(true);
    /*QByteArray prep =*/ preprocess.run(QLatin1String("<test-case>"), input);
    QCOMPARE(QString::fromUtf8(client.includeGuard()), includeGuard);
}

void tst_Preprocessor::include_guard_data()
{
    QTest::addColumn<QString>("includeGuard");
    QTest::addColumn<QString>("input");

    QTest::newRow("basic-test") << "BASIC_TEST"
                                << "#ifndef BASIC_TEST\n"
                                   "#define BASIC_TEST\n"
                                   "\n"
                                   "#endif // BASIC_TEST\n";
    QTest::newRow("comments-1") << "GUARD"
                                << "/* some\n"
                                   " * copyright\n"
                                   " * header.\n"
                                   " */\n"
                                   "#ifndef GUARD\n"
                                   "#define GUARD\n"
                                   "\n"
                                   "#endif // GUARD\n";
    QTest::newRow("comments-2") << "GUARD"
                                << "#ifndef GUARD\n"
                                   "#define GUARD\n"
                                   "\n"
                                   "#endif // GUARD\n"
                                   "/* some\n"
                                   " * trailing\n"
                                   " * comments.\n"
                                   " */\n"
                                   ;
    QTest::newRow("nested-ifdef") << "GUARD"
                                  << "#ifndef GUARD\n"
                                     "#define GUARD\n"
                                     "#ifndef NOT_GUARD\n"
                                     "#define NOT_GUARD\n"
                                     "#endif // NOT_GUARD\n"
                                     "\n"
                                     "#endif // GUARD\n"
                                     ;
    QTest::newRow("leading-tokens") << ""
                                    << "int i;\n"
                                       "#ifndef GUARD\n"
                                       "#define GUARD\n"
                                       "\n"
                                       "#endif // GUARD\n"
                                       ;
    QTest::newRow("trailing-tokens") << ""
                                     << "#ifndef GUARD\n"
                                        "#define GUARD\n"
                                        "\n"
                                        "#endif // GUARD\n"
                                        "int i;\n"
                                        ;
    QTest::newRow("surprising-but-correct") << "GUARD"
                                            << "#ifndef GUARD\n"
                                               "int i;\n"
                                               "\n"
                                               "#define GUARD\n"
                                               "#endif // GUARD\n"
                                               ;
    QTest::newRow("incomplete-1") << ""
                                  << "#ifndef GUARD\n"
                                     ;
    QTest::newRow("incomplete-2") << "GUARD"
                                  << "#ifndef GUARD\n"
                                     "#define GUARD\n"
                                     ;
}

1596
void tst_Preprocessor::compare_input_output(bool keepComments)
1597
1598
1599
1600
1601
1602
{
    QFETCH(QByteArray, input);
    QFETCH(QByteArray, output);

    Environment env;
    Preprocessor preprocess(0, &env);
1603
    preprocess.setKeepComments(keepComments);
1604
1605
1606
1607
    QByteArray prep = preprocess.run(QLatin1String("<stdin>"), input);
    QCOMPARE(output, prep);
}

1608
QTEST_APPLESS_MAIN(tst_Preprocessor)
1609

1610
#include "tst_preprocessor.moc"