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

#include "compilationdb.h"

#include "cppeditortr.h"

#include <projectexplorer/abi.h>
#include <projectexplorer/projectexplorerconstants.h>

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

using namespace ProjectExplorer;
namespace PEConstants = ProjectExplorer::Constants;
using namespace Utils;

namespace CppEditor {

static QStringList projectPartArguments(const ProjectPart &projectPart)
{
    QStringList args;
    args << projectPart.compilerFilePath.path();
    args << "-c";
    if (projectPart.toolchainType != PEConstants::MSVC_TOOLCHAIN_TYPEID) {
        args << "--target=" + projectPart.toolchainTargetTriple;
        if (projectPart.toolchainAbi.architecture() == Abi::X86Architecture)
            args << QLatin1String(projectPart.toolchainAbi.wordWidth() == 64 ? "-m64" : "-m32");
    }
    args << projectPart.compilerFlags;
    for (const ProjectExplorer::HeaderPath &headerPath : projectPart.headerPaths) {
        if (headerPath.type == HeaderPathType::User) {
            args << "-I" + headerPath.path.path();
        } else if (headerPath.type == HeaderPathType::System) {
            args << (projectPart.toolchainType == PEConstants::MSVC_TOOLCHAIN_TYPEID
                         ? "-I"
                         : "-isystem")
                        + headerPath.path.path();
        }
    }
    for (const Macro &macro : projectPart.projectMacros) {
        args.append(
            QString::fromUtf8(macro.toKeyValue(macro.type == MacroType::Define ? "-D" : "-U")));
    }

    return args;
}

static QJsonArray projectPartOptions(const CppEditor::CompilerOptionsBuilder &optionsBuilder)
{
    const QStringList optionsList = optionsBuilder.options();
    QJsonArray optionsArray;
    for (const QString &opt : optionsList) {
        // These will be added later by the file-specific code, and they trigger warnings
        // if they appear twice; see QTCREATORBUG-26664.
        if (opt != "-TP" && opt != "-TC")
            optionsArray << opt;
    }
    return optionsArray;
}

static QJsonArray fullProjectPartOptions(const QJsonArray &projectPartOptions,
                                  const QJsonArray &projectOptions)
{
    QJsonArray fullProjectPartOptions = projectPartOptions;
    for (const QJsonValue &opt : projectOptions)
        fullProjectPartOptions.prepend(opt);
    return fullProjectPartOptions;
}

QJsonArray fullProjectPartOptions(const CppEditor::CompilerOptionsBuilder &optionsBuilder,
                                  const QStringList &projectOptions)
{
    return fullProjectPartOptions(projectPartOptions(optionsBuilder),
                                  QJsonArray::fromStringList(projectOptions));
}

QJsonArray clangOptionsForFile(const ProjectFile &file, const ProjectPart &projectPart,
                               const QJsonArray &generalOptions, UsePrecompiledHeaders usePch,
                               bool clStyle)
{
    CompilerOptionsBuilder optionsBuilder(projectPart);
    optionsBuilder.setClStyle(clStyle);
    ProjectFile::Kind fileKind = file.kind;
    if (fileKind == ProjectFile::AmbiguousHeader) {
        fileKind = projectPart.languageVersion <= LanguageVersion::LatestC
                       ? ProjectFile::CHeader : ProjectFile::CXXHeader;
    }
    if (usePch == UsePrecompiledHeaders::Yes && projectPart.precompiledHeaders.contains(file.path))
        usePch = UsePrecompiledHeaders::No;

    optionsBuilder.updateFileLanguage(fileKind);
    optionsBuilder.addPrecompiledHeaderOptions(usePch);
    const QJsonArray specificOptions = QJsonArray::fromStringList(optionsBuilder.options());
    QJsonArray fullOptions = generalOptions;
    for (const QJsonValue &opt : specificOptions)
        fullOptions << opt;
    return fullOptions;
}

static QJsonObject createFileObject(const FilePath &buildDir,
                                    const QStringList &arguments,
                                    const ProjectPart &projectPart,
                                    const ProjectFile &projFile,
                                    CompilationDbPurpose purpose,
                                    const QJsonArray &projectPartOptions,
                                    UsePrecompiledHeaders usePch,
                                    bool clStyle)
{
    QJsonObject fileObject;
    fileObject["file"] = projFile.path.path();
    QJsonArray args;

    if (purpose == CompilationDbPurpose::Project) {
        args = QJsonArray::fromStringList(arguments);

        const ProjectFile::Kind kind = ProjectFile::classify(projFile.path);
        if (projectPart.toolchainType == ProjectExplorer::Constants::MSVC_TOOLCHAIN_TYPEID
            || projectPart.toolchainType == ProjectExplorer::Constants::CLANG_CL_TOOLCHAIN_TYPEID) {
            if (!ProjectFile::isObjC(kind)) {
                if (ProjectFile::isC(kind))
                    args.append("/TC");
                else if (ProjectFile::isCxx(kind))
                    args.append("/TP");
            }
        } else {
            const QStringList langOption
                = createLanguageOptionGcc(projectPart.language, kind,
                                          projectPart.languageExtensions
                                              & LanguageExtension::ObjectiveC);
            for (const QString &langOptionPart : langOption)
                args.append(langOptionPart);
        }
    } else {
        args = clangOptionsForFile(projFile, projectPart, projectPartOptions, usePch, clStyle);
        if (purpose == CompilationDbPurpose::Analysis && projFile.isHeader())
            args << "-Wno-pragma-once-outside-header";
        args.prepend("clang"); // TODO: clang-cl for MSVC targets? Does it matter at all what we put here?
    }

    args.append(projFile.path.path());
    fileObject["arguments"] = args;
    fileObject["directory"] = buildDir.path();
    return fileObject;
}

void generateCompilationDB(
    QPromise<GenerateCompilationDbResult> &promise,
    const QList<ProjectInfo::ConstPtr> &projectInfoList,
    const FilePath &baseDir,
    CompilationDbPurpose purpose,
    const QStringList &projectOptions,
    const GetOptionsBuilder &getOptionsBuilder)
{
    const QString fileName = "compile_commands.json";
    QTC_ASSERT(
        !baseDir.isEmpty(),
        promise.addResult(make_unexpected(Tr::tr("Invalid location for %1.").arg(fileName)));
        return);
    QTC_CHECK(baseDir.ensureWritableDir());
    QFile compileCommandsFile(baseDir.pathAppended(fileName).toFSPathString());
    const bool fileOpened = compileCommandsFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
    if (!fileOpened) {
        promise.addResult(make_unexpected(
            Tr::tr("Could not create \"%1\": %2")
                .arg(compileCommandsFile.fileName(), compileCommandsFile.errorString())));
        return;
    }
    compileCommandsFile.write("[");

    const QJsonArray jsonProjectOptions = QJsonArray::fromStringList(projectOptions);
    for (bool hasEntries = false;
         const ProjectInfo::ConstPtr &projectInfo : std::as_const(projectInfoList)) {
        QTC_ASSERT(projectInfo, continue);
        for (ProjectPart::ConstPtr projectPart : projectInfo->projectParts()) {
            QTC_ASSERT(projectPart, continue);
            QStringList args;
            const CompilerOptionsBuilder optionsBuilder = getOptionsBuilder(*projectPart);
            QJsonArray ppOptions;
            if (purpose == CompilationDbPurpose::Project) {
                args = projectPartArguments(*projectPart);
            } else {
                ppOptions = fullProjectPartOptions(projectPartOptions(optionsBuilder),
                                                   jsonProjectOptions);
            }
            for (const ProjectFile &projFile : projectPart->files) {
                if (promise.isCanceled())
                    return;
                if (purpose == CompilationDbPurpose::CodeModel && projFile.isHeader())
                    continue;
                const QJsonObject json
                    = createFileObject(baseDir,
                                       args,
                                       *projectPart,
                                       projFile,
                                       purpose,
                                       ppOptions,
                                       projectInfo->settings().usePrecompiledHeaders(),
                                       optionsBuilder.isClStyle());
                if (hasEntries)
                    compileCommandsFile.write(",");
                compileCommandsFile.write(QJsonDocument(json).toJson(QJsonDocument::Compact));
                hasEntries = true;
            }
        }
    }

    compileCommandsFile.write("]");
    compileCommandsFile.close();
    promise.addResult(FilePath::fromUserInput(compileCommandsFile.fileName()));

}

} // namespace CppEditor