summaryrefslogtreecommitdiff
path: root/src/plugins/clangcodemodel/test/clangbatchfileprocessor.cpp
blob: b73b9d75e57f3d710c6003db34c53b37dc69a1c7 (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
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "clangbatchfileprocessor.h"

#include <clangcodemodel/clangeditordocumentprocessor.h>

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icore.h>
#include <cppeditor/cpptoolsreuse.h>
#include <cppeditor/cpptoolstestcase.h>
#include <cppeditor/modelmanagertesthelper.h>
#include <cppeditor/projectinfo.h>
#include <projectexplorer/projectexplorer.h>
#include <texteditor/codeassist/assistinterface.h>
#include <texteditor/codeassist/assistproposalitem.h>
#include <texteditor/codeassist/completionassistprovider.h>
#include <texteditor/codeassist/genericproposalmodel.h>
#include <texteditor/codeassist/iassistprocessor.h>
#include <texteditor/codeassist/iassistproposal.h>
#include <texteditor/textdocument.h>
#include <texteditor/texteditor.h>

#include <utils/executeondestruction.h>
#include <utils/qtcassert.h>

#include <QDebug>
#include <QElapsedTimer>
#include <QFileInfo>
#include <QLoggingCategory>
#include <QSharedPointer>
#include <QString>
#include <QThread>

using namespace ProjectExplorer;

namespace ClangCodeModel {
namespace Internal {

static Q_LOGGING_CATEGORY(debug, "qtc.clangcodemodel.batch", QtWarningMsg);

static int timeOutFromEnvironmentVariable()
{
    const QByteArray timeoutAsByteArray = qgetenv("QTC_CLANG_BATCH_TIMEOUT");

    bool isConversionOk = false;
    const int intervalAsInt = timeoutAsByteArray.toInt(&isConversionOk);
    if (!isConversionOk) {
        qCDebug(debug, "Environment variable QTC_CLANG_BATCH_TIMEOUT is not set, assuming 30000.");
        return 30000;
    }

    return intervalAsInt;
}

int timeOutInMs()
{
    static int timeOut = timeOutFromEnvironmentVariable();
    return timeOut;
}

namespace {

class BatchFileLineTokenizer
{
public:
    BatchFileLineTokenizer(const QString &line);

    QString nextToken();

private:
    const QChar *advanceToTokenBegin();
    const QChar *advanceToTokenEnd();

    bool atEnd() const;
    bool atWhiteSpace() const;
    bool atQuotationMark() const;

private:
    bool m_isWithinQuotation = false;
    QString m_line;
    const QChar *m_currentChar;
};

BatchFileLineTokenizer::BatchFileLineTokenizer(const QString &line)
    : m_line(line)
    , m_currentChar(m_line.unicode())
{
}

QString BatchFileLineTokenizer::nextToken()
{
    if (const QChar *tokenBegin = advanceToTokenBegin()) {
        if (const QChar *tokenEnd = advanceToTokenEnd()) {
            const int length = tokenEnd - tokenBegin;
            return QString(tokenBegin, length);
        }
    }

    return QString();
}

const QChar *BatchFileLineTokenizer::advanceToTokenBegin()
{
    m_isWithinQuotation = false;

    forever {
        if (atEnd())
            return nullptr;

        if (atQuotationMark()) {
            m_isWithinQuotation = true;
            ++m_currentChar;
            return m_currentChar;
        }

        if (!atWhiteSpace())
            return m_currentChar;

        ++m_currentChar;
    }
}

const QChar *BatchFileLineTokenizer::advanceToTokenEnd()
{
    forever {
        if (m_isWithinQuotation) {
            if (atEnd()) {
                qWarning("ClangBatchFileProcessor: error: unfinished quotation.");
                return nullptr;
            }

            if (atQuotationMark())
                return m_currentChar++;

        } else if (atWhiteSpace() || atEnd()) {
            return m_currentChar;
        }

        ++m_currentChar;
    }
}

bool BatchFileLineTokenizer::atEnd() const
{
    return *m_currentChar == QLatin1Char('\0');
}

bool BatchFileLineTokenizer::atWhiteSpace() const
{
    return *m_currentChar == ' '
        || *m_currentChar == '\t'
        || *m_currentChar == '\n';
}

bool BatchFileLineTokenizer::atQuotationMark() const
{
    return *m_currentChar == '"';
}

struct CommandContext {
    QString filePath;
    int lineNumber = -1;
};

class Command
{
public:
    using Ptr = QSharedPointer<Command>;

public:
    Command(const CommandContext &context) : m_commandContext(context) {}
    virtual ~Command() = default;

    const CommandContext &context() const { return m_commandContext; }
    virtual bool run() { return true; }

private:
    const CommandContext m_commandContext;
};

class OpenProjectCommand : public Command
{
public:
    OpenProjectCommand(const CommandContext &context,
                       const QString &projectFilePath);

    bool run() override;

    static Command::Ptr parse(BatchFileLineTokenizer &arguments,
                              const CommandContext &context);

private:
    QString m_projectFilePath;
};

OpenProjectCommand::OpenProjectCommand(const CommandContext &context,
                                       const QString &projectFilePath)
    : Command(context)
    , m_projectFilePath(projectFilePath)
{
}

bool OpenProjectCommand::run()
{
    qCDebug(debug) << "line" << context().lineNumber << "OpenProjectCommand" << m_projectFilePath;

    const ProjectExplorerPlugin::OpenProjectResult openProjectSucceeded
            = ProjectExplorerPlugin::openProject(Utils::FilePath::fromString(m_projectFilePath));
    QTC_ASSERT(openProjectSucceeded, return false);

    Project *project = openProjectSucceeded.project();
    project->configureAsExampleProject(nullptr);

    return CppEditor::Tests::TestCase::waitUntilProjectIsFullyOpened(project, timeOutInMs());
}

Command::Ptr OpenProjectCommand::parse(BatchFileLineTokenizer &arguments,
                                       const CommandContext &context)
{
    const QString projectFilePath = arguments.nextToken();
    if (projectFilePath.isEmpty()) {
        qWarning("%s:%d: error: No project file path given.",
                  qPrintable(context.filePath),
                  context.lineNumber);
        return Command::Ptr();
    }

    const QString absoluteProjectFilePath = QFileInfo(projectFilePath).absoluteFilePath();

    return Command::Ptr(new OpenProjectCommand(context, absoluteProjectFilePath));
}

class OpenDocumentCommand : public Command
{
public:
    OpenDocumentCommand(const CommandContext &context,
                        const QString &documentFilePath);

    bool run() override;

    static Command::Ptr parse(BatchFileLineTokenizer &arguments, const CommandContext &context);

private:
    QString m_documentFilePath;
};

OpenDocumentCommand::OpenDocumentCommand(const CommandContext &context,
                                         const QString &documentFilePath)
    : Command(context)
    , m_documentFilePath(documentFilePath)
{
}

class WaitForUpdatedCodeWarnings : public QObject
{
public:
    WaitForUpdatedCodeWarnings(ClangEditorDocumentProcessor *processor);

    bool wait(int timeOutInMs) const;

private:
    void onCodeWarningsUpdated() { m_gotResults = true; }

private:

    bool m_gotResults = false;
};

WaitForUpdatedCodeWarnings::WaitForUpdatedCodeWarnings(ClangEditorDocumentProcessor *processor)
{
    connect(processor,
            &ClangEditorDocumentProcessor::codeWarningsUpdated,
            this, &WaitForUpdatedCodeWarnings::onCodeWarningsUpdated);
}

bool WaitForUpdatedCodeWarnings::wait(int timeOutInMs) const
{
    QElapsedTimer time;
    time.start();

    forever {
        if (time.elapsed() > timeOutInMs) {
            qWarning("WaitForUpdatedCodeWarnings: timeout of %d ms reached.", timeOutInMs);
            return false;
        }

        if (m_gotResults)
            return true;

        QCoreApplication::processEvents();
        QThread::msleep(20);
    }
}

bool OpenDocumentCommand::run()
{
    qCDebug(debug) << "line" << context().lineNumber << "OpenDocumentCommand" << m_documentFilePath;

    const bool openEditorSucceeded = Core::EditorManager::openEditor(
        Utils::FilePath::fromString(m_documentFilePath));
    QTC_ASSERT(openEditorSucceeded, return false);

    auto *processor = ClangEditorDocumentProcessor::get(m_documentFilePath);
    QTC_ASSERT(processor, return false);

    WaitForUpdatedCodeWarnings waiter(processor);
    return waiter.wait(timeOutInMs());
}

Command::Ptr OpenDocumentCommand::parse(BatchFileLineTokenizer &arguments,
                                        const CommandContext &context)
{
    const QString documentFilePath = arguments.nextToken();
    if (documentFilePath.isEmpty()) {
        qWarning("%s:%d: error: No document file path given.",
                  qPrintable(context.filePath),
                  context.lineNumber);
        return Command::Ptr();
    }

    const QString absoluteDocumentFilePath = QFileInfo(documentFilePath).absoluteFilePath();

    return Command::Ptr(new OpenDocumentCommand(context, absoluteDocumentFilePath));
}

class CloseAllDocuments : public Command
{
public:
    CloseAllDocuments(const CommandContext &context);

    bool run() override;

    static Command::Ptr parse(BatchFileLineTokenizer &arguments, const CommandContext &context);
};

CloseAllDocuments::CloseAllDocuments(const CommandContext &context)
    : Command(context)
{
}

bool CloseAllDocuments::run()
{
    qCDebug(debug) << "line" << context().lineNumber << "CloseAllDocuments";

    return Core::EditorManager::closeAllEditors(/*askAboutModifiedEditors=*/ false);
}

Command::Ptr CloseAllDocuments::parse(BatchFileLineTokenizer &arguments,
                                      const CommandContext &context)
{
    const QString argument = arguments.nextToken();
    if (!argument.isEmpty()) {
        qWarning("%s:%d: error: Unexpected argument.",
                 qPrintable(context.filePath),
                 context.lineNumber);
        return Command::Ptr();
    }

    return Command::Ptr(new CloseAllDocuments(context));
}

class InsertTextCommand : public Command
{
public:
    // line and column are 1-based
    InsertTextCommand(const CommandContext &context, const QString &text);

    bool run() override;

    static Command::Ptr parse(BatchFileLineTokenizer &arguments,
                              const CommandContext &context);

private:
    const QString m_textToInsert;
};

InsertTextCommand::InsertTextCommand(const CommandContext &context, const QString &text)
    : Command(context)
    , m_textToInsert(text)
{
}

TextEditor::BaseTextEditor *currentTextEditor()
{
    return qobject_cast<TextEditor::BaseTextEditor*>(Core::EditorManager::currentEditor());
}

bool InsertTextCommand::run()
{
    qCDebug(debug) << "line" << context().lineNumber << "InsertTextCommand" << m_textToInsert;

    TextEditor::BaseTextEditor *editor = currentTextEditor();
    QTC_ASSERT(editor, return false);
    const QString documentFilePath = editor->document()->filePath().toString();
    auto *processor = ClangEditorDocumentProcessor::get(documentFilePath);
    QTC_ASSERT(processor, return false);

    editor->insert(m_textToInsert);

    WaitForUpdatedCodeWarnings waiter(processor);
    return waiter.wait(timeOutInMs());
}

Command::Ptr InsertTextCommand::parse(BatchFileLineTokenizer &arguments,
                                      const CommandContext &context)
{
    const QString textToInsert = arguments.nextToken();
    if (textToInsert.isEmpty()) {
        qWarning("%s:%d: error: No text to insert given.",
                  qPrintable(context.filePath),
                  context.lineNumber);
        return Command::Ptr();
    }

    return Command::Ptr(new InsertTextCommand(context, textToInsert));
}

class SetCursorCommand : public Command
{
public:
    // line and column are 1-based
    SetCursorCommand(const CommandContext &context, int line, int column);

    bool run() override;

    static Command::Ptr parse(BatchFileLineTokenizer &arguments,
                              const CommandContext &context);

private:
    int m_line;
    int m_column;
};

SetCursorCommand::SetCursorCommand(const CommandContext &context, int line, int column)
    : Command(context)
    , m_line(line)
    , m_column(column)
{
}

bool SetCursorCommand::run()
{
    qCDebug(debug) << "line" << context().lineNumber << "SetCursorCommand" << m_line << m_column;

    TextEditor::BaseTextEditor *editor = currentTextEditor();
    QTC_ASSERT(editor, return false);

    editor->gotoLine(m_line, m_column - 1);

    return true;
}

Command::Ptr SetCursorCommand::parse(BatchFileLineTokenizer &arguments,
                                     const CommandContext &context)
{
    // Process line
    const QString line = arguments.nextToken();
    if (line.isEmpty()) {
        qWarning("%s:%d: error: No line number given.",
                  qPrintable(context.filePath),
                  context.lineNumber);
        return Command::Ptr();
    }
    bool converted = false;
    const int lineNumber = line.toInt(&converted);
    if (!converted) {
        qWarning("%s:%d: error: Invalid line number.",
                  qPrintable(context.filePath),
                  context.lineNumber);
        return Command::Ptr();
    }

    // Process column
    const QString column = arguments.nextToken();
    if (column.isEmpty()) {
        qWarning("%s:%d: error: No column number given.",
                  qPrintable(context.filePath),
                  context.lineNumber);
        return Command::Ptr();
    }
    converted = false;
    const int columnNumber = column.toInt(&converted);
    if (!converted) {
        qWarning("%s:%d: error: Invalid column number.",
                  qPrintable(context.filePath),
                  context.lineNumber);
        return Command::Ptr();
    }

    return Command::Ptr(new SetCursorCommand(context, lineNumber, columnNumber));
}

class ProcessEventsCommand : public Command
{
public:
    ProcessEventsCommand(const CommandContext &context, int durationInMs);

    bool run() override;

    static Command::Ptr parse(BatchFileLineTokenizer &arguments,
                              const CommandContext &context);

private:
    int m_durationInMs;
};

ProcessEventsCommand::ProcessEventsCommand(const CommandContext &context,
                                           int durationInMs)
    : Command(context)
    , m_durationInMs(durationInMs)
{
}

bool ProcessEventsCommand::run()
{
    qCDebug(debug) << "line" << context().lineNumber << "ProcessEventsCommand" << m_durationInMs;

    QElapsedTimer time;
    time.start();

    forever {
        if (time.elapsed() > m_durationInMs)
            return true;

        QCoreApplication::processEvents();
        QThread::msleep(20);
    }
}

Command::Ptr ProcessEventsCommand::parse(BatchFileLineTokenizer &arguments,
                                         const CommandContext &context)
{
    const QString durationInMsText = arguments.nextToken();
    if (durationInMsText.isEmpty()) {
        qWarning("%s:%d: error: No duration given.",
                 qPrintable(context.filePath),
                 context.lineNumber);
        return Command::Ptr();
    }

    bool converted = false;
    const int durationInMs = durationInMsText.toInt(&converted);
    if (!converted) {
        qWarning("%s:%d: error: Invalid duration given.",
                 qPrintable(context.filePath),
                 context.lineNumber);
        return Command::Ptr();
    }

    return Command::Ptr(new ProcessEventsCommand(context, durationInMs));
}

class BatchFileReader
{
public:
    BatchFileReader(const QString &filePath);

    bool isFilePathValid() const;

    QString read() const;

private:
    const QString m_batchFilePath;
};

BatchFileReader::BatchFileReader(const QString &filePath)
    : m_batchFilePath(filePath)
{
}

bool BatchFileReader::isFilePathValid() const
{
    QFileInfo fileInfo(m_batchFilePath);

    return !m_batchFilePath.isEmpty()
        && fileInfo.isFile()
        && fileInfo.isReadable();
}

QString BatchFileReader::read() const
{
    QFile file(m_batchFilePath);
    QTC_CHECK(file.open(QFile::ReadOnly | QFile::Text));

    return QString::fromLocal8Bit(file.readAll());
}

class BatchFileParser
{
public:
    BatchFileParser(const QString &filePath,
                    const QString &commands);

    bool parse();
    QVector<Command::Ptr> commands() const;

private:
    bool advanceLine();
    QString currentLine() const;
    bool parseLine(const QString &line);

private:
    using ParseFunction = Command::Ptr (*)(BatchFileLineTokenizer &, const CommandContext &);
    using CommandToParseFunction = QHash<QString, ParseFunction>;
    CommandToParseFunction m_commandParsers;

    int m_currentLineIndex = -1;
    CommandContext m_context;
    QStringList m_lines;
    QVector<Command::Ptr> m_commands;
};

BatchFileParser::BatchFileParser(const QString &filePath,
                                 const QString &commands)
    : m_lines(commands.split('\n'))
{
    m_context.filePath = filePath;

    m_commandParsers.insert("openProject", &OpenProjectCommand::parse);
    m_commandParsers.insert("openDocument", &OpenDocumentCommand::parse);
    m_commandParsers.insert("closeAllDocuments", &CloseAllDocuments::parse);
    m_commandParsers.insert("setCursor", &SetCursorCommand::parse);
    m_commandParsers.insert("insertText", &InsertTextCommand::parse);
    m_commandParsers.insert("processEvents", &ProcessEventsCommand::parse);
}

bool BatchFileParser::parse()
{
    while (advanceLine()) {
        const QString line = currentLine().trimmed();
        if (line.isEmpty() || line.startsWith('#'))
            continue;

        if (!parseLine(line))
            return false;
    }

    return true;
}

QVector<Command::Ptr> BatchFileParser::commands() const
{
    return m_commands;
}

bool BatchFileParser::advanceLine()
{
    ++m_currentLineIndex;
    m_context.lineNumber = m_currentLineIndex + 1;
    return m_currentLineIndex < m_lines.size();
}

QString BatchFileParser::currentLine() const
{
    return m_lines[m_currentLineIndex];
}

bool BatchFileParser::parseLine(const QString &line)
{
    BatchFileLineTokenizer tokenizer(line);
    QString command = tokenizer.nextToken();
    QTC_CHECK(!command.isEmpty());

    if (const ParseFunction parseFunction = m_commandParsers.value(command)) {
        if (Command::Ptr cmd = parseFunction(tokenizer, m_context)) {
            m_commands.append(cmd);
            return true;
        }

        return false;
    }

    qWarning("%s:%d: error: Unknown command \"%s\".",
             qPrintable(m_context.filePath),
             m_context.lineNumber,
             qPrintable(command));

    return false;
}

} // anonymous namespace

static QString applySubstitutions(const QString &filePath, const QString &text)
{
    const QString dirPath = QFileInfo(filePath).absolutePath();

    QString result = text;
    result.replace("${PWD}", dirPath);

    return result;
}

bool runClangBatchFile(const QString &filePath)
{
    qWarning("ClangBatchFileProcessor: Running \"%s\".", qPrintable(filePath));

    BatchFileReader reader(filePath);
    QTC_ASSERT(reader.isFilePathValid(), return false);
    const QString fileContent = reader.read();
    const QString fileContentWithSubstitutionsApplied = applySubstitutions(filePath, fileContent);

    BatchFileParser parser(filePath, fileContentWithSubstitutionsApplied);
    QTC_ASSERT(parser.parse(), return false);
    const QVector<Command::Ptr> commands = parser.commands();

    Utils::ExecuteOnDestruction closeAllEditors([](){
        qWarning("ClangBatchFileProcessor: Finished, closing all documents.");
        QTC_CHECK(Core::EditorManager::closeAllEditors(/*askAboutModifiedEditors=*/ false));
    });

    for (const Command::Ptr &command : commands) {
        const bool runSucceeded = command->run();
        QCoreApplication::processEvents(); // Update GUI

        if (!runSucceeded) {
            const CommandContext context = command->context();
            qWarning("%s:%d: Failed to run.",
                     qPrintable(context.filePath),
                     context.lineNumber);
            return false;
        }
    }

    return true;
}

} // namespace Internal
} // namespace ClangCodeModel