-
Notifications
You must be signed in to change notification settings - Fork 9
/
fileapiparser.cpp
940 lines (823 loc) · 35.8 KB
/
fileapiparser.cpp
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
// 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 "fileapiparser.h"
#include "cmakeprocess.h"
#include "cmakeprojectmanagertr.h"
#include <coreplugin/messagemanager.h>
#include <projectexplorer/rawprojectpart.h>
#include <utils/algorithm.h>
#include <utils/qtcassert.h>
#include <QGuiApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLoggingCategory>
#include <QPromise>
using namespace Utils;
namespace CMakeProjectManager::Internal {
using namespace FileApiDetails;
const char CMAKE_RELATIVE_REPLY_PATH[] = ".cmake/api/v1/reply";
const char CMAKE_RELATIVE_QUERY_PATH[] = ".cmake/api/v1/query";
static Q_LOGGING_CATEGORY(cmakeFileApi, "qtc.cmake.fileApi", QtWarningMsg);
const QStringList CMAKE_QUERY_FILENAMES = {"cache-v2", "codemodel-v2", "cmakeFiles-v1"};
// --------------------------------------------------------------------
// Helper:
// --------------------------------------------------------------------
FilePath FileApiParser::cmakeReplyDirectory(const FilePath &buildDirectory)
{
return buildDirectory.pathAppended(CMAKE_RELATIVE_REPLY_PATH);
}
static void reportFileApiSetupFailure()
{
Core::MessageManager::writeFlashing(
addCMakePrefix(Tr::tr("Failed to set up CMake file API support. %1 cannot "
"extract project information.")
.arg(QGuiApplication::applicationDisplayName())));
}
static std::pair<int, int> cmakeVersion(const QJsonObject &obj)
{
const QJsonObject version = obj.value("version").toObject();
const int major = version.value("major").toInt(-1);
const int minor = version.value("minor").toInt(-1);
return {major, minor};
}
static bool checkJsonObject(const QJsonObject &obj, const QString &kind, int major, int minor = -1)
{
auto version = cmakeVersion(obj);
if (major == -1)
version.first = major;
if (minor == -1)
version.second = minor;
return obj.value("kind").toString() == kind && version == std::make_pair(major, minor);
}
static std::pair<QString, QString> nameValue(const QJsonObject &obj)
{
return {obj.value("name").toString(), obj.value("value").toString()};
}
static QJsonDocument readJsonFile(const FilePath &filePath)
{
qCDebug(cmakeFileApi) << "readJsonFile:" << filePath;
QTC_ASSERT(!filePath.isEmpty(), return {});
const expected_str<QByteArray> contents = filePath.fileContents();
if (!contents)
return {};
const QJsonDocument doc = QJsonDocument::fromJson(*contents);
return doc;
}
std::vector<int> indexList(const QJsonValue &v)
{
const QJsonArray &indexList = v.toArray();
std::vector<int> result;
result.reserve(static_cast<size_t>(indexList.count()));
for (const auto &v : indexList) {
result.push_back(v.toInt(-1));
}
return result;
}
// Reply file:
static ReplyFileContents readReplyFile(const FilePath &filePath, QString &errorMessage)
{
const QJsonDocument document = readJsonFile(filePath);
static const QString msg = Tr::tr("Invalid reply file created by CMake.");
ReplyFileContents result;
if (document.isNull() || document.isEmpty() || !document.isObject()) {
errorMessage = msg;
return result;
}
const QJsonObject rootObject = document.object();
{
const QJsonObject cmakeObject = rootObject.value("cmake").toObject();
{
const QJsonObject paths = cmakeObject.value("paths").toObject();
{
result.cmakeExecutable = paths.value("cmake").toString();
result.ctestExecutable = paths.value("ctest").toString();
result.cmakeRoot = paths.value("root").toString();
}
const QJsonObject generator = cmakeObject.value("generator").toObject();
{
result.generator = generator.value("name").toString();
result.isMultiConfig = generator.value("multiConfig").toBool();
}
const QJsonObject version = cmakeObject.value("version").toObject();
{
int major = version.value("major").toInt();
int minor = version.value("minor").toInt();
int patch = version.value("patch").toInt();
result.cmakeVersion = QVersionNumber(major, minor, patch);
}
}
}
bool hadInvalidObject = false;
{
const QJsonArray objects = rootObject.value("objects").toArray();
for (const auto &v : objects) {
const QJsonObject object = v.toObject();
{
ReplyObject r;
r.kind = object.value("kind").toString();
r.file = object.value("jsonFile").toString();
r.version = cmakeVersion(object);
if (r.kind.isEmpty() || r.file.isEmpty() || r.version.first == -1
|| r.version.second == -1)
hadInvalidObject = true;
else
result.replies.append(r);
}
}
}
if (result.generator.isEmpty() || result.cmakeExecutable.isEmpty() || result.cmakeRoot.isEmpty()
|| result.replies.isEmpty() || hadInvalidObject)
errorMessage = msg;
return result;
}
// Cache file:
static CMakeConfig readCacheFile(const FilePath &cacheFile, QString &errorMessage)
{
CMakeConfig result;
const QJsonDocument doc = readJsonFile(cacheFile);
const QJsonObject root = doc.object();
if (!checkJsonObject(root, "cache", 2)) {
errorMessage = Tr::tr("Invalid cache file generated by CMake.");
return {};
}
const QJsonArray entries = root.value("entries").toArray();
for (const auto &v : entries) {
CMakeConfigItem item;
const QJsonObject entry = v.toObject();
auto nv = nameValue(entry);
item.key = nv.first.toUtf8();
item.value = nv.second.toUtf8();
item.type = CMakeConfigItem::typeStringToType(entry.value("type").toString().toUtf8());
{
const QJsonArray properties = entry.value("properties").toArray();
for (const auto &v : properties) {
const QJsonObject prop = v.toObject();
auto nv = nameValue(prop);
if (nv.first == "ADVANCED") {
const auto boolValue = CMakeConfigItem::toBool(nv.second);
item.isAdvanced = boolValue.has_value() && boolValue.value();
} else if (nv.first == "HELPSTRING") {
item.documentation = nv.second.toUtf8();
} else if (nv.first == "STRINGS") {
item.values = nv.second.split(';');
}
}
}
result.append(item);
}
return result;
}
// CMake Files:
static std::vector<CMakeFileInfo> readCMakeFilesFile(const FilePath &cmakeFilesFile, QString &errorMessage)
{
std::vector<CMakeFileInfo> result;
const QJsonDocument doc = readJsonFile(cmakeFilesFile);
const QJsonObject root = doc.object();
if (!checkJsonObject(root, "cmakeFiles", 1)) {
errorMessage = Tr::tr( "Invalid cmakeFiles file generated by CMake.");
return {};
}
const QJsonArray inputs = root.value("inputs").toArray();
for (const auto &v : inputs) {
CMakeFileInfo info;
const QJsonObject input = v.toObject();
info.path = cmakeFilesFile.withNewPath(input.value("path").toString());
info.isCMake = input.value("isCMake").toBool();
const QString filename = info.path.fileName();
info.isCMakeListsDotTxt = (filename.compare("CMakeLists.txt",
HostOsInfo::fileNameCaseSensitivity())
== 0);
info.isGenerated = input.value("isGenerated").toBool();
info.isExternal = input.value("isExternal").toBool();
result.emplace_back(std::move(info));
}
return result;
}
// Codemodel file:
std::vector<Directory> extractDirectories(const QJsonArray &directories, QString &errorMessage)
{
if (directories.isEmpty()) {
errorMessage = Tr::tr(
"Invalid codemodel file generated by CMake: No directories.");
return {};
}
std::vector<Directory> result;
for (const auto &v : directories) {
const QJsonObject obj = v.toObject();
if (obj.isEmpty()) {
errorMessage = Tr::tr(
"Invalid codemodel file generated by CMake: Empty directory object.");
continue;
}
Directory dir;
dir.sourcePath = obj.value("source").toString();
dir.buildPath = obj.value("build").toString();
dir.parent = obj.value("parentIndex").toInt(-1);
dir.project = obj.value("projectIndex").toInt(-1);
dir.children = indexList(obj.value("childIndexes"));
dir.targets = indexList(obj.value("targetIndexes"));
dir.hasInstallRule = obj.value("hasInstallRule").toBool();
result.emplace_back(std::move(dir));
}
return result;
}
static std::vector<Project> extractProjects(const QJsonArray &projects, QString &errorMessage)
{
if (projects.isEmpty()) {
errorMessage = Tr::tr(
"Invalid codemodel file generated by CMake: No projects.");
return {};
}
std::vector<Project> result;
for (const auto &v : projects) {
const QJsonObject obj = v.toObject();
if (obj.isEmpty()) {
qCDebug(cmakeFileApi) << "Empty project skipped!";
errorMessage = Tr::tr(
"Invalid codemodel file generated by CMake: Empty project object.");
continue;
}
Project project;
project.name = obj.value("name").toString();
project.parent = obj.value("parentIndex").toInt(-1);
project.children = indexList(obj.value("childIndexes"));
project.directories = indexList(obj.value("directoryIndexes"));
project.targets = indexList(obj.value("targetIndexes"));
if (project.directories.empty()) {
qCDebug(cmakeFileApi) << "Invalid project skipped!";
errorMessage = Tr::tr(
"Invalid codemodel file generated by CMake: Broken project data.");
continue;
}
qCDebug(cmakeFileApi) << "Project read:" << project.name << project.directories;
result.emplace_back(std::move(project));
}
return result;
}
static std::vector<Target> extractTargets(const QJsonArray &targets, QString &errorMessage)
{
std::vector<Target> result;
for (const auto &v : targets) {
const QJsonObject obj = v.toObject();
if (obj.isEmpty()) {
errorMessage = Tr::tr(
"Invalid codemodel file generated by CMake: Empty target object.");
continue;
}
Target target;
target.name = obj.value("name").toString();
target.id = obj.value("id").toString();
target.directory = obj.value("directoryIndex").toInt(-1);
target.project = obj.value("projectIndex").toInt(-1);
target.jsonFile = obj.value("jsonFile").toString();
if (target.name.isEmpty() || target.id.isEmpty() || target.jsonFile.isEmpty()
|| target.directory == -1 || target.project == -1) {
errorMessage = Tr::tr(
"Invalid codemodel file generated by CMake: Broken target data.");
continue;
}
result.emplace_back(std::move(target));
}
return result;
}
static bool validateIndexes(const Configuration &config)
{
const int directoryCount = static_cast<int>(config.directories.size());
const int projectCount = static_cast<int>(config.projects.size());
const int targetCount = static_cast<int>(config.targets.size());
int topLevelCount = 0;
for (const Directory &d : config.directories) {
if (d.parent == -1)
++topLevelCount;
if (d.parent < -1 || d.parent >= directoryCount) {
qCWarning(cmakeFileApi)
<< "Directory" << d.sourcePath << ": parent index" << d.parent << "is broken.";
return false;
}
if (d.project < 0 || d.project >= projectCount) {
qCWarning(cmakeFileApi)
<< "Directory" << d.sourcePath << ": project index" << d.project << "is broken.";
return false;
}
if (contains(d.children, [directoryCount](int c) { return c < 0 || c >= directoryCount; })) {
qCWarning(cmakeFileApi)
<< "Directory" << d.sourcePath << ": A child index" << d.children << "is broken.";
return false;
}
if (contains(d.targets, [targetCount](int t) { return t < 0 || t >= targetCount; })) {
qCWarning(cmakeFileApi)
<< "Directory" << d.sourcePath << ": A target index" << d.targets << "is broken.";
return false;
}
}
if (topLevelCount != 1) {
qCWarning(cmakeFileApi) << "Directories: Invalid number of top level directories, "
<< topLevelCount << " (expected: 1).";
return false;
}
topLevelCount = 0;
for (const Project &p : config.projects) {
if (p.parent == -1)
++topLevelCount;
if (p.parent < -1 || p.parent >= projectCount) {
qCWarning(cmakeFileApi)
<< "Project" << p.name << ": parent index" << p.parent << "is broken.";
return false;
}
if (contains(p.children, [projectCount](int p) { return p < 0 || p >= projectCount; })) {
qCWarning(cmakeFileApi)
<< "Project" << p.name << ": A child index" << p.children << "is broken.";
return false;
}
if (contains(p.targets, [targetCount](int t) { return t < 0 || t >= targetCount; })) {
qCWarning(cmakeFileApi)
<< "Project" << p.name << ": A target index" << p.targets << "is broken.";
return false;
}
if (contains(p.directories,
[directoryCount](int d) { return d < 0 || d >= directoryCount; })) {
qCWarning(cmakeFileApi)
<< "Project" << p.name << ": A directory index" << p.directories << "is broken.";
return false;
}
}
if (topLevelCount != 1) {
qCWarning(cmakeFileApi) << "Projects: Invalid number of top level projects, "
<< topLevelCount << " (expected: 1).";
return false;
}
for (const Target &t : config.targets) {
if (t.directory < 0 || t.directory >= directoryCount) {
qCWarning(cmakeFileApi)
<< "Target" << t.name << ": directory index" << t.directory << "is broken.";
return false;
}
if (t.project < 0 || t.project >= projectCount) {
qCWarning(cmakeFileApi)
<< "Target" << t.name << ": project index" << t.project << "is broken.";
return false;
}
}
return true;
}
static std::vector<Configuration> extractConfigurations(const QJsonArray &configs,
QString &errorMessage)
{
if (configs.isEmpty()) {
errorMessage = Tr::tr(
"Invalid codemodel file generated by CMake: No configurations.");
return {};
}
std::vector<FileApiDetails::Configuration> result;
for (const auto &v : configs) {
const QJsonObject obj = v.toObject();
if (obj.isEmpty()) {
errorMessage = Tr::tr(
"Invalid codemodel file generated by CMake: Empty configuration object.");
continue;
}
Configuration config;
config.name = obj.value("name").toString();
config.directories = extractDirectories(obj.value("directories").toArray(), errorMessage);
config.projects = extractProjects(obj.value("projects").toArray(), errorMessage);
config.targets = extractTargets(obj.value("targets").toArray(), errorMessage);
if (!validateIndexes(config)) {
errorMessage = Tr::tr("Invalid codemodel file generated by CMake: Broken "
"indexes in directories, projects, or targets.");
return {};
}
result.emplace_back(std::move(config));
}
return result;
}
static std::vector<Configuration> readCodemodelFile(const FilePath &codemodelFile,
QString &errorMessage)
{
const QJsonDocument doc = readJsonFile(codemodelFile);
const QJsonObject root = doc.object();
if (!checkJsonObject(root, "codemodel", 2)) {
errorMessage = Tr::tr("Invalid codemodel file generated by CMake.");
return {};
}
return extractConfigurations(root.value("configurations").toArray(), errorMessage);
}
// TargetDetails:
static std::vector<FileApiDetails::FragmentInfo> extractFragments(const QJsonObject &obj)
{
const QJsonArray fragments = obj.value("commandFragments").toArray();
return transform<std::vector>(fragments, [](const QJsonValue &v) {
const QJsonObject o = v.toObject();
return FileApiDetails::FragmentInfo{o.value("fragment").toString(),
o.value("role").toString()};
});
}
static void addIncludeInfo(std::vector<IncludeInfo> *includes,
const QJsonObject &compileGroups,
const QString §ion)
{
const std::vector<IncludeInfo> add
= transform<std::vector>(compileGroups.value(section).toArray(), [](const QJsonValue &v) {
const QJsonObject i = v.toObject();
const QString path = i.value("path").toString();
const bool isSystem = i.value("isSystem").toBool();
const ProjectExplorer::HeaderPath hp(path,
isSystem
? ProjectExplorer::HeaderPathType::System
: ProjectExplorer::HeaderPathType::User);
return IncludeInfo{ProjectExplorer::RawProjectPart::frameworkDetectionHeuristic(hp),
i.value("backtrace").toInt(-1)};
});
std::copy(add.cbegin(), add.cend(), std::back_inserter(*includes));
}
static TargetDetails extractTargetDetails(const QJsonObject &root, QString &errorMessage)
{
TargetDetails t;
t.name = root.value("name").toString();
t.id = root.value("id").toString();
t.type = root.value("type").toString();
if (t.name.isEmpty() || t.id.isEmpty() || t.type.isEmpty()) {
errorMessage = Tr::tr("Invalid target file: Information is missing.");
return {};
}
t.backtrace = root.value("backtrace").toInt(-1);
{
const QJsonObject folder = root.value("folder").toObject();
t.folderTargetProperty = folder.value("name").toString();
}
{
const QJsonObject paths = root.value("paths").toObject();
t.sourceDir = FilePath::fromString(paths.value("source").toString());
t.buildDir = FilePath::fromString(paths.value("build").toString());
}
t.nameOnDisk = root.value("nameOnDisk").toString();
{
const QJsonArray artifacts = root.value("artifacts").toArray();
t.artifacts = transform<QList>(artifacts, [](const QJsonValue &v) {
return FilePath::fromString(v.toObject().value("path").toString());
});
}
t.isGeneratorProvided = root.value("isGeneratorProvided").toBool();
{
const QJsonObject install = root.value("install").toObject();
t.installPrefix = install.value("prefix").toObject().value("path").toString();
{
const QJsonArray destinations = install.value("destinations").toArray();
t.installDestination = transform<std::vector>(destinations, [](const QJsonValue &v) {
const QJsonObject o = v.toObject();
return InstallDestination{o.value("path").toString(),
o.value("backtrace").toInt(-1)};
});
}
}
{
const QJsonObject link = root.value("link").toObject();
if (link.isEmpty()) {
t.link = {};
} else {
LinkInfo info;
info.language = link.value("language").toString();
info.isLto = link.value("lto").toBool();
info.sysroot = link.value("sysroot").toObject().value("path").toString();
info.fragments = extractFragments(link);
t.link = info;
}
}
{
const QJsonObject archive = root.value("archive").toObject();
if (archive.isEmpty()) {
t.archive = {};
} else {
ArchiveInfo info;
info.isLto = archive.value("lto").toBool();
info.fragments = extractFragments(archive);
t.archive = info;
}
}
{
const QJsonArray dependencies = root.value("dependencies").toArray();
t.dependencies = transform<std::vector>(dependencies, [](const QJsonValue &v) {
const QJsonObject o = v.toObject();
return DependencyInfo{o.value("id").toString(), o.value("backtrace").toInt(-1)};
});
}
{
const QJsonArray sources = root.value("sources").toArray();
t.sources = transform<std::vector>(sources, [](const QJsonValue &v) {
const QJsonObject o = v.toObject();
return SourceInfo{o.value("path").toString(),
o.value("compileGroupIndex").toInt(-1),
o.value("sourceGroupIndex").toInt(-1),
o.value("backtrace").toInt(-1),
o.value("isGenerated").toBool()};
});
}
{
const QJsonArray sourceGroups = root.value("sourceGroups").toArray();
t.sourceGroups = transform<std::vector>(sourceGroups, [](const QJsonValue &v) {
const QJsonObject o = v.toObject();
return o.value("name").toString();
});
}
{
const QJsonArray compileGroups = root.value("compileGroups").toArray();
t.compileGroups = transform<std::vector>(compileGroups, [](const QJsonValue &v) {
const QJsonObject o = v.toObject();
std::vector<IncludeInfo> includes;
addIncludeInfo(&includes, o, "includes");
// new in CMake 3.27+:
addIncludeInfo(&includes, o, "frameworks");
return CompileInfo{
transform<std::vector>(o.value("sourceIndexes").toArray(),
[](const QJsonValue &v) { return v.toInt(-1); }),
o.value("language").toString(),
transform<QList>(o.value("compileCommandFragments").toArray(),
[](const QJsonValue &v) {
const QJsonObject o = v.toObject();
return o.value("fragment").toString();
}),
includes,
transform<std::vector>(o.value("defines").toArray(),
[](const QJsonValue &v) {
const QJsonObject d = v.toObject();
return DefineInfo{
ProjectExplorer::Macro::fromKeyValue(
d.value("define").toString()),
d.value("backtrace").toInt(-1),
};
}),
o.value("sysroot").toString(),
};
});
}
{
const QJsonObject backtraceGraph = root.value("backtraceGraph").toObject();
t.backtraceGraph.files = transform<std::vector>(backtraceGraph.value("files").toArray(),
[](const QJsonValue &v) {
return v.toString();
});
t.backtraceGraph.commands
= transform<std::vector>(backtraceGraph.value("commands").toArray(),
[](const QJsonValue &v) { return v.toString(); });
t.backtraceGraph.nodes = transform<std::vector>(backtraceGraph.value("nodes").toArray(),
[](const QJsonValue &v) {
const QJsonObject o = v.toObject();
return BacktraceNode{
o.value("file").toInt(-1),
o.value("line").toInt(-1),
o.value("command").toInt(-1),
o.value("parent").toInt(-1),
};
});
}
return t;
}
static int validateBacktraceGraph(const TargetDetails &t)
{
const int backtraceFilesCount = static_cast<int>(t.backtraceGraph.files.size());
const int backtraceCommandsCount = static_cast<int>(t.backtraceGraph.commands.size());
const int backtraceNodeCount = static_cast<int>(t.backtraceGraph.nodes.size());
int topLevelNodeCount = 0;
for (const BacktraceNode &n : t.backtraceGraph.nodes) {
if (n.parent == -1) {
++topLevelNodeCount;
}
if (n.file < 0 || n.file >= backtraceFilesCount) {
qCWarning(cmakeFileApi) << "BacktraceNode: file index" << n.file << "is broken.";
return -1;
}
if (n.command < -1 || n.command >= backtraceCommandsCount) {
qCWarning(cmakeFileApi) << "BacktraceNode: command index" << n.command << "is broken.";
return -1;
}
if (n.parent < -1 || n.parent >= backtraceNodeCount) {
qCWarning(cmakeFileApi) << "BacktraceNode: parent index" << n.parent << "is broken.";
return -1;
}
}
if (topLevelNodeCount == 0 && backtraceNodeCount > 0) { // This is a forest, not a tree
qCWarning(cmakeFileApi) << "BacktraceNode: Invalid number of top level nodes"
<< topLevelNodeCount;
return -1;
}
return backtraceNodeCount;
}
static bool validateTargetDetails(const TargetDetails &t)
{
// The part filled in by the codemodel file has already been covered!
// Internal consistency of backtraceGraph:
const int backtraceCount = validateBacktraceGraph(t);
if (backtraceCount < 0)
return false;
const int sourcesCount = static_cast<int>(t.sources.size());
const int sourceGroupsCount = static_cast<int>(t.sourceGroups.size());
const int compileGroupsCount = static_cast<int>(t.compileGroups.size());
if (t.backtrace < -1 || t.backtrace >= backtraceCount) {
qCWarning(cmakeFileApi) << "TargetDetails" << t.name << ": backtrace index" << t.backtrace
<< "is broken.";
return false;
}
for (const InstallDestination &id : t.installDestination) {
if (id.backtrace < -1 || id.backtrace >= backtraceCount) {
qCWarning(cmakeFileApi) << "TargetDetails" << t.name << ": backtrace index"
<< t.backtrace << "of install destination is broken.";
return false;
}
}
for (const DependencyInfo &dep : t.dependencies) {
if (dep.backtrace < -1 || dep.backtrace >= backtraceCount) {
qCWarning(cmakeFileApi) << "TargetDetails" << t.name << ": backtrace index"
<< t.backtrace << "of dependency is broken.";
return false;
}
}
for (const SourceInfo &s : t.sources) {
if (s.compileGroup < -1 || s.compileGroup >= compileGroupsCount) {
qCWarning(cmakeFileApi) << "TargetDetails" << t.name << ": compile group index"
<< s.compileGroup << "of source info is broken.";
return false;
}
if (s.sourceGroup < -1 || s.sourceGroup >= sourceGroupsCount) {
qCWarning(cmakeFileApi) << "TargetDetails" << t.name << ": source group index"
<< s.sourceGroup << "of source info is broken.";
return false;
}
if (s.backtrace < -1 || s.backtrace >= backtraceCount) {
qCWarning(cmakeFileApi) << "TargetDetails" << t.name << ": backtrace index"
<< s.backtrace << "of source info is broken.";
return false;
}
}
for (const CompileInfo &cg : t.compileGroups) {
for (int s : cg.sources) {
if (s < 0 || s >= sourcesCount) {
qCWarning(cmakeFileApi) << "TargetDetails" << t.name << ": sources index" << s
<< "of compile group is broken.";
return false;
}
}
for (const IncludeInfo &i : cg.includes) {
if (i.backtrace < -1 || i.backtrace >= backtraceCount) {
qCWarning(cmakeFileApi) << "TargetDetails" << t.name << ": includes/backtrace index"
<< i.backtrace << "of compile group is broken.";
return false;
}
}
for (const DefineInfo &d : cg.defines) {
if (d.backtrace < -1 || d.backtrace >= backtraceCount) {
qCWarning(cmakeFileApi) << "TargetDetails" << t.name << ": defines/backtrace index"
<< d.backtrace << "of compile group is broken.";
return false;
}
}
}
return true;
}
static TargetDetails readTargetFile(const FilePath &targetFile, QString &errorMessage)
{
const QJsonDocument doc = readJsonFile(targetFile);
const QJsonObject root = doc.object();
TargetDetails result = extractTargetDetails(root, errorMessage);
if (errorMessage.isEmpty() && !validateTargetDetails(result)) {
errorMessage = Tr::tr(
"Invalid target file generated by CMake: Broken indexes in target details.");
}
return result;
}
// --------------------------------------------------------------------
// ReplyFileContents:
// --------------------------------------------------------------------
FilePath FileApiDetails::ReplyFileContents::jsonFile(const QString &kind, const FilePath &replyDir) const
{
const auto ro = findOrDefault(replies, equal(&ReplyObject::kind, kind));
if (ro.file.isEmpty())
return {};
else
return (replyDir / ro.file).absoluteFilePath();
}
// --------------------------------------------------------------------
// FileApi:
// --------------------------------------------------------------------
bool FileApiParser::setupCMakeFileApi(const FilePath &buildDirectory)
{
// So that we have a directory to watch.
buildDirectory.pathAppended(CMAKE_RELATIVE_REPLY_PATH).ensureWritableDir();
FilePath queryDir = buildDirectory.pathAppended(CMAKE_RELATIVE_QUERY_PATH);
queryDir.ensureWritableDir();
if (!queryDir.exists()) {
reportFileApiSetupFailure();
return false;
}
QTC_ASSERT(queryDir.exists(), return false);
bool failedBefore = false;
for (const FilePath &filePath : cmakeQueryFilePaths(buildDirectory)) {
const bool success = filePath.ensureExistingFile();
if (!success && !failedBefore) {
failedBefore = true;
reportFileApiSetupFailure();
}
}
return true;
}
static QStringList uniqueTargetFiles(const Configuration &config)
{
QSet<QString> knownIds;
QStringList files;
for (const Target &t : config.targets) {
const int knownCount = knownIds.count();
knownIds.insert(t.id);
if (knownIds.count() > knownCount) {
files.append(t.jsonFile);
}
}
return files;
}
FileApiData FileApiParser::parseData(QPromise<std::shared_ptr<FileApiQtcData>> &promise,
const FilePath &replyFilePath,
const QString &cmakeBuildType,
QString &errorMessage)
{
QTC_CHECK(errorMessage.isEmpty());
const FilePath replyDir = replyFilePath.parentDir();
FileApiData result;
const auto cancelCheck = [&promise, &errorMessage] {
if (promise.isCanceled()) {
errorMessage = Tr::tr("CMake parsing was canceled.");
return true;
}
return false;
};
result.replyFile = readReplyFile(replyFilePath, errorMessage);
if (cancelCheck())
return {};
result.cache = readCacheFile(result.replyFile.jsonFile("cache", replyDir), errorMessage);
if (cancelCheck())
return {};
result.cmakeFiles = readCMakeFilesFile(result.replyFile.jsonFile("cmakeFiles", replyDir),
errorMessage);
if (cancelCheck())
return {};
auto codeModels = readCodemodelFile(result.replyFile.jsonFile("codemodel", replyDir),
errorMessage);
if (codeModels.size() == 0) {
errorMessage = Tr::tr("CMake project configuration failed. No CMake configuration for "
"build type \"%1\" found.")
.arg(cmakeBuildType);
return result;
}
auto it = std::find_if(codeModels.begin(), codeModels.end(),
[cmakeBuildType](const Configuration& cfg) {
return QString::compare(cfg.name, cmakeBuildType, Qt::CaseInsensitive) == 0;
});
if (it == codeModels.end()) {
QStringList buildTypes;
for (const Configuration &cfg: codeModels)
buildTypes << cfg.name;
if (result.replyFile.isMultiConfig) {
errorMessage = Tr::tr("No \"%1\" CMake configuration found. Available configurations: \"%2\".\n"
"Make sure that CMAKE_CONFIGURATION_TYPES variable contains the \"Build type\" field.")
.arg(cmakeBuildType)
.arg(buildTypes.join(", "));
} else {
errorMessage = Tr::tr("No \"%1\" CMake configuration found. Available configuration: \"%2\".\n"
"Make sure that CMAKE_BUILD_TYPE variable matches the \"Build type\" field.")
.arg(cmakeBuildType)
.arg(buildTypes.join(", "));
}
return result;
}
result.codemodel = std::move(*it);
if (cancelCheck())
return {};
const QStringList targetFiles = uniqueTargetFiles(result.codemodel);
for (const QString &targetFile : targetFiles) {
if (cancelCheck())
return {};
QString targetErrorMessage;
TargetDetails td = readTargetFile((replyDir / targetFile).absoluteFilePath(), targetErrorMessage);
if (targetErrorMessage.isEmpty()) {
result.targetDetails.emplace_back(std::move(td));
} else {
qWarning() << "Failed to retrieve target data from cmake fileapi:"
<< targetErrorMessage;
errorMessage = targetErrorMessage;
}
}
return result;
}
FilePath FileApiParser::scanForCMakeReplyFile(const FilePath &buildDirectory)
{
const FilePath replyDir = cmakeReplyDirectory(buildDirectory);
if (!replyDir.exists())
return {};
const FilePaths entries = replyDir.dirEntries({{"index-*.json"}, QDir::Files}, QDir::Name);
return entries.isEmpty() ? FilePath() : entries.first();
}
FilePaths FileApiParser::cmakeQueryFilePaths(const FilePath &buildDirectory)
{
const FilePath queryDir = buildDirectory / CMAKE_RELATIVE_QUERY_PATH;
return transform(CMAKE_QUERY_FILENAMES, [&queryDir](const QString &name) {
return queryDir.resolvePath(name);
});
}
} // CMakeProjectManager::Internal