summaryrefslogtreecommitdiff
path: root/src/tools/clangpchmanagerbackend/source/pchcreator.cpp
blob: dda93d434d378748cdbd8e25643ec7dcdfed9f8c (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
/****************************************************************************
**
** 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 "pchcreator.h"

#include "environment.h"
#include "includecollector.h"
#include "pchnotcreatederror.h"

#include <clangpathwatcherinterface.h>
#include <filepathcachinginterface.h>
#include <generatedfiles.h>
#include <pchmanagerclientinterface.h>
#include <precompiledheadersupdatedmessage.h>
#include <projectpartpch.h>

#include <QCryptographicHash>
#include <QDateTime>
#include <QFile>
#include <QProcess>
#include <QTemporaryFile>

namespace ClangBackEnd {

namespace {
template <typename Source,
          typename Target>
void append(Target &target, const Source &source)
{
    using ValueType = typename Target::value_type;
    Source clonedSource = source.clone();

    target.reserve(target.size() + source.size());

    for (auto &&entry : clonedSource)
        target.push_back(ValueType(std::move(entry)));
}

void appendFilePathId(Utils::PathStringVector &target,
                      const ClangBackEnd::FilePathIds &source,
                      const ClangBackEnd::FilePathCachingInterface &filePathCache)
{
    for (FilePathId id : source)
        target.emplace_back(filePathCache.filePath(id).path());
}

Utils::PathStringVector generatedFilePaths(const V2::FileContainers &generaredFiles)
{
    Utils::PathStringVector generaredFilePaths;
    generaredFilePaths.reserve(generaredFiles.size());

    for (const V2::FileContainer &generatedFile : generaredFiles)
        generaredFilePaths.push_back(generatedFile.filePath.path());

    return generaredFilePaths;
}

}

namespace {

std::size_t contentSize(const FilePaths &includes)
{
    auto countIncludeSize = [] (std::size_t size, const auto &include) {
        return size + include.size();
    };

    return std::accumulate(includes.begin(), includes.end(), std::size_t(0), countIncludeSize);
}
}

Utils::SmallString PchCreator::generatePchIncludeFileContent(const FilePathIds &includeIds) const
{
    Utils::SmallString fileContent;
    const std::size_t lineTemplateSize = 12;
    auto includes = m_filePathCache.filePaths(includeIds);

    fileContent.reserve(includes.size() * lineTemplateSize + contentSize(includes));

    for (Utils::SmallStringView include : includes)
        fileContent += {"#include \"", include, "\"\n"};

    return fileContent;
}


bool PchCreator::generatePch(Utils::SmallStringVector &&compilerArguments)
{
    QProcess process;

    process.setProcessChannelMode(QProcess::ForwardedChannels);
    process.setArguments(QStringList(compilerArguments));
    process.setProgram(QString(m_environment.clangCompilerPath()));

    process.start();
    process.waitForFinished(300000);

    return process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0;
}

QStringList PchCreator::convertToQStringList(const Utils::SmallStringVector &compilerArguments)
{
    QStringList qStringList;

    append(qStringList, compilerArguments);

    return qStringList;
}

namespace {

void hashProjectPart(QCryptographicHash &hash, const V2::ProjectPartContainer &projectPart)
{
    const auto &projectPartId = projectPart.projectPartId;
    hash.addData(projectPartId.data(), int(projectPartId.size()));

    for (const auto &argument : projectPart.arguments)
        hash.addData(argument.data(), int(argument.size()));
}
}

Utils::SmallStringVector PchCreator::generateProjectPartCommandLine(
        const V2::ProjectPartContainer &projectPart) const
{
    const Utils::SmallStringVector &arguments = projectPart.arguments;

    Utils::SmallStringVector commandLine;
    commandLine.reserve(arguments.size() + 1);

    commandLine.emplace_back(m_environment.clangCompilerPath());

    append(commandLine , arguments);

    return commandLine;
}

Utils::SmallString PchCreator::generateProjectPartPchFilePathWithoutExtension(
        const V2::ProjectPartContainer &projectPart) const
{
    QByteArray fileName = m_environment.pchBuildDirectory().toUtf8();
    fileName += '/';
    fileName += projectPartHash(projectPart);

    return Utils::SmallString::fromQByteArray(fileName);
}

Utils::PathStringVector PchCreator::generateProjectPartHeaders(
        const V2::ProjectPartContainer &projectPart) const
{
   Utils::PathStringVector headerPaths;
   headerPaths.reserve(projectPart.headerPathIds.size() + m_unsavedFiles.size());

   std::transform(projectPart.headerPathIds.begin(),
                  projectPart.headerPathIds.end(),
                  std::back_inserter(headerPaths),
                  [&] (FilePathId filePathId) {
       return m_filePathCache.filePath(filePathId);
   });

   Utils::PathStringVector generatedPath = generatedFilePaths(m_unsavedFiles);

   std::copy(std::make_move_iterator(generatedPath.begin()),
             std::make_move_iterator(generatedPath.end()),
             std::back_inserter(headerPaths));

   return headerPaths;
}

namespace {

std::size_t sizeOfContent(const Utils::PathStringVector &paths)
{
    return std::accumulate(paths.begin(),
                           paths.end(),
                           std::size_t(0),
                           [] (std::size_t size, const Utils::PathString &path) {
        const char includeTemplate[] = "#include \"\"\n";
        return size + path.size() + sizeof(includeTemplate);
    });
}

Utils::SmallString concatContent(const Utils::PathStringVector &paths, std::size_t size)
{
    Utils::SmallString content;
    content.reserve(size);

    for (const Utils::PathString &path : paths) {
        content += "#include \"";
        content +=  path;
        content += "\"\n";
    };

    return content;
}

}

Utils::SmallString PchCreator::generateProjectPartSourcesContent(
        const V2::ProjectPartContainer &projectPart) const
{
    Utils::PathStringVector paths = generateProjectPartSourcePaths(projectPart);

    return concatContent(paths, sizeOfContent(paths));
}

Utils::PathStringVector PchCreator::generateProjectPartSourcePaths(
        const V2::ProjectPartContainer &projectPart) const
{
    Utils::PathStringVector includeAndSources;
    includeAndSources.reserve(projectPart.sourcePathIds.size());

    appendFilePathId(includeAndSources, projectPart.sourcePathIds, m_filePathCache);

    return includeAndSources;
}

PchCreatorIncludes PchCreator::generateProjectPartPchIncludes(
        const V2::ProjectPartContainer &projectPart) const
{
    Utils::SmallString jointedFileContent = generateProjectPartSourcesContent(projectPart);
    Utils::SmallString jointedFilePath = generateProjectPartSourceFilePath(projectPart);
    auto jointFile = generateFileWithContent(jointedFilePath, jointedFileContent);
    Utils::SmallStringVector arguments = generateProjectPartCommandLine(projectPart);
    arguments.push_back(jointedFilePath);
    FilePath filePath{Utils::PathString(jointedFilePath)};

    IncludeCollector collector(m_filePathCache);

    collector.setExcludedIncludes(generateProjectPartSourcePaths(projectPart));

    collector.addFile(std::string(filePath.directory()),
                      std::string(filePath.name()),
                      {},
                      arguments);

    collector.addUnsavedFiles(m_unsavedFiles);

    collector.collectIncludes();

    jointFile->remove();

    return  {collector.takeIncludeIds(), collector.takeTopIncludeIds(), collector.takeTopsSystemIncludeIds()};
}

Utils::SmallString PchCreator::generateProjectPathPchHeaderFilePath(
        const V2::ProjectPartContainer &projectPart) const
{
    return Utils::SmallString{generateProjectPartPchFilePathWithoutExtension(projectPart), ".h"};
}

Utils::SmallString PchCreator::generateProjectPartPchFilePath(
        const V2::ProjectPartContainer &projectPart) const
{
    return Utils::SmallString{generateProjectPartPchFilePathWithoutExtension(projectPart), ".pch"};
}

Utils::SmallString PchCreator::generateProjectPartSourceFilePath(const V2::ProjectPartContainer &projectPart) const
{
    return Utils::SmallString{generateProjectPartPchFilePathWithoutExtension(projectPart), ".cpp"};
}

Utils::SmallStringVector PchCreator::generateProjectPartPchCompilerArguments(
        const V2::ProjectPartContainer &projectPart) const
{
    Utils::SmallStringVector arguments;
    arguments.reserve(5);

    arguments.emplace_back("-x");
    arguments.emplace_back("c++-header");
    arguments.emplace_back("-Xclang");
    arguments.emplace_back("-emit-pch");
    arguments.emplace_back("-o");
    arguments.emplace_back(generateProjectPartPchFilePath(projectPart));
    arguments.emplace_back(generateProjectPathPchHeaderFilePath(projectPart));

    return arguments;
}

Utils::SmallStringVector PchCreator::generateProjectPartClangCompilerArguments(
        const V2::ProjectPartContainer &projectPart) const
{
    Utils::SmallStringVector compilerArguments = projectPart.arguments.clone();
    const auto pchArguments = generateProjectPartPchCompilerArguments(projectPart);

    append(compilerArguments, pchArguments);

    return compilerArguments;
}

IdPaths PchCreator::generateProjectPartPch(const V2::ProjectPartContainer &projectPart)
{
    long long lastModified = QDateTime::currentSecsSinceEpoch();
    auto includes = generateProjectPartPchIncludes(projectPart);
    auto content = generatePchIncludeFileContent(includes.topIncludeIds);
    auto pchIncludeFilePath = generateProjectPathPchHeaderFilePath(projectPart);
    auto pchFilePath = generateProjectPartPchFilePath(projectPart);
    generateFileWithContent(pchIncludeFilePath, content);

    bool success = generatePch(generateProjectPartClangCompilerArguments(projectPart));

    m_projectPartPch.projectPartId = projectPart.projectPartId;

    if (success) {
        m_projectPartPch.pchPath = std::move(pchFilePath);
        m_projectPartPch.lastModified = lastModified;
    }

    return {projectPart.projectPartId.clone(), std::move(includes.includeIds)};
}

void PchCreator::generatePch(const V2::ProjectPartContainer &projectPart)
{
    m_projectIncludeIds = generateProjectPartPch(projectPart);
}

IdPaths PchCreator::takeProjectIncludes()
{
    return std::move(m_projectIncludeIds);
}

const ProjectPartPch &PchCreator::projectPartPch()
{
    return m_projectPartPch;
}

void PchCreator::setUnsavedFiles(const V2::FileContainers &fileContainers)
{
    m_unsavedFiles = fileContainers;
}

void PchCreator::setIsUsed(bool isUsed)
{
    m_isUsed = isUsed;
}

bool PchCreator::isUsed() const
{
    return m_isUsed;
}

void PchCreator::clear()
{
    m_projectPartPch = ProjectPartPch{};
    m_projectIncludeIds = IdPaths{};
}

void PchCreator::doInMainThreadAfterFinished()
{
    m_pchManagerClient.precompiledHeadersUpdated(ProjectPartPchs{m_projectPartPch});
    m_fileSystemWatcher.updateIdPaths({takeProjectIncludes()});
}

const IdPaths &PchCreator::projectIncludes() const
{
    return m_projectIncludeIds;
}

const FilePathCaching &PchCreator::filePathCache()
{
    return m_filePathCache;
}

std::unique_ptr<QFile> PchCreator::generateFileWithContent(
        const Utils::SmallString &filePath,
        const Utils::SmallString &content)
{
    std::unique_ptr<QFile> precompiledIncludeFile(new QFile(QString(filePath)));

    precompiledIncludeFile->open(QIODevice::WriteOnly);

    precompiledIncludeFile->write(content.data(), qint64(content.size()));
    precompiledIncludeFile->close();

    return precompiledIncludeFile;
}

QByteArray PchCreator::projectPartHash(const V2::ProjectPartContainer &projectPart)
{
    QCryptographicHash hash(QCryptographicHash::Sha1);

    hashProjectPart(hash, projectPart);

    auto result = hash.result();

    return result.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);
}

} // namespace ClangBackEnd