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

#include "executableinfo.h"

#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>

#include <utils/environment.h>
#include <utils/qtcprocess.h>

#include <QDir>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTextStream>

using namespace Utils;

namespace ClangTools {
namespace Internal {

static QString runExecutable(const Utils::CommandLine &commandLine, QueryFailMode queryFailMode)
{
    if (commandLine.executable().isEmpty() || !commandLine.executable().toFileInfo().isExecutable())
        return {};

    Process cpp;
    Environment env = Environment::systemEnvironment();
    env.setupEnglishOutput();
    cpp.setEnvironment(env);
    cpp.setCommand(commandLine);

    cpp.runBlocking();
    if (cpp.result() != ProcessResult::FinishedWithSuccess
            && (queryFailMode == QueryFailMode::Noisy
            || cpp.result() != ProcessResult::FinishedWithError)) {
        Core::MessageManager::writeFlashing(cpp.exitMessage());
        Core::MessageManager::writeFlashing(QString::fromUtf8(cpp.allRawOutput()));
        return {};
    }

    return cpp.cleanedStdOut();
}

static QStringList queryClangTidyChecks(const FilePath &executable,
                                        const QString &checksArgument)
{
    QStringList arguments = QStringList("-list-checks");
    if (!checksArgument.isEmpty())
        arguments.prepend(checksArgument);

    const CommandLine commandLine(executable, arguments);
    QString output = runExecutable(commandLine, QueryFailMode::Noisy);
    if (output.isEmpty())
        return {};

    // Expected output is (clang-tidy 8.0):
    //   Enabled checks:
    //       abseil-duration-comparison
    //       abseil-duration-division
    //       abseil-duration-factory-float
    //       ...

    QTextStream stream(&output);
    QString line = stream.readLine();
    if (!line.startsWith("Enabled checks:"))
        return {};

    QStringList checks;
    while (!stream.atEnd()) {
        const QString candidate = stream.readLine().trimmed();
        if (!candidate.isEmpty())
            checks << candidate;
    }

    return checks;
}

static ClazyChecks querySupportedClazyChecks(const FilePath &executablePath)
{
    static const QString queryFlag = "-supported-checks-json";
    QString jsonOutput = runExecutable(CommandLine(executablePath, {queryFlag}),
                                       QueryFailMode::Noisy);

    // Some clazy 1.6.x versions have a bug where they expect an argument after the
    // option.
    if (jsonOutput.isEmpty())
        jsonOutput = runExecutable(CommandLine(executablePath, {queryFlag, "dummy"}),
                                   QueryFailMode::Noisy);
    if (jsonOutput.isEmpty())
        return {};

    // Expected output is (clazy-standalone 1.6):
    //   {
    //       "available_categories" : ["readability", "qt4", "containers", ... ],
    //       "checks" : [
    //           {
    //               "name"  : "qt-keywords",
    //               "level" : -1,
    //               "fixits" : [ { "name" : "qt-keywords" } ]
    //           },
    //           ...
    //           {
    //               "name"  : "inefficient-qlist",
    //               "level" : -1,
    //               "categories" : ["containers", "performance"],
    //               "visits_decls" : true
    //           },
    //           ...
    //       ]
    //   }

    ClazyChecks infos;

    const QJsonDocument document = QJsonDocument::fromJson(jsonOutput.toUtf8());
    if (document.isNull())
        return {};
    const QJsonArray checksArray = document.object()["checks"].toArray();

    for (const QJsonValue &item: checksArray) {
        const QJsonObject checkObject = item.toObject();

        ClazyCheck info;
        info.name = checkObject["name"].toString().trimmed();
        if (info.name.isEmpty())
            continue;
        info.level = checkObject["level"].toInt();
        for (const QJsonValue &item : checkObject["categories"].toArray())
            info.topics.append(item.toString().trimmed());

        infos << info;
    }

    return infos;
}

ClangTidyInfo::ClangTidyInfo(const FilePath &executablePath)
    : defaultChecks(queryClangTidyChecks(executablePath, {}))
    , supportedChecks(queryClangTidyChecks(executablePath, "-checks=*"))
{}

ClazyStandaloneInfo ClazyStandaloneInfo::getInfo(const FilePath &executablePath)
{
    const QDateTime timeStamp = executablePath.lastModified();
    const auto it = cache.find(executablePath);
    if (it == cache.end()) {
        const ClazyStandaloneInfo info(executablePath);
        cache.insert(executablePath, {timeStamp, info});
        return info;
    }
    if (it->first != timeStamp) {
        it->first = timeStamp;
        it->second = ClazyStandaloneInfo::getInfo(executablePath);
    }
    return it->second;
}

ClazyStandaloneInfo::ClazyStandaloneInfo(const FilePath &executablePath)
    : defaultChecks(queryClangTidyChecks(executablePath, {})) // Yup, behaves as clang-tidy.
    , supportedChecks(querySupportedClazyChecks(executablePath))
{
    QString output = runExecutable({executablePath, {"--version"}}, QueryFailMode::Silent);
    QTextStream stream(&output);
    while (!stream.atEnd()) {
        // It's just "clazy version " right now, but let's be prepared for someone adding a colon
        // later on.
        static const QStringList versionPrefixes{"clazy version ", "clazy version: "};
        const QString line = stream.readLine().simplified();
        for (const QString &prefix : versionPrefixes) {
            if (line.startsWith(prefix)) {
                version = QVersionNumber::fromString(line.mid(prefix.length()));
                break;
            }
        }
    }
}

static FilePath queryResourceDir(const FilePath &clangToolPath)
{
    QString output = runExecutable(CommandLine(clangToolPath, {"someFilePath", "--",
                                                               "-print-resource-dir"}),
                                   QueryFailMode::Silent);

    // Expected output is (clang-tidy 10):
    //   lib/clang/10.0.1
    //   Error while trying to load a compilation database:
    //   ...

    // Parse
    QTextStream stream(&output);
    const QString path = clangToolPath.parentDir().parentDir()
            .pathAppended(stream.readLine()).toString();
    const auto filePath = FilePath::fromUserInput(QDir::cleanPath(path));
    if (filePath.exists())
        return filePath;
    return {};
}

QString queryVersion(const FilePath &clangToolPath, QueryFailMode failMode)
{
    QString output = runExecutable(CommandLine(clangToolPath, {"--version"}), failMode);
    QTextStream stream(&output);
    while (!stream.atEnd()) {
        static const QStringList versionPrefixes{"LLVM version ", "clang version: "};
        const QString line = stream.readLine().simplified();
        for (const QString &prefix : versionPrefixes) {
            auto idx = line.indexOf(prefix);
            if (idx >= 0)
                return line.mid(idx + prefix.length());
        }
    }
    return {};
}

static QPair<FilePath, QString> clangIncludeDirAndVersion(const FilePath &clangToolPath)
{
    const FilePath dynamicResourceDir = queryResourceDir(clangToolPath);
    const QString dynamicVersion = queryVersion(clangToolPath, QueryFailMode::Noisy);
    if (dynamicResourceDir.isEmpty() || dynamicVersion.isEmpty())
        return {FilePath::fromUserInput(CLANG_INCLUDE_DIR), QString(CLANG_VERSION)};
    return {dynamicResourceDir / "include", dynamicVersion};
}

QPair<FilePath, QString> getClangIncludeDirAndVersion(const FilePath &clangToolPath)
{
    QTC_CHECK(!clangToolPath.isEmpty());
    static QMap<FilePath, QPair<FilePath, QString>> cache;
    auto it = cache.find(clangToolPath);
    if (it == cache.end())
        it = cache.insert(clangToolPath, clangIncludeDirAndVersion(clangToolPath));
    return it.value();
}

QHash<Utils::FilePath, QPair<QDateTime, ClazyStandaloneInfo>> ClazyStandaloneInfo::cache;

} // namespace Internal
} // namespace ClangTools