aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/clangtools/clangtidyclazytool.cpp
blob: a5f28b9e49bab5aa706917cb977f6417d3b90422 (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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "clangtidyclazytool.h"

#include "clangfixitsrefactoringchanges.h"
#include "clangselectablefilesdialog.h"
#include "clangtoolsconstants.h"
#include "clangtoolsdiagnosticmodel.h"
#include "clangtoolslogfilereader.h"
#include "clangtidyclazyruncontrol.h"
#include "clangtoolsdiagnosticview.h"
#include "clangtoolsprojectsettings.h"
#include "clangtoolssettings.h"

#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>

#include <cpptools/clangdiagnosticconfigsmodel.h>
#include <cpptools/cppcodemodelsettings.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/cpptoolsreuse.h>

#include <debugger/analyzer/analyzermanager.h>

#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorericons.h>
#include <projectexplorer/target.h>
#include <projectexplorer/session.h>

#include <utils/fancylineedit.h>
#include <utils/utilsicons.h>

#include <QAction>
#include <QToolButton>

using namespace Core;
using namespace CppTools;
using namespace Debugger;
using namespace ProjectExplorer;
using namespace Utils;

namespace ClangTools {
namespace Internal {

static ClangTidyClazyTool *s_instance;

class ApplyFixIts
{
public:
    class RefactoringFileInfo
    {
    public:
        bool isValid() const { return file.isValid(); }

        FixitsRefactoringFile file;
        QVector<DiagnosticItem *> diagnosticItems;
        bool hasScheduledFixits = false;
    };

    ApplyFixIts(const QVector<DiagnosticItem *> &diagnosticItems)
    {
        for (DiagnosticItem *diagnosticItem : diagnosticItems) {
            const QString &filePath = diagnosticItem->diagnostic().location.filePath;
            QTC_ASSERT(!filePath.isEmpty(), continue);

            // Get or create refactoring file
            RefactoringFileInfo &fileInfo = m_refactoringFileInfos[filePath];
            if (!fileInfo.isValid())
                fileInfo.file = FixitsRefactoringFile(filePath);

            // Append item
            fileInfo.diagnosticItems += diagnosticItem;
            if (diagnosticItem->fixItStatus() == FixitStatus::Scheduled)
                fileInfo.hasScheduledFixits = true;
        }
    }

    static void addFixitOperations(DiagnosticItem *diagnosticItem,
                                   const FixitsRefactoringFile &file, bool apply)
    {
        // Did we already created the fixit operations?
        ReplacementOperations currentOps = diagnosticItem->fixitOperations();
        if (!currentOps.isEmpty()) {
            for (ReplacementOperation *op : currentOps)
                op->apply = apply;
            return;
        }

        // Collect/construct the fixit operations
        ReplacementOperations replacements;

        for (const ExplainingStep &step : diagnosticItem->diagnostic().explainingSteps) {
            if (!step.isFixIt)
                continue;

            const Debugger::DiagnosticLocation start = step.ranges.first();
            const Debugger::DiagnosticLocation end = step.ranges.last();
            const int startPos = file.position(start.filePath, start.line, start.column);
            const int endPos = file.position(start.filePath, end.line, end.column);

            auto op = new ReplacementOperation;
            op->pos = startPos;
            op->length = endPos - startPos;
            op->text = step.message;
            op->fileName = start.filePath;
            op->apply = apply;

            replacements += op;
        }

        diagnosticItem->setFixitOperations(replacements);
    }

    void apply()
    {
        for (auto it = m_refactoringFileInfos.begin(); it != m_refactoringFileInfos.end(); ++it) {
            RefactoringFileInfo &fileInfo = it.value();

            QVector<DiagnosticItem *> itemsScheduledOrSchedulable;
            QVector<DiagnosticItem *> itemsScheduled;
            QVector<DiagnosticItem *> itemsSchedulable;

            // Construct refactoring operations
            for (DiagnosticItem *diagnosticItem : fileInfo.diagnosticItems) {
                const FixitStatus fixItStatus = diagnosticItem->fixItStatus();

                const bool isScheduled = fixItStatus == FixitStatus::Scheduled;
                const bool isSchedulable = fileInfo.hasScheduledFixits
                                           && fixItStatus == FixitStatus::NotScheduled;

                if (isScheduled || isSchedulable) {
                    addFixitOperations(diagnosticItem, fileInfo.file, isScheduled);
                    itemsScheduledOrSchedulable += diagnosticItem;
                    if (isScheduled)
                        itemsScheduled += diagnosticItem;
                    else
                        itemsSchedulable += diagnosticItem;
                }
            }

            // Collect replacements
            ReplacementOperations ops;
            for (DiagnosticItem *item : itemsScheduledOrSchedulable)
                ops += item->fixitOperations();

            // Apply file
            QVector<DiagnosticItem *> itemsApplied;
            QVector<DiagnosticItem *> itemsFailedToApply;
            QVector<DiagnosticItem *> itemsInvalidated;

            fileInfo.file.setReplacements(ops);
            if (fileInfo.file.apply()) {
                itemsApplied = itemsScheduled;
            } else {
                itemsFailedToApply = itemsScheduled;
                itemsInvalidated = itemsSchedulable;
            }

            // Update DiagnosticItem state
            for (DiagnosticItem *diagnosticItem : itemsScheduled)
                diagnosticItem->setFixItStatus(FixitStatus::Applied);
            for (DiagnosticItem *diagnosticItem : itemsFailedToApply)
                diagnosticItem->setFixItStatus(FixitStatus::FailedToApply);
            for (DiagnosticItem *diagnosticItem : itemsInvalidated)
                diagnosticItem->setFixItStatus(FixitStatus::Invalidated);
        }
    }

private:
    QMap<QString, RefactoringFileInfo> m_refactoringFileInfos;
};

ClangTidyClazyTool::ClangTidyClazyTool()
    : ClangTool("Clang-Tidy and Clazy")
{
    setObjectName("ClangTidyClazyTool");
    s_instance = this;

    m_diagnosticFilterModel = new DiagnosticFilterModel(this);
    m_diagnosticFilterModel->setSourceModel(m_diagnosticModel);

    m_diagnosticView = new DiagnosticView;
    initDiagnosticView();
    m_diagnosticView->setModel(m_diagnosticFilterModel);
    m_diagnosticView->setObjectName(QLatin1String("ClangTidyClazyIssuesView"));
    m_diagnosticView->setWindowTitle(tr("Clang-Tidy and Clazy Issues"));

    foreach (auto * const model,
             QList<QAbstractItemModel *>() << m_diagnosticModel << m_diagnosticFilterModel) {
        connect(model, &QAbstractItemModel::rowsInserted,
                this, &ClangTidyClazyTool::handleStateUpdate);
        connect(model, &QAbstractItemModel::rowsRemoved,
                this, &ClangTidyClazyTool::handleStateUpdate);
        connect(model, &QAbstractItemModel::modelReset,
                this, &ClangTidyClazyTool::handleStateUpdate);
        connect(model, &QAbstractItemModel::layoutChanged, // For QSortFilterProxyModel::invalidate()
                this, &ClangTidyClazyTool::handleStateUpdate);
    }

    // Go to previous diagnostic
    auto action = new QAction(this);
    action->setDisabled(true);
    action->setIcon(Utils::Icons::PREV_TOOLBAR.icon());
    action->setToolTip(tr("Go to previous diagnostic."));
    connect(action, &QAction::triggered, m_diagnosticView, &DetailedErrorView::goBack);
    m_goBack = action;

    // Go to next diagnostic
    action = new QAction(this);
    action->setDisabled(true);
    action->setIcon(Utils::Icons::NEXT_TOOLBAR.icon());
    action->setToolTip(tr("Go to next diagnostic."));
    connect(action, &QAction::triggered, m_diagnosticView, &DetailedErrorView::goNext);
    m_goNext = action;

    // Filter line edit
    m_filterLineEdit = new Utils::FancyLineEdit();
    m_filterLineEdit->setFiltering(true);
    m_filterLineEdit->setHistoryCompleter("CppTools.ClangTidyClazyIssueFilter", true);
    connect(m_filterLineEdit, &Utils::FancyLineEdit::filterChanged, [this](const QString &filter) {
        m_diagnosticFilterModel->setFilterRegExp(
            QRegExp(filter, Qt::CaseSensitive, QRegExp::WildcardUnix));
    });

    // Apply fixits button
    m_applyFixitsButton = new QToolButton;
    m_applyFixitsButton->setText(tr("Apply Fixits"));
    m_applyFixitsButton->setEnabled(false);
    connect(m_diagnosticModel,
            &ClangToolsDiagnosticModel::fixItsToApplyCountChanged,
            [this](int c) {
        m_applyFixitsButton->setEnabled(c);
        static_cast<DiagnosticView *>(m_diagnosticView.data())->setSelectedFixItsCount(c);
    });
    connect(m_applyFixitsButton, &QToolButton::clicked, [this]() {
        QVector<DiagnosticItem *> diagnosticItems;
        m_diagnosticModel->rootItem()->forChildrenAtLevel(1, [&](TreeItem *item){
            diagnosticItems += static_cast<DiagnosticItem *>(item);
        });

        ApplyFixIts(diagnosticItems).apply();
    });

    ActionContainer *menu = ActionManager::actionContainer(Debugger::Constants::M_DEBUG_ANALYZER);
    const QString toolTip = tr("Clang-Tidy and Clazy use a customized Clang executable from the "
                               "Clang project to search for errors and warnings.");

    auto perspective = new Perspective(ClangTidyClazyPerspectiveId, tr("Clang-Tidy and Clazy"));
    perspective->addWindow(m_diagnosticView, Perspective::SplitVertical, nullptr);

    action = new QAction(tr("Clang-Tidy and Clazy..."), this);
    action->setToolTip(toolTip);
    menu->addAction(ActionManager::registerAction(action, "ClangTidyClazy.Action"),
                    Debugger::Constants::G_ANALYZER_TOOLS);
    QObject::connect(action, &QAction::triggered, this, [this]() { startTool(true); });
    QObject::connect(m_startAction, &QAction::triggered, action, &QAction::triggered);
    QObject::connect(m_startAction, &QAction::changed, action, [action, this] {
        action->setEnabled(m_startAction->isEnabled());
    });

    perspective->addToolBarAction(m_startAction);
    perspective->addToolBarAction(m_stopAction);
    perspective->addToolBarAction(m_goBack);
    perspective->addToolBarAction(m_goNext);
    perspective->addToolBarWidget(m_filterLineEdit);
    perspective->addToolBarWidget(m_applyFixitsButton);

    Debugger::registerPerspective(perspective);

    updateRunActions();

    connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::updateRunActions,
            this, &ClangTidyClazyTool::updateRunActions);

}

ClangTidyClazyTool *ClangTidyClazyTool::instance()
{
    return s_instance;
}

static ClangDiagnosticConfig getDiagnosticConfig(Project *project)
{
    ClangToolsProjectSettings *projectSettings = ClangToolsProjectSettingsManager::getSettings(
        project);

    Core::Id diagnosticConfigId;
    if (projectSettings->useGlobalSettings())
        diagnosticConfigId = ClangToolsSettings::instance()->savedDiagnosticConfigId();
    else
        diagnosticConfigId = projectSettings->diagnosticConfig();

    const ClangDiagnosticConfigsModel configsModel(
                CppTools::codeModelSettings()->clangCustomDiagnosticConfigs());

    QTC_ASSERT(configsModel.hasConfigWithId(diagnosticConfigId), return ClangDiagnosticConfig());
    return configsModel.configWithId(diagnosticConfigId);
}

void ClangTidyClazyTool::startTool(bool askUserForFileSelection)
{
    auto runControl = new RunControl(nullptr, Constants::CLANGTIDYCLAZY_RUN_MODE);
    runControl->setDisplayName(tr("Clang-Tidy and Clazy"));
    runControl->setIcon(ProjectExplorer::Icons::ANALYZER_START_SMALL_TOOLBAR);

    Project *project = SessionManager::startupProject();
    QTC_ASSERT(project, return);

    const FileInfos fileInfos = collectFileInfos(project, askUserForFileSelection);
    if (fileInfos.empty())
        return;

    auto clangTool = new ClangTidyClazyRunControl(runControl,
                                                  project->activeTarget(),
                                                  getDiagnosticConfig(project),
                                                  fileInfos);

    m_stopAction->disconnect();
    connect(m_stopAction, &QAction::triggered, runControl, [runControl] {
        runControl->appendMessage(tr("Clang-Tidy and Clazy tool stopped by user."),
                                  NormalMessageFormat);
        runControl->initiateStop();
    });

    connect(runControl, &RunControl::stopped, this, [this, clangTool] {
        bool success = clangTool->success();
        setToolBusy(false);
        m_running = false;
        handleStateUpdate();
        updateRunActions();
        emit finished(success);
    });

    Debugger::selectPerspective(ClangTidyClazyPerspectiveId);

    m_diagnosticModel->clear();
    setToolBusy(true);
    m_diagnosticFilterModel->setProject(project);
    m_running = true;
    handleStateUpdate();
    updateRunActions();

    ProjectExplorerPlugin::startRunControl(runControl);
}

void ClangTidyClazyTool::updateRunActions()
{
    if (m_toolBusy) {
        m_startAction->setEnabled(false);
        QString tooltipText = tr("Clang-Tidy and Clazy are still running.");
        m_startAction->setToolTip(tooltipText);
        m_stopAction->setEnabled(true);
    } else {
        QString toolTip = tr("Start Clang-Tidy and Clazy.");
        Project *project = SessionManager::startupProject();
        Target *target = project ? project->activeTarget() : nullptr;
        const Core::Id cxx = ProjectExplorer::Constants::CXX_LANGUAGE_ID;
        bool canRun = target && project->projectLanguages().contains(cxx)
                && ToolChainKitInformation::toolChain(target->kit(), cxx);
        if (!canRun)
            toolTip = tr("This is not a C++ project.");

        m_startAction->setToolTip(toolTip);
        m_startAction->setEnabled(canRun);
        m_stopAction->setEnabled(false);
    }
}

void ClangTidyClazyTool::handleStateUpdate()
{
    QTC_ASSERT(m_goBack, return);
    QTC_ASSERT(m_goNext, return);
    QTC_ASSERT(m_diagnosticModel, return);
    QTC_ASSERT(m_diagnosticFilterModel, return);

    const int issuesFound = m_diagnosticModel->diagnosticsCount();
    const int issuesVisible = m_diagnosticFilterModel->rowCount();
    m_goBack->setEnabled(issuesVisible > 1);
    m_goNext->setEnabled(issuesVisible > 1);

    QString message;
    if (m_running)
        message = tr("Clang-Tidy and Clazy are running.");
    else
        message = tr("Clang-Tidy and Clazy finished.");

    message += QLatin1Char(' ');
    if (issuesFound == 0)
        message += tr("No issues found.");
    else
        message += tr("%n issues found.", nullptr, issuesFound);

    Debugger::showPermanentStatusMessage(message);
}

QList<Diagnostic> ClangTidyClazyTool::read(const QString &filePath,
                                           const QString &logFilePath,
                                           QString *errorMessage) const
{
    return LogFileReader::readSerialized(filePath, logFilePath, errorMessage);
}

} // namespace Internal
} // namespace ClangTools