aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/clangtools/clangtoolsutils.cpp
blob: 7a812d3750d223b3d6d00286806aa4c18b486d61 (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "clangtoolsutils.h"

#include "clangtool.h"
#include "clangtoolsconstants.h"
#include "clangtoolsdiagnostic.h"
#include "clangtoolssettings.h"
#include "clangtoolstr.h"

#include <coreplugin/icore.h>
#include <cppeditor/cppeditorconstants.h>
#include <cppeditor/cpptoolsreuse.h>
#include <projectexplorer/projectexplorerconstants.h>

#include <utils/checkablemessagebox.h>
#include <utils/environment.h>
#include <utils/filepath.h>
#include <utils/hostosinfo.h>
#include <utils/process.h>
#include <utils/qtcassert.h>

#include <cppeditor/clangdiagnosticconfigsmodel.h>

using namespace CppEditor;
using namespace Utils;

namespace ClangTools {
namespace Internal {

static QString lineColumnString(const Debugger::DiagnosticLocation &location)
{
    return QString("%1:%2").arg(QString::number(location.line), QString::number(location.column));
}

static QString fixitStatus(FixitStatus status)
{
    switch (status) {
    case FixitStatus::NotAvailable:
        return Tr::tr("No Fixits");
    case FixitStatus::NotScheduled:
        return Tr::tr("Not Scheduled");
    case FixitStatus::Invalidated:
        return Tr::tr("Invalidated");
    case FixitStatus::Scheduled:
        return Tr::tr("Scheduled");
    case FixitStatus::FailedToApply:
        return Tr::tr("Failed to Apply");
    case FixitStatus::Applied:
        return Tr::tr("Applied");
    }
    return QString();
}

QString createDiagnosticToolTipString(
    const Diagnostic &diagnostic,
    std::optional<FixitStatus> status,
    bool showSteps)
{
    using StringPair = QPair<QString, QString>;
    QList<StringPair> lines;

    if (!diagnostic.category.isEmpty()) {
        lines.push_back({Tr::tr("Category:"),
                         diagnostic.category.toHtmlEscaped()});
    }

    if (!diagnostic.type.isEmpty()) {
        lines.push_back({Tr::tr("Type:"),
                         diagnostic.type.toHtmlEscaped()});
    }

    if (!diagnostic.description.isEmpty()) {
        lines.push_back({Tr::tr("Description:"),
                         diagnostic.description.toHtmlEscaped()});
    }

    lines.push_back({Tr::tr("Location:"),
                     createFullLocationString(diagnostic.location)});

    if (status) {
        lines.push_back({Tr::tr("Fixit status:"),
                         fixitStatus(*status)});
    }

    if (showSteps && !diagnostic.explainingSteps.isEmpty()) {
        StringPair steps;
        steps.first = Tr::tr("Steps:");
        for (const ExplainingStep &step : diagnostic.explainingSteps) {
            if (!steps.second.isEmpty())
                steps.second += "<br>";
            steps.second += QString("%1:%2: %3")
                    .arg(step.location.filePath.toUserOutput(),
                         lineColumnString(step.location),
                         step.message);
        }
        lines << steps;
    }

    const QString url = documentationUrl(diagnostic.name);
    if (!url.isEmpty()) {
        lines.push_back({Tr::tr("Documentation:"),
                         QString("<a href=\"%1\">%1</a>").arg(url)});
    }

    QString html = QLatin1String("<html>"
                                 "<head>"
                                 "<style>dt { font-weight:bold; } dd { font-family: monospace; }</style>"
                                 "</head>\n"
                                 "<body><dl>");

    for (const StringPair &pair : std::as_const(lines)) {
        html += QLatin1String("<dt>");
        html += pair.first;
        html += QLatin1String("</dt><dd>");
        html += pair.second;
        html += QLatin1String("</dd>\n");
    }
    html += QLatin1String("</dl></body></html>");
    return html;
}

QString createFullLocationString(const Debugger::DiagnosticLocation &location)
{
    return location.filePath.toUserOutput() + QLatin1Char(':') + QString::number(location.line)
            + QLatin1Char(':') + QString::number(location.column);
}

QString hintAboutBuildBeforeAnalysis()
{
    return Tr::tr(
        "In general, the project should be built before starting the analysis to ensure that the "
        "code to analyze is valid.<br/><br/>"
        "Building the project might also run code generators that update the source files as "
        "necessary.");
}

void showHintAboutBuildBeforeAnalysis()
{
    Utils::CheckableMessageBox::doNotShowAgainInformation(
        Core::ICore::dialogParent(),
        Tr::tr("Info About Build the Project Before Analysis"),
        hintAboutBuildBeforeAnalysis(),
        Core::ICore::settings(),
        "ClangToolsDisablingBuildBeforeAnalysisHint");
}

FilePath fullPath(const FilePath &executable)
{
    FilePath candidate = executable;
    const bool hasSuffix = candidate.endsWith(QTC_HOST_EXE_SUFFIX);

    if (candidate.isAbsolutePath()) {
        if (!hasSuffix)
            candidate = candidate.withExecutableSuffix();
    } else {
        const Environment environment = Environment::systemEnvironment();
        const FilePath expandedPath = environment.searchInPath(candidate.toString());
        if (!expandedPath.isEmpty())
            candidate = expandedPath;
    }

    return candidate;
}

static FilePath findValidExecutable(const FilePaths &candidates)
{
    for (const FilePath &candidate : candidates) {
        const FilePath expandedPath = fullPath(candidate);
        if (expandedPath.isExecutableFile())
            return expandedPath;
    }

    return {};
}

FilePath toolShippedExecutable(ClangToolType tool)
{
    const FilePath shippedExecutable = tool == ClangToolType::Tidy
                                     ? Core::ICore::clangTidyExecutable(CLANG_BINDIR)
                                     : Core::ICore::clazyStandaloneExecutable(CLANG_BINDIR);
    if (shippedExecutable.isExecutableFile())
        return shippedExecutable;
    return {};
}

FilePath toolExecutable(ClangToolType tool)
{
    const FilePath fromSettings = ClangToolsSettings::instance()->executable(tool);
    if (!fromSettings.isEmpty())
        return fullPath(fromSettings);
    return toolFallbackExecutable(tool);
}

FilePath toolFallbackExecutable(ClangToolType tool)
{
    const FilePath fallback = tool == ClangToolType::Tidy
                            ? FilePath(Constants::CLANG_TIDY_EXECUTABLE_NAME)
                            : FilePath(Constants::CLAZY_STANDALONE_EXECUTABLE_NAME);
    return findValidExecutable({toolShippedExecutable(tool), fallback});
}

QString clangToolName(CppEditor::ClangToolType tool)
{
    return tool == ClangToolType::Tidy ? Tr::tr("Clang-Tidy") : Tr::tr("Clazy");
}

bool isVFSOverlaySupported(const FilePath &executable)
{
    static QMap<FilePath, bool> vfsCapabilities;
    auto it = vfsCapabilities.find(executable);
    if (it == vfsCapabilities.end()) {
        Process p;
        p.setCommand({executable, {"--help"}});
        p.runBlocking();
        it = vfsCapabilities.insert(executable, p.allOutput().contains("vfsoverlay"));
    }
    return it.value();
}

static void addBuiltinConfigs(ClangDiagnosticConfigsModel &model)
{
    model.appendOrUpdate(builtinConfig());
}

ClangDiagnosticConfig builtinConfig()
{
    ClangDiagnosticConfig config;
    config.setId(Constants::DIAG_CONFIG_TIDY_AND_CLAZY);
    config.setDisplayName(Tr::tr("Default Clang-Tidy and Clazy checks"));
    config.setIsReadOnly(true);
    config.setClangOptions({"-w"}); // Do not emit any clang-only warnings
    config.setClangTidyMode(ClangDiagnosticConfig::TidyMode::UseDefaultChecks);
    config.setClazyMode(ClangDiagnosticConfig::ClazyMode::UseDefaultChecks);
    return config;
}

ClangDiagnosticConfigsModel diagnosticConfigsModel(const ClangDiagnosticConfigs &customConfigs)
{
    ClangDiagnosticConfigsModel model;
    addBuiltinConfigs(model);
    for (const ClangDiagnosticConfig &config : customConfigs)
        model.appendOrUpdate(config);
    return model;
}

ClangDiagnosticConfigsModel diagnosticConfigsModel()
{
    return Internal::diagnosticConfigsModel(ClangToolsSettings::instance()->diagnosticConfigs());
}

QString documentationUrl(const QString &checkName)
{
    QString name = checkName;
    const QString clangPrefix = "clang-diagnostic-";
    if (name.startsWith(clangPrefix))
        return {}; // No documentation for this.

    QString url;
    const QString clazyPrefix = "clazy-";
    const QString clangStaticAnalyzerPrefix = "clang-analyzer-core.";
    if (name.startsWith(clazyPrefix)) {
        name = checkName.mid(clazyPrefix.length());
        url = clazyDocUrl(name);
    } else if (name.startsWith(clangStaticAnalyzerPrefix)) {
        url = CppEditor::Constants::CLANG_STATIC_ANALYZER_DOCUMENTATION_URL;
    } else {
        url = clangTidyDocUrl(name);
    }

    return url;
}

ClangDiagnosticConfig diagnosticConfig(const Utils::Id &diagConfigId)
{
    const ClangDiagnosticConfigsModel configs = diagnosticConfigsModel();
    QTC_ASSERT(configs.hasConfigWithId(diagConfigId), return ClangDiagnosticConfig());
    return configs.configWithId(diagConfigId);
}

static QStringList extraOptions(const QString &envVar)
{
    if (!qtcEnvironmentVariableIsSet(envVar))
        return QStringList();
    QString arguments = qtcEnvironmentVariable(envVar);
    return ProcessArgs::splitArgs(arguments, HostOsInfo::hostOs());
}

QStringList extraClangToolsPrependOptions()
{
    constexpr char csaPrependOptions[] = "QTC_CLANG_CSA_CMD_PREPEND";
    constexpr char toolsPrependOptions[] = "QTC_CLANG_TOOLS_CMD_PREPEND";
    static const QStringList options = extraOptions(csaPrependOptions)
                                       + extraOptions(toolsPrependOptions);
    if (!options.isEmpty())
        qWarning() << "ClangTools options are prepended with " << options;
    return options;
}

QStringList extraClangToolsAppendOptions()
{
    constexpr char csaAppendOptions[] = "QTC_CLANG_CSA_CMD_APPEND";
    constexpr char toolsAppendOptions[] = "QTC_CLANG_TOOLS_CMD_APPEND";
    static const QStringList options = extraOptions(csaAppendOptions)
                                       + extraOptions(toolsAppendOptions);
    if (!options.isEmpty())
        qWarning() << "ClangTools options are appended with " << options;
    return options;
}

QString clangTidyDocUrl(const QString &check)
{
    VersionAndSuffix version = ClangToolsSettings::clangTidyVersion();
    version.first = QVersionNumber(version.first.majorVersion(), 0, 0);
    if (version.first == QVersionNumber(0))
        version.first = QVersionNumber(12);
    static const char versionedUrlPrefix[]
            = "https://releases.llvm.org/%1/tools/clang/tools/extra/docs/";
    static const char unversionedUrlPrefix[] = "https://clang.llvm.org/extra/";
    QString url = version.second.contains("git")
            ? QString::fromLatin1(unversionedUrlPrefix)
            : QString::fromLatin1(versionedUrlPrefix).arg(version.first.toString());
    url.append("clang-tidy/checks/");
    if (version.first.majorVersion() < 15) {
        url.append(check);
    } else {
        const int hyphenIndex = check.indexOf('-');
        QTC_ASSERT(hyphenIndex != -1, return {});
        url.append(check.left(hyphenIndex)).append('/').append(check.mid(hyphenIndex + 1));
    }
    return url.append(".html");
}

QString clazyDocUrl(const QString &check)
{
    QVersionNumber version = ClangToolsSettings::clazyVersion();
    if (!version.isNull())
        version = QVersionNumber(version.majorVersion(), version.minorVersion());
    const QString versionString = version.isNull() ? "master" : version.toString();
    static const char urlTemplate[]
            = "https://github.com/KDE/clazy/blob/%1/docs/checks/README-%2.md";
    return QString::fromLatin1(urlTemplate).arg(versionString, check);
}

bool toolEnabled(CppEditor::ClangToolType type, const ClangDiagnosticConfig &config,
                 const RunSettings &runSettings)
{
    if (type == ClangToolType::Tidy && runSettings.preferConfigFile())
        return true;
    return config.isEnabled(type);
}

} // namespace Internal
} // namespace ClangTools