Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4/*
5 * The tool generates deployment artifacts for the Qt builds such as:
6 * - CaMeL case header files named by public C++ symbols located in public module header files
7 * - Header file that contains the module version information, and named as <module>Vesion
8 * - LD version script if applicable
9 * - Aliases or copies of the header files sorted by the generic Qt-types: public/private/qpa
10 * and stored in the corresponding directories.
11 * Also the tool executes conformity checks on each header file if applicable, to make sure they
12 * follow rules that are relevant for their header type.
13 * The tool can be run in two modes: with either '-all' or '-headers' options specified. Depending
14 * on the selected mode, the tool either scans the filesystem to find header files or use the
15 * pre-defined list of header files.
16 */
17
18#include <algorithm>
19#include <iostream>
20#include <fstream>
21#include <string>
22#include <string_view>
23#include <charconv>
24#include <cstring>
25#include <sstream>
26#include <filesystem>
27#include <unordered_map>
28#include <vector>
29#include <regex>
30#include <map>
31#include <set>
32#include <stdexcept>
33#include <array>
34
40
41// Enum contains the list of checks that can be executed on header files.
44 NamespaceChecks = 1, /* Checks if header file is wrapped with QT_<BEGIN|END>_NAMESPACE macros */
45 PrivateHeaderChecks = 2, /* Checks if the public header includes a private header */
46 IncludeChecks = 4, /* Checks if the real header file but not an alias is included */
47 WeMeantItChecks = 8, /* Checks if private header files contains 'We meant it' disclaimer */
49 /* Checks that lead to the fatal error of the sync process: */
52};
53
55
56static const std::regex GlobalHeaderRegex("^q(.*)global\\.h$");
57
58constexpr std::string_view ErrorMessagePreamble = "ERROR: ";
59constexpr std::string_view WarningMessagePreamble = "WARNING: ";
60
61// This comparator is used to sort include records in master header.
62// It's used to put q.*global.h file to the top of the list and sort all other files alphabetically.
63bool MasterHeaderIncludeComparator(const std::string &a, const std::string &b)
64{
65 std::smatch amatch;
66 std::smatch bmatch;
67
68 if (std::regex_match(a, amatch, GlobalHeaderRegex)) {
69 if (std::regex_match(b, bmatch, GlobalHeaderRegex)) {
70 return amatch[1].str().empty()
71 || (!bmatch[1].str().empty() && amatch[1].str() < bmatch[1].str());
72 }
73 return true;
74 } else if (std::regex_match(b, bmatch, GlobalHeaderRegex)) {
75 return false;
76 }
77
78 return a < b;
79};
80
81namespace utils {
82std::string asciiToLower(std::string s)
83{
84 std::transform(s.begin(), s.end(), s.begin(),
85 [](unsigned char c) { return (c >= 'A' && c <= 'Z') ? c | 0x20 : c; });
86 return s;
87}
88
89std::string asciiToUpper(std::string s)
90{
91 std::transform(s.begin(), s.end(), s.begin(),
92 [](unsigned char c) { return (c >= 'a' && c <= 'z') ? c & 0xdf : c; });
93 return s;
94}
95
97{
98 std::array<int, 3> parts = {};
100 std::string error;
101
102 bool ok() const { return error.empty(); }
103};
104
105// Parses "<major>.<minor>" or "<major>.<minor>.<patch>", ignoring surrounding whitespace.
106// Unused parts are left as 0.
107VersionParseResult parseVersion(const std::string &version)
108{
109 static const std::regex VersionPartsRegex("\\s*(\\d+)\\.(\\d+)(?:\\.(\\d+))?\\s*");
110
111 VersionParseResult result;
112 std::smatch match;
113 if (!std::regex_match(version, match, VersionPartsRegex)) {
114 result.error = "expected 2 or 3 dot-separated integer parts";
115 return result;
116 }
117
118 for (size_t i = 1; i < match.size(); ++i) {
119 if (!match[i].matched)
120 // Skip over 'patch' match for a 2-part version.
121 continue;
122 const std::string part = match[i].str();
123 int value = 0;
124 const auto [_, errorCode] = std::from_chars(part.data(), part.data() + part.size(), value);
125 if (errorCode != std::errc{}) {
126 result.error = "failed to convert version part '" + part + "' to an integer";
127 result.count = 0;
128 return result;
129 }
130 result.parts[result.count++] = value;
131 }
132 return result;
133}
134
136{
137 struct : public std::streambuf
138 {
139 int overflow(int c) override { return c; }
140 } buff;
141
142public:
144} DummyOutput;
145
147{
148 std::cerr << "Internal error. Please create bugreport at https://bugreports.qt.io "
149 "using 'Build tools: Other component.'"
150 << std::endl;
151}
152
153void printFilesystemError(const std::filesystem::filesystem_error &fserr, std::string_view errorMsg)
154{
155 std::cerr << errorMsg << ": " << fserr.path1() << ".\n"
156 << fserr.what() << "(" << fserr.code().value() << ")" << std::endl;
157}
158
159std::filesystem::path normalizedPath(const std::string &path)
160{
161 try {
162 auto result = std::filesystem::path(std::filesystem::weakly_canonical(path).generic_string());
163 return result;
164 } catch (const std::filesystem::filesystem_error &fserr) {
165 printFilesystemError(fserr, "Unable to normalize path");
166 throw;
167 }
168}
169
170bool createDirectories(const std::string &path, std::string_view errorMsg, bool *exists = nullptr)
171{
172 bool result = true;
173 try {
174 if (!std::filesystem::exists(path)) {
175 if (exists)
176 *exists = false;
177 std::filesystem::create_directories(path);
178 } else {
179 if (exists)
180 *exists = true;
181 }
182 } catch (const std::filesystem::filesystem_error &fserr) {
183 result = false;
184 std::cerr << errorMsg << ": " << path << ".\n"
185 << fserr.code().message() << "(" << fserr.code().value() << "):" << fserr.what()
186 << std::endl;
187 }
188 return result;
189}
190
191} // namespace utils
192
193using FileStamp = std::filesystem::file_time_type;
194
196{
197 template<typename T>
198 struct CommandLineOption
199 {
200 CommandLineOption(T *_value, bool _isOptional = false)
201 : value(_value), isOptional(_isOptional)
202 {
203 }
204
205 T *value;
206 bool isOptional;
207 };
208
209public:
210 CommandLineOptions(int argc, char *argv[]) : m_isValid(parseArguments(argc, argv)) { }
211
212 bool isValid() const { return m_isValid; }
213
214 const std::string &moduleName() const { return m_moduleName; }
215
216 const std::string &moduleVersion() const { return m_moduleVersion; }
217 int moduleVersionMajor() const { return m_moduleVersionMajor; }
218 int moduleVersionMinor() const { return m_moduleVersionMinor; }
219 int moduleVersionPatch() const { return m_moduleVersionPatch; }
220
221 const std::string &sourceDir() const { return m_sourceDir; }
222
223 const std::string &binaryDir() const { return m_binaryDir; }
224
225 const std::string &includeDir() const { return m_includeDir; }
226
227 const std::string &installIncludeDir() const { return m_installIncludeDir; }
228
229 const std::string &privateIncludeDir() const { return m_privateIncludeDir; }
230
231 const std::string &qpaIncludeDir() const { return m_qpaIncludeDir; }
232
233 const std::string &rhiIncludeDir() const { return m_rhiIncludeDir; }
234
235 const std::string &ssgIncludeDir() const { return m_ssgIncludeDir; }
236
237 const std::string &spiIncludeDir() const { return m_spiIncludeDir; }
238
239 const std::string &stagingDir() const { return m_stagingDir; }
240
241 const std::string &versionScriptFile() const { return m_versionScriptFile; }
242
243 const std::string &moduleMapFile() const { return m_moduleMapFile; }
244
245 const std::set<std::string> &knownModules() const { return m_knownModules; }
246
247 const std::regex &qpaHeadersRegex() const { return m_qpaHeadersRegex; }
248
249 const std::regex &rhiHeadersRegex() const { return m_rhiHeadersRegex; }
250
251 const std::regex &ssgHeadersRegex() const { return m_ssgHeadersRegex; }
252
253 const std::regex &spiHeadersRegex() const { return m_spiHeadersRegex; }
254
255 const std::regex &privateHeadersRegex() const { return m_privateHeadersRegex; }
256
257 const std::regex &publicNamespaceRegex() const { return m_publicNamespaceRegex; }
258
259 const std::set<std::string> &headers() const { return m_headers; }
260
261 const std::set<std::string> &generatedHeaders() const { return m_generatedHeaders; }
262
263 bool scanAllMode() const { return m_scanAllMode; }
264
265 bool isInternal() const { return m_isInternal; }
266
267 bool isNonQtModule() const { return m_isNonQtModule; }
268
269 bool printHelpOnly() const { return m_printHelpOnly; }
270
271 bool debug() const { return m_debug; }
272
273 bool copy() const { return m_copy; }
274
275 bool minimal() const { return m_minimal; }
276
277 bool showOnly() const { return m_showOnly; }
278
279 bool isFramework() const { return m_isFramework; }
280
281 bool warningsAreErrors() const { return m_warningsAreErrors; }
282
283 void printHelp() const
284 {
285 std::cout << "Usage: syncqt -sourceDir <dir> -binaryDir <dir> -module <module name>"
286 " -includeDir <dir> -privateIncludeDir <dir> -qpaIncludeDir <dir> -rhiIncludeDir <dir> -ssgIncludeDir <dir>"
287 " -spiIncludeDir <dir>"
288 " -stagingDir <dir> <-headers <header list>|-all> [-debug]"
289 " [-moduleVersion <version>]" // TODO: Make it required in Qt 6.13
290 " [-versionScript <path>] [-qpaHeadersFilter <regex>] [-rhiHeadersFilter <regex>]"
291 " [-spiHeadersFilter <regex>]"
292 " [-knownModules <module1> <module2>... <moduleN>]"
293 " [-nonQt] [-internal] [-copy]\n"
294 ""
295 "Mandatory arguments:\n"
296 " -module Module name.\n"
297 " -headers List of header files.\n"
298 " -all In 'all' mode syncqt scans source\n"
299 " directory for public qt headers and\n"
300 " artifacts not considering CMake source\n"
301 " tree. The main use cases are the \n"
302 " generating of documentation and creating\n"
303 " API review changes.\n"
304 " -sourceDir Module source directory.\n"
305 " -binaryDir Module build directory.\n"
306 " -includeDir Module include directory where the\n"
307 " generated header files will be located.\n"
308 " -privateIncludeDir Module include directory for the\n"
309 " generated private header files.\n"
310 " -qpaIncludeDir Module include directory for the \n"
311 " generated QPA header files.\n"
312 " -rhiIncludeDir Module include directory for the \n"
313 " generated RHI header files.\n"
314 " -ssgIncludeDir Module include directory for the \n"
315 " generated SSG header files.\n"
316 " -spiIncludeDir Module include directory for the \n"
317 " generated SPI (semi-private or\n"
318 " service-provider interface) header files.\n"
319 " -stagingDir Temporary staging directory to collect\n"
320 " artifacts that need to be installed.\n"
321 " -knownModules list of known modules. syncqt uses the\n"
322 " list to check the #include macros\n"
323 " consistency.\n"
324 " -moduleMapFile Module maps file to generate.\n"
325 " syncqt uses the .in file path as the\n"
326 " template.\n"
327 "Optional arguments:\n"
328 " -internal Indicates that the module is internal.\n"
329 " -nonQt Indicates that the module is not a Qt\n"
330 " module.\n"
331 " -privateHeadersFilter Regex that filters private header files\n"
332 " from the list of 'headers'.\n"
333 " -qpaHeadersFilter Regex that filters qpa header files from.\n"
334 " the list of 'headers'.\n"
335 " -rhiHeadersFilter Regex that filters rhi header files from.\n"
336 " the list of 'headers'.\n"
337 " -ssgHeadersFilter Regex that filters ssg files from.\n"
338 " the list of 'headers'.\n"
339 " -spiHeadersFilter Regex that filters SPI (semi-private or\n"
340 " service-provider interface) header files\n"
341 " from the list of 'headers'.\n"
342 " -publicNamespaceFilter Symbols that are in the specified\n"
343 " namespace.\n"
344 " are treated as public symbols.\n"
345 " -moduleVersion Specify the module's version.\n"
346 " Defaults to the Qt version.\n"
347 " -versionScript Generate linker version script by\n"
348 " provided path.\n"
349 " -debug Enable debug output.\n"
350 " -copy Copy header files instead of creating\n"
351 " aliases.\n"
352 " -minimal Do not create CaMeL case headers for the\n"
353 " public C++ symbols.\n"
354 " -showonly Show actions, but not perform them.\n"
355 " -framework Indicates that the module is built as a\n"
356 " framework. Generates lowercase forwarding\n"
357 " headers so the framework's headers can\n"
358 " also be reached via a plain include path.\n"
359 " -warningsAreErrors Treat all warnings as errors.\n"
360 " -help Print this help.\n";
361 }
362
363private:
364 template<typename T>
365 [[nodiscard]] bool checkRequiredArguments(const std::unordered_map<std::string, T> &arguments)
366 {
367 bool ret = true;
368 for (const auto &argument : arguments) {
369 if (!argument.second.isOptional
370 && (!argument.second.value || argument.second.value->size()) == 0) {
371 std::cerr << "Missing argument: " << argument.first << std::endl;
372 ret = false;
373 }
374 }
375 return ret;
376 }
377
378 [[nodiscard]] bool parseArguments(int argc, char *argv[])
379 {
380 std::string qpaHeadersFilter;
381 std::string rhiHeadersFilter;
382 std::string ssgHeadersFilter;
383 std::string spiHeadersFilter;
384 std::string privateHeadersFilter;
385 std::string publicNamespaceFilter;
386 const std::unordered_map<std::string, CommandLineOption<std::string>> stringArgumentMap = {
387 { "-module", { &m_moduleName } },
388 { "-sourceDir", { &m_sourceDir } },
389 { "-binaryDir", { &m_binaryDir } },
390 { "-installIncludeDir", { &m_installIncludeDir, true } },
391 { "-privateHeadersFilter", { &privateHeadersFilter, true } },
392 { "-qpaHeadersFilter", { &qpaHeadersFilter, true } },
393 { "-rhiHeadersFilter", { &rhiHeadersFilter, true } },
394 { "-ssgHeadersFilter", { &ssgHeadersFilter, true } },
395 { "-spiHeadersFilter", { &spiHeadersFilter, true } },
396 { "-includeDir", { &m_includeDir } },
397 { "-privateIncludeDir", { &m_privateIncludeDir } },
398 { "-qpaIncludeDir", { &m_qpaIncludeDir } },
399 { "-rhiIncludeDir", { &m_rhiIncludeDir } },
400 { "-ssgIncludeDir", { &m_ssgIncludeDir } },
401 { "-spiIncludeDir", { &m_spiIncludeDir } },
402 { "-stagingDir", { &m_stagingDir, true } },
403 { "-versionScript", { &m_versionScriptFile, true } },
404 { "-publicNamespaceFilter", { &publicNamespaceFilter, true } },
405 { "-moduleMapFile", { &m_moduleMapFile, true } },
406 { "-moduleVersion", { &m_moduleVersion, true } },
407 };
408
409 const std::unordered_map<std::string, CommandLineOption<std::set<std::string>>>
410 listArgumentMap = {
411 { "-headers", { &m_headers, true } },
412 { "-generatedHeaders", { &m_generatedHeaders, true } },
413 { "-knownModules", { &m_knownModules, true } },
414 };
415
416 const std::unordered_map<std::string, CommandLineOption<bool>> boolArgumentMap = {
417 { "-nonQt", { &m_isNonQtModule, true } }, { "-debug", { &m_debug, true } },
418 { "-help", { &m_printHelpOnly, true } },
419 { "-internal", { &m_isInternal, true } }, { "-all", { &m_scanAllMode, true } },
420 { "-copy", { &m_copy, true } }, { "-minimal", { &m_minimal, true } },
421 { "-showonly", { &m_showOnly, true } }, { "-showOnly", { &m_showOnly, true } },
422 { "-framework", { &m_isFramework, true } },
423 { "-warningsAreErrors", { &m_warningsAreErrors, true } }
424 };
425
426 std::string *currentValue = nullptr;
427 std::set<std::string> *currentListValue = nullptr;
428
429 auto parseArgument = [&](const std::string &arg) -> bool {
430 if (arg[0] == '-') {
431 currentValue = nullptr;
432 currentListValue = nullptr;
433 {
434 auto it = stringArgumentMap.find(arg);
435 if (it != stringArgumentMap.end()) {
436 if (it->second.value == nullptr) {
438 return false;
439 }
440 currentValue = it->second.value;
441 return true;
442 }
443 }
444
445 {
446 auto it = boolArgumentMap.find(arg);
447 if (it != boolArgumentMap.end()) {
448 if (it->second.value == nullptr) {
450 return false;
451 }
452 *(it->second.value) = true;
453 return true;
454 }
455 }
456
457 {
458 auto it = listArgumentMap.find(arg);
459 if (it != listArgumentMap.end()) {
460 if (it->second.value == nullptr) {
462 return false;
463 }
464 currentListValue = it->second.value;
465 currentListValue->insert(""); // Indicate that argument is provided
466 return true;
467 }
468 }
469
470 std::cerr << "Unknown argument: " << arg << std::endl;
471 return false;
472 }
473
474 if (currentValue != nullptr) {
475 *currentValue = arg;
476 currentValue = nullptr;
477 } else if (currentListValue != nullptr) {
478 currentListValue->insert(arg);
479 } else {
480 std::cerr << "Unknown argument: " << arg << std::endl;
481 return false;
482 }
483 return true;
484 };
485
486 for (int i = 1; i < argc; ++i) {
487 std::string arg(argv[i]);
488 if (arg.empty())
489 continue;
490
491 if (arg[0] == '@') {
492 std::ifstream ifs(arg.substr(1), std::ifstream::in);
493 if (!ifs.is_open()) {
494 std::cerr << "Unable to open rsp file: " << arg[0] << std::endl;
495 return false;
496 }
497 std::string argFromFile;
498 while (std::getline(ifs, argFromFile)) {
499 if (argFromFile.empty())
500 continue;
501 if (!parseArgument(argFromFile))
502 return false;
503 }
504 ifs.close();
505 continue;
506 }
507
508 if (!parseArgument(arg))
509 return false;
510 }
511
512 if (m_printHelpOnly)
513 return true;
514
515 if (!qpaHeadersFilter.empty())
516 m_qpaHeadersRegex = std::regex(qpaHeadersFilter);
517
518 if (!rhiHeadersFilter.empty())
519 m_rhiHeadersRegex = std::regex(rhiHeadersFilter);
520
521 if (!ssgHeadersFilter.empty())
522 m_ssgHeadersRegex = std::regex(ssgHeadersFilter);
523
524 if (!spiHeadersFilter.empty())
525 m_spiHeadersRegex = std::regex(spiHeadersFilter);
526
527 if (!privateHeadersFilter.empty())
528 m_privateHeadersRegex = std::regex(privateHeadersFilter);
529
530 if (!publicNamespaceFilter.empty())
531 m_publicNamespaceRegex = std::regex(publicNamespaceFilter);
532
533 if (m_headers.empty() && !m_scanAllMode) {
534 std::cerr << "You need to specify either -headers or -all option." << std::endl;
535 return false;
536 }
537
538 if (!m_headers.empty() && m_scanAllMode) {
539 std::cerr << "Both -headers and -all are specified. Need to choose only one"
540 "operational mode." << std::endl;
541 return false;
542 }
543
544 if (m_moduleVersion.empty()) {
545 // TODO: Make the argument required in Qt 6.13. For now default to the Qt version.
546 m_moduleVersion = QT_VERSION_STR;
547 }
548
549 const utils::VersionParseResult version = utils::parseVersion(m_moduleVersion);
550 if (!version.ok()) {
551 std::cerr << "Failed to parse module version '" << m_moduleVersion << "': "
552 << version.error
553 << ". The version is expected to be in the format "
554 "<major>.<minor>[.<patch>]." << std::endl;
555 return false;
556 }
557
558 for (size_t i = 0; i < version.count; ++i) {
559 if (version.parts[i] > 255) {
560 std::cerr << "Module version part '" << version.parts[i]
561 << "' can not be encoded into a 2 digit hexidecimal number which "
562 << "is embbedded into the module version file. Operating on the value "
563 << "using macros like QT_VERSION_CHECK will not work correctly."
564 << std::endl;
565 }
566 }
567
568 m_moduleVersionMajor = version.parts[0];
569 m_moduleVersionMinor = version.parts[1];
570 m_moduleVersionPatch = version.parts[2];
571
572 for (const auto &argument : listArgumentMap)
573 argument.second.value->erase("");
574
575 bool ret = true;
576 ret &= checkRequiredArguments(stringArgumentMap);
577 ret &= checkRequiredArguments(listArgumentMap);
578
579 normalizePaths();
580
581 return ret;
582 }
583
584 // Convert all paths from command line to a generic one.
585 void normalizePaths()
586 {
587 const std::array paths = {
588 &m_sourceDir, &m_binaryDir, &m_includeDir,
589 &m_installIncludeDir, &m_privateIncludeDir, &m_qpaIncludeDir,
590 &m_rhiIncludeDir, &m_stagingDir, &m_versionScriptFile,
591 &m_spiIncludeDir,
592 };
593 for (auto path : paths) {
594 if (!path->empty())
595 *path = utils::normalizedPath(*path).generic_string();
596 }
597
598 // Match the resolution done by makeHeaderAbsolute(), so that isHeaderGenerated() finds
599 // headers whose path contains symlinks.
600 std::set<std::string> generatedHeaders;
601 for (const auto &header : m_generatedHeaders) {
602 if (header.empty())
603 continue;
604 const std::string absolute = std::filesystem::path(header).is_relative()
605 ? m_sourceDir + '/' + header
606 : header;
607 generatedHeaders.insert(utils::normalizedPath(absolute).generic_string());
608 }
609 m_generatedHeaders = std::move(generatedHeaders);
610 }
611
612 std::string m_moduleName;
613 std::string m_moduleVersion;
614 int m_moduleVersionMajor;
615 int m_moduleVersionMinor;
616 int m_moduleVersionPatch;
617 std::string m_sourceDir;
618 std::string m_binaryDir;
619 std::string m_includeDir;
620 std::string m_installIncludeDir;
621 std::string m_privateIncludeDir;
622 std::string m_qpaIncludeDir;
623 std::string m_rhiIncludeDir;
624 std::string m_ssgIncludeDir;
625 std::string m_spiIncludeDir;
626 std::string m_stagingDir;
627 std::string m_versionScriptFile;
628 std::string m_moduleMapFile;
629 std::set<std::string> m_knownModules;
630 std::set<std::string> m_headers;
631 std::set<std::string> m_generatedHeaders;
632 bool m_scanAllMode = false;
633 bool m_copy = false;
634 bool m_isNonQtModule = false;
635 bool m_isInternal = false;
636 bool m_printHelpOnly = false;
637 bool m_debug = false;
638 bool m_minimal = false;
639 bool m_showOnly = false;
640 bool m_isFramework = false;
641 bool m_warningsAreErrors = false;
642 std::regex m_qpaHeadersRegex;
643 std::regex m_rhiHeadersRegex;
644 std::regex m_ssgHeadersRegex;
645 std::regex m_spiHeadersRegex;
646 std::regex m_privateHeadersRegex;
647 std::regex m_publicNamespaceRegex;
648
649 bool m_isValid;
650};
651
653{
654 class SymbolDescriptor
655 {
656 public:
657 // Where the symbol comes from
658 enum SourceType {
659 Pragma = 0, // pragma qt_class is mentioned a header file
660 Declaration, // The symbol declaration inside a header file
661 MaxSourceType
662 };
663
664 void update(const std::string &file, SourceType type)
665 {
666 if (type < m_type) {
667 m_file = file;
668 m_type = type;
669 }
670 }
671
672 // The file that contains a symbol.
673 const std::string &file() const { return m_file; }
674
675 private:
676 SourceType m_type = MaxSourceType;
677 std::string m_file;
678 };
680
681 struct ParsingResult
682 {
683 std::vector<std::string> versionScriptContent;
684 std::string requireConfig;
685 bool masterInclude = true;
686 };
687
688 CommandLineOptions *m_commandLineArgs = nullptr;
689
690 std::map<std::string /* header file name */, std::string /* header feature guard name */,
691 decltype(MasterHeaderIncludeComparator) *>
692 m_masterHeaderContents;
693 std::string m_masterHeaderBuffer;
694
695 std::unordered_map<std::string /* the deprecated header name*/,
696 std::string /* the replacement */>
697 m_deprecatedHeaders;
698 std::vector<std::string> m_versionScriptContents;
699 std::set<std::string> m_producedHeaders;
700 std::set<std::string> m_publicHeaders;
701 std::vector<std::string> m_headerCheckExceptions;
702 std::map<std::string,std::string> m_moduleMapContents;
703 SymbolContainer m_symbols;
704 std::ostream &scannerDebug() const
705 {
706 if (m_commandLineArgs->debug())
707 return std::cout;
708 return utils::DummyOutput;
709 }
710
711 enum { Active, Stopped, IgnoreNext, Ignore } m_versionScriptGeneratorState = Active;
712
713 std::filesystem::path m_outputRootName;
714 std::filesystem::path m_currentFile;
715 std::string m_currentFilename;
716 std::string m_currentFileString;
717 size_t m_currentFileLineNumber = 0;
718 bool m_currentFileInSourceDir = false;
719
720 enum FileType {
721 PublicHeader = 0,
722 PrivateHeader = 1,
723 QpaHeader = 2,
724 ExportHeader = 4,
725 RhiHeader = 8,
726 SsgHeader = 16,
727 SpiHeader = 32
728 };
729 unsigned int m_currentFileType = PublicHeader;
730
731 int m_criticalChecks = CriticalChecks;
732 std::string_view m_warningMessagePreamble;
733
734public:
743
744 // The function converts the relative path to a header files to the absolute. It also makes the
745 // path canonical(removes '..' and '.' parts of the path). The source directory passed in
746 // '-sourceDir' command line argument is used as base path for relative paths to create the
747 // absolute path.
748 [[nodiscard]] std::filesystem::path makeHeaderAbsolute(const std::string &filename) const;
749
751 {
752 if (m_commandLineArgs->warningsAreErrors()) {
753 m_criticalChecks = AllChecks;
754 m_warningMessagePreamble = ErrorMessagePreamble;
755 }
756
757 m_versionScriptGeneratorState =
758 m_commandLineArgs->versionScriptFile().empty() ? Stopped : Active;
759 auto error = NoError;
760
761 // In the scan all mode we ingore the list of header files that is specified in the
762 // '-headers' argument, and collect header files from the source directory tree.
763 if (m_commandLineArgs->scanAllMode()) {
764 enum class HeaderOrigin { SourceTree, Generated };
765 const auto scanHeaderFile = [this, &error](const std::filesystem::path &path,
766 bool isRegularFile, HeaderOrigin origin) {
767 const std::string filePath = path.generic_string();
768 const bool isHeaderFlag = isHeader(path);
769 const bool isDocFileHeuristicFlag = isDocFileHeuristic(filePath);
770 const bool isGenerated = origin == HeaderOrigin::Generated;
771
772 if (isRegularFile && isHeaderFlag && !isDocFileHeuristicFlag) {
773 scannerDebug() << "Processing header: " << filePath
774 << " isGenerated: " << isGenerated << std::endl;
776 error = SyncFailed;
777 } else {
778 scannerDebug()
779 << "Skipping processing header: " << filePath
780 << " isRegularFile: " << isRegularFile
781 << " isHeaderFlag: " << isHeaderFlag
782 << " isDocFileHeuristicFlag: " << isDocFileHeuristicFlag
783 << " isGenerated: " << isGenerated
784 << std::endl;
785 }
786 };
787
788 for (auto const &entry :
789 std::filesystem::recursive_directory_iterator(m_commandLineArgs->sourceDir())) {
790 scanHeaderFile(entry.path(), entry.is_regular_file(),
791 HeaderOrigin::SourceTree);
792 }
793
794 // Headers that are generated into the build directory are not covered by the source
795 // directory scan above, so process them explicitly.
796 for (const auto &header : m_commandLineArgs->generatedHeaders()) {
797 if (header.empty())
798 continue;
799 const auto headerPath = makeHeaderAbsolute(header);
800 scanHeaderFile(headerPath, std::filesystem::is_regular_file(headerPath),
801 HeaderOrigin::Generated);
802 }
803 } else {
804 // Since the list of header file is quite big syncqt supports response files to avoid
805 // the issues with long command lines.
806 std::set<std::string> rspHeaders;
807 const auto &headers = m_commandLineArgs->headers();
808 for (auto it = headers.begin(); it != headers.end(); ++it) {
809 const auto &header = *it;
810 scannerDebug() << "Processing header: " << header << std::endl;
812 error = SyncFailed;
813 }
814 }
815 for (const auto &header : rspHeaders) {
816 scannerDebug() << "Processing header: " << header << std::endl;
817 if (!processHeader(makeHeaderAbsolute(header)))
818 error = SyncFailed;
819 }
820 }
821
822 // No further processing in minimal mode.
823 if (m_commandLineArgs->minimal())
824 return error;
825
826 // Generate aliases for all unique symbols collected during the header files parsing.
827 for (auto it = m_symbols.begin(); it != m_symbols.end(); ++it) {
828 const std::string &filename = it->second.file();
829 if (!filename.empty()) {
830 const auto camelCaseFile = m_commandLineArgs->includeDir() + '/' + it->first;
831 if (generateForwardingHeader(camelCaseFile, filename)) {
832 m_producedHeaders.insert(it->first);
833 m_moduleMapContents.insert({camelCaseFile, filename});
834 } else {
835 error = SyncFailed;
836 }
837 }
838 }
839
840 // Generate the header file containing version information.
841 if (!m_commandLineArgs->isNonQtModule()) {
842 std::string moduleNameLower = utils::asciiToLower(m_commandLineArgs->moduleName());
843 std::string versionHeaderFilename(moduleNameLower + "version.h");
844 std::string versionHeaderCamel(m_commandLineArgs->moduleName() + "Version");
845 std::string versionFile = m_commandLineArgs->includeDir() + '/' + versionHeaderFilename;
846
847 std::error_code ec;
848 FileStamp originalStamp = std::filesystem::last_write_time(versionFile, ec);
849 if (ec)
850 originalStamp = FileStamp::clock::now();
851
852 if (generateVersionHeader(versionFile)) {
853 const auto camelCaseFile =
854 m_commandLineArgs->includeDir() + '/' + versionHeaderCamel;
855 if (!generateAliasedHeaderFileIfTimestampChanged(camelCaseFile,
856 versionFile, originalStamp)) {
857 error = SyncFailed;
858 }
859 m_masterHeaderContents[versionHeaderFilename] = {};
860 m_producedHeaders.insert(versionHeaderFilename);
861 m_producedHeaders.insert(versionHeaderCamel);
862 m_moduleMapContents.insert({versionFile, {}});
863 m_moduleMapContents.insert({camelCaseFile, versionFile});
864 } else {
865 error = SyncFailed;
866 }
867 }
868
869 if (!m_commandLineArgs->scanAllMode()) {
870 if (!m_commandLineArgs->isNonQtModule()) {
872 error = SyncFailed;
873
875 error = SyncFailed;
876 }
877
878 if (!m_commandLineArgs->versionScriptFile().empty()) {
880 error = SyncFailed;
881 }
882 }
883
884 if (!m_commandLineArgs->isNonQtModule()) {
886 error = SyncFailed;
887 }
888
889 if (!m_commandLineArgs->moduleMapFile().empty()) {
891 error = SyncFailed;
892 }
893
894 if (!m_commandLineArgs->scanAllMode() && !m_commandLineArgs->stagingDir().empty()) {
895 // Copy the generated files to a spearate staging directory to make the installation
896 // process eaiser.
898 error = SyncFailed;
899
900 // For framework builds the staging directory is installed into the non-framework
901 // include/<Module> dir alongside the framework, so that its headers can also be
902 // reached via a plain include path. Generate lowercase forwarding headers there
903 // (in addition to the CaMeL case aliases copied above) so that bare includes like
904 // #include <qstring.h> resolve into the framework. These are generated after the
905 // copy above so they are not overwritten by the build-tree source aliases.
906 if (m_commandLineArgs->isFramework()) {
907 for (const auto &header : m_publicHeaders) {
908 if (!generateForwardingHeader(m_commandLineArgs->stagingDir() + '/' + header,
909 header, /*frameworkForwarder=*/true)) {
910 error = SyncFailed;
911 }
912 }
913 }
914 }
915 return error;
916 }
917
918 // The function copies files, that were generated while the sync procedure to a staging
919 // directory. This is necessary to simplify the installation of the generated files.
920 [[nodiscard]] bool copyGeneratedHeadersToStagingDirectory(const std::string &outputDirectory,
921 bool skipCleanup = false)
922 {
923 bool result = true;
924 bool outDirExists = false;
925 if (!utils::createDirectories(outputDirectory, "Unable to create staging directory",
926 &outDirExists))
927 return false;
928
929 if (outDirExists && !skipCleanup) {
930 try {
931 for (const auto &entry :
932 std::filesystem::recursive_directory_iterator(outputDirectory)) {
933 if (m_producedHeaders.find(entry.path().filename().generic_string())
934 == m_producedHeaders.end()) {
935 // Check if header file came from another module as result of the
936 // cross-module deprecation before removing it.
937 std::string firstLine;
938 {
939 std::ifstream input(entry.path(), std::ifstream::in);
940 if (input.is_open()) {
941 std::getline(input, firstLine);
942 input.close();
943 }
944 }
945 if (firstLine.find("#ifndef DEPRECATED_HEADER_"
946 + m_commandLineArgs->moduleName())
947 == 0
948 || firstLine.find("#ifndef DEPRECATED_HEADER_") != 0)
949 std::filesystem::remove(entry.path());
950 }
951 }
952 } catch (const std::filesystem::filesystem_error &fserr) {
953 utils::printFilesystemError(fserr, "Unable to clean the staging directory");
954 return false;
955 }
956 }
957
958 for (const auto &header : m_producedHeaders) {
959 std::filesystem::path src(m_commandLineArgs->includeDir() + '/' + header);
960 std::filesystem::path dst(outputDirectory + '/' + header);
961 if (m_commandLineArgs->showOnly())
962 continue;
963 // A concurrent syncqt -all run could write a module header with different content
964 // to the include directory. So instead of copying that file, write the
965 // 'correct' module header contents from memory directly into the staging directory.
966 if (header == m_commandLineArgs->moduleName())
967 result &= writeIfDifferent(dst.string(), m_masterHeaderBuffer);
968 else
969 result &= updateOrCopy(src, dst);
970 }
971 return result;
972 }
973
974 void resetCurrentFileInfoData(const std::filesystem::path &headerFile)
975 {
976 // This regex filters the generated '*exports.h' and '*exports_p.h' header files.
977 static const std::regex ExportsHeaderRegex("^q(.*)exports(_p)?\\.h$");
978
979 m_currentFile = headerFile;
980 m_currentFileLineNumber = 0;
981 m_currentFilename = m_currentFile.filename().generic_string();
982 m_currentFileType = PublicHeader;
983 m_currentFileString = m_currentFile.generic_string();
984 m_currentFileInSourceDir = m_currentFileString.find(m_commandLineArgs->sourceDir()) == 0;
985
986 if (isHeaderPrivate(m_currentFilename))
987 m_currentFileType = PrivateHeader;
988
989 if (isHeaderQpa(m_currentFilename))
990 m_currentFileType = QpaHeader | PrivateHeader;
991
992 if (isHeaderRhi(m_currentFilename))
993 m_currentFileType = RhiHeader | PrivateHeader;
994
995 if (isHeaderSsg(m_currentFilename))
996 m_currentFileType = SsgHeader | PrivateHeader;
997
998 if (isHeaderSpi(m_currentFilename))
999 m_currentFileType = SpiHeader | PrivateHeader;
1000
1001 if (std::regex_match(m_currentFilename, ExportsHeaderRegex))
1002 m_currentFileType |= ExportHeader;
1003 }
1004
1005 [[nodiscard]] std::string currentFileOutputDir() const
1006 {
1007 if (m_currentFileType & QpaHeader)
1008 return m_commandLineArgs->qpaIncludeDir();
1009 if (m_currentFileType & RhiHeader)
1010 return m_commandLineArgs->rhiIncludeDir();
1011 if (m_currentFileType & SsgHeader)
1012 return m_commandLineArgs->ssgIncludeDir();
1013 if (m_currentFileType & SpiHeader)
1014 return m_commandLineArgs->spiIncludeDir();
1015 if (m_currentFileType & PrivateHeader)
1016 return m_commandLineArgs->privateIncludeDir();
1017 return m_commandLineArgs->includeDir();
1018 }
1019
1020 [[nodiscard]] std::string currentFileIncludePath() const
1021 {
1022 std::string includePath = m_commandLineArgs->moduleName() + '/';
1023 const std::string outputDir = currentFileOutputDir();
1024 if (outputDir != m_commandLineArgs->includeDir())
1025 includePath += std::filesystem::path(outputDir).filename().generic_string() + '/';
1026 return includePath + m_currentFilename;
1027 }
1028
1029 [[nodiscard]] bool processHeader(const std::filesystem::path &headerFile)
1030 {
1031 // This regex filters any paths that contain the '3rdparty' directory.
1032 static const std::regex ThirdPartyFolderRegex("(^|.+/)3rdparty/.+");
1033
1034 // This regex filters '-config.h' and '-config_p.h' header files.
1035 static const std::regex ConfigHeaderRegex("^(q|.+-)config(_p)?\\.h");
1036
1038
1039 bool isPrivate = m_currentFileType & PrivateHeader;
1040 bool isQpa = m_currentFileType & QpaHeader;
1041 bool isRhi = m_currentFileType & RhiHeader;
1042 bool isSsg = m_currentFileType & SsgHeader;
1043 bool isSpi = m_currentFileType & SpiHeader;
1044 bool isExport = m_currentFileType & ExportHeader;
1045 bool isPublic = !isPrivate && !isQpa && !isRhi && !isSsg && !isSpi;
1046
1047 // We assume that header files ouside of the module source or build directories do not
1048 // belong to the module. Skip any processing.
1049 if (!m_currentFileInSourceDir
1050 && m_currentFileString.find(m_commandLineArgs->binaryDir()) != 0) {
1051 scannerDebug() << "Header file: " << headerFile
1052 << " is outside the sync directories. Skipping." << std::endl;
1053 m_headerCheckExceptions.push_back(m_currentFileString);
1054
1055 // For some reason we don't treat the export header or Depends header as
1056 // "belonging to the module", as per the comment above. Yet we do need it
1057 // in the module map if it's in the include dir.
1058 // And we need to create a forwarding header in the install include dir for
1059 // framework builds.
1060 if (m_currentFileString.find(m_commandLineArgs->includeDir()) == 0) {
1061 m_moduleMapContents.insert({m_currentFileString, {}});
1062
1063 if (m_commandLineArgs->isFramework() && isPublic)
1064 m_publicHeaders.insert(m_currentFilename);
1065 }
1066
1067 return true;
1068 }
1069
1070 // Check if a directory is passed as argument. That shouldn't happen, print error and exit.
1071 if (m_currentFilename.empty()) {
1072 std::cerr << "Header file name of " << m_currentFileString << "is empty" << std::endl;
1073 return false;
1074 }
1075
1076 std::error_code ec;
1077 FileStamp originalStamp = std::filesystem::last_write_time(headerFile, ec);
1078 if (ec)
1079 originalStamp = FileStamp::clock::now();
1080 ec.clear();
1081
1082 scannerDebug()
1083 << "processHeader:start: " << headerFile
1084 << " m_currentFilename: " << m_currentFilename
1085 << " isPrivate: " << isPrivate
1086 << " isQpa: " << isQpa
1087 << " isRhi: " << isRhi
1088 << " isSsg: " << isSsg
1089 << " isSpi: " << isSpi
1090 << " isExport: " << isExport
1091 << std::endl;
1092
1093 // Chose the directory where to generate the header aliases or to copy header file if
1094 // the '-copy' argument is passed.
1095 const std::string outputDir = currentFileOutputDir();
1096 if (!utils::createDirectories(outputDir, "Unable to create output directory"))
1097 return false;
1098
1099 bool headerFileExists = std::filesystem::exists(headerFile);
1100
1101 std::string aliasedFilepath = headerFile.generic_string();
1102
1103 std::string aliasPath = outputDir + '/' + m_currentFilename;
1104
1105 // If the '-copy' argument is passed, we copy the original file to a corresponding output
1106 // directory otherwise we only create a header file alias that contains relative path to
1107 // the original header file in the module source or build tree.
1108 if (m_commandLineArgs->copy() && headerFileExists) {
1109 if (!updateOrCopy(headerFile, aliasPath))
1110 return false;
1111 } else {
1112 if (!generateAliasedHeaderFileIfTimestampChanged(aliasPath, aliasedFilepath,
1113 originalStamp))
1114 return false;
1115 }
1116
1117 // Remember the public headers so that, for framework builds, we can generate
1118 // forwarding headers that re-expose them via a plain (non-framework) include path
1119 // alongside the framework (see generateForwardingHeader).
1120 if (isPublic)
1121 m_publicHeaders.insert(m_currentFilename);
1122
1123 // No further processing in minimal mode.
1124 if (m_commandLineArgs->minimal())
1125 return true;
1126
1127 // Stop processing if header files doesn't exist. This happens at configure time, since
1128 // either header files are generated later than syncqt is running or header files only
1129 // generated at build time. These files will be processed at build time, if CMake files
1130 // contain the correct dependencies between the missing header files and the module
1131 // 'sync_headers' targets.
1132 if (!headerFileExists) {
1133 scannerDebug() << "Header file: " << headerFile
1134 << " doesn't exist, but is added to syncqt scanning. Skipping.";
1135 return true;
1136 }
1137
1138 bool isGenerated = isHeaderGenerated(m_currentFileString);
1139
1140 // Make sure that we detect the '3rdparty' directory inside the source directory only,
1141 // since full path to the Qt sources might contain '/3rdparty/' too.
1142 bool is3rdParty = std::regex_match(
1143 std::filesystem::relative(headerFile, m_commandLineArgs->sourceDir())
1144 .generic_string(),
1145 ThirdPartyFolderRegex);
1146
1147 // No processing of generated Qt config header files.
1148 if (!std::regex_match(m_currentFilename, ConfigHeaderRegex)) {
1149 unsigned int skipChecks = m_commandLineArgs->scanAllMode() ? AllChecks : NoChecks;
1150
1151 // Collect checks that should skipped for the header file.
1152 if (m_commandLineArgs->isNonQtModule() || is3rdParty || isQpa || isRhi || isSsg
1153 || isSpi || !m_currentFileInSourceDir || isGenerated) {
1154 skipChecks = AllChecks;
1155 } else {
1156 if (std::regex_match(m_currentFilename, GlobalHeaderRegex) || isExport)
1157 skipChecks |= NamespaceChecks;
1158
1159 if (isHeaderPCH(m_currentFilename))
1160 skipChecks |= WeMeantItChecks;
1161
1162 if (isPrivate) {
1163 skipChecks |= NamespaceChecks;
1164 skipChecks |= PrivateHeaderChecks;
1165 skipChecks |= IncludeChecks;
1166 } else {
1167 skipChecks |= WeMeantItChecks;
1168 }
1169 }
1170
1171 ParsingResult parsingResult;
1172 parsingResult.masterInclude = m_currentFileInSourceDir && !isExport && !is3rdParty
1173 && isPublic && !isGenerated;
1174 if (!parseHeader(headerFile, parsingResult, skipChecks)) {
1175 scannerDebug() << "parseHeader failed: " << headerFile << std::endl;
1176 return false;
1177 }
1178
1179 // Record the private header file inside the version script content.
1180 if (isPrivate && !m_commandLineArgs->versionScriptFile().empty()
1181 && !parsingResult.versionScriptContent.empty()) {
1182 m_versionScriptContents.insert(m_versionScriptContents.end(),
1183 parsingResult.versionScriptContent.begin(),
1184 parsingResult.versionScriptContent.end());
1185 }
1186
1187 // Add the '#if QT_CONFIG(<feature>)' check for header files that supposed to be
1188 // included into the module master header only if corresponding feature is enabled.
1189 bool willBeInModuleMasterHeader = false;
1190 if (isPublic) {
1191 if (m_currentFilename.find('_') == std::string::npos
1192 && parsingResult.masterInclude) {
1193 m_masterHeaderContents[m_currentFilename] = parsingResult.requireConfig;
1194 willBeInModuleMasterHeader = true;
1195 }
1196 }
1197
1198 scannerDebug()
1199 << "processHeader:end: " << headerFile
1200 << " is3rdParty: " << is3rdParty
1201 << " isGenerated: " << isGenerated
1202 << " m_currentFileInSourceDir: " << m_currentFileInSourceDir
1203 << " willBeInModuleMasterHeader: " << willBeInModuleMasterHeader
1204 << std::endl;
1205 } else if (m_currentFilename == "qconfig.h") {
1206 // Hardcode generating of QtConfig alias
1207 updateSymbolDescriptor("QtConfig", "qconfig.h", SyncScanner::SymbolDescriptor::Pragma);
1208 }
1209
1210 m_moduleMapContents.insert({outputDir + "/" + m_currentFilename, {}});
1211
1212 return true;
1213 }
1214
1215 void parseVersionScriptContent(const std::string buffer, ParsingResult &result)
1216 {
1217 // This regex looks for the symbols that needs to be placed into linker version script.
1218 static const std::regex VersionScriptSymbolRegex(
1219 "^(?:struct|class)(?:\\s+Q_\\w*_EXPORT)?\\s+([\\w:]+)[^;]*(;$)?");
1220
1221 // This regex looks for the namespaces that needs to be placed into linker version script.
1222 static const std::regex VersionScriptNamespaceRegex(
1223 "^namespace\\s+Q_\\w+_EXPORT\\s+([\\w:]+).*");
1224
1225 // This regex filters the tailing colon from the symbol name.
1226 static const std::regex TrailingColonRegex("([\\w]+):$");
1227
1228 switch (m_versionScriptGeneratorState) {
1229 case Ignore:
1230 scannerDebug() << "line ignored: " << buffer << std::endl;
1231 m_versionScriptGeneratorState = Active;
1232 return;
1233 case Stopped:
1234 return;
1235 case IgnoreNext:
1236 m_versionScriptGeneratorState = Ignore;
1237 break;
1238 case Active:
1239 break;
1240 }
1241
1242 if (buffer.empty())
1243 return;
1244
1245 std::smatch match;
1246 std::string symbol;
1247 if (std::regex_match(buffer, match, VersionScriptSymbolRegex) && match[2].str().empty())
1248 symbol = match[1].str();
1249 else if (std::regex_match(buffer, match, VersionScriptNamespaceRegex))
1250 symbol = match[1].str();
1251
1252 if (std::regex_match(symbol, match, TrailingColonRegex))
1253 symbol = match[1].str();
1254
1255 // checkLineForSymbols(buffer, symbol);
1256 if (!symbol.empty() && symbol[symbol.size() - 1] != ';') {
1257 std::string relPath = m_currentFileInSourceDir
1258 ? std::filesystem::relative(m_currentFile, m_commandLineArgs->sourceDir())
1259 .string()
1260 : std::filesystem::relative(m_currentFile, m_commandLineArgs->binaryDir())
1261 .string();
1262
1263 std::string versionStringRecord = " *";
1264 size_t startPos = 0;
1265 size_t endPos = 0;
1266 while (endPos != std::string::npos) {
1267 endPos = symbol.find("::", startPos);
1268 size_t length = endPos != std::string::npos ? (endPos - startPos)
1269 : (symbol.size() - startPos);
1270 if (length > 0) {
1271 std::string symbolPart = symbol.substr(startPos, length);
1272 versionStringRecord += std::to_string(symbolPart.size());
1273 versionStringRecord += symbolPart;
1274 }
1275 startPos = endPos + 2;
1276 }
1277 versionStringRecord += "*;";
1278 if (versionStringRecord.size() < LinkerScriptCommentAlignment)
1279 versionStringRecord +=
1280 std::string(LinkerScriptCommentAlignment - versionStringRecord.size(), ' ');
1281 versionStringRecord += " # ";
1282 versionStringRecord += relPath;
1283 versionStringRecord += ":";
1284 versionStringRecord += std::to_string(m_currentFileLineNumber);
1285 versionStringRecord += "\n";
1286 result.versionScriptContent.push_back(versionStringRecord);
1287 }
1288 }
1289
1290 // The function parses 'headerFile' and collect artifacts that are used at generating step.
1291 // 'timeStamp' is saved in internal structures to compare it when generating files.
1292 // 'result' the function output value that stores the result of parsing.
1293 // 'skipChecks' checks that are not applicable for the header file.
1294 [[nodiscard]] bool parseHeader(const std::filesystem::path &headerFile,
1295 ParsingResult &result,
1296 unsigned int skipChecks)
1297 {
1298 if (m_commandLineArgs->showOnly())
1299 std::cout << headerFile << " [" << m_commandLineArgs->moduleName() << "]" << std::endl;
1300 // This regex checks if line contains a macro.
1301 static const std::regex MacroRegex("^\\s*#.*");
1302
1303 // The regex's bellow check line for known pragmas:
1304 //
1305 // - 'once' is not allowed in installed headers, so error out.
1306 //
1307 // - 'qt_sync_skip_header_check' avoid any header checks.
1308 //
1309 // - 'qt_sync_stop_processing' stops the header proccesing from a moment when pragma is
1310 // found. Important note: All the parsing artifacts were found before this point are
1311 // stored for further processing.
1312 //
1313 // - 'qt_sync_suspend_processing' pauses processing and skip lines inside a header until
1314 // 'qt_sync_resume_processing' is found. 'qt_sync_stop_processing' stops processing if
1315 // it's found before the 'qt_sync_resume_processing'.
1316 //
1317 // - 'qt_sync_resume_processing' resumes processing after 'qt_sync_suspend_processing'.
1318 //
1319 // - 'qt_class(<symbol>)' manually declares the 'symbol' that should be used to generate
1320 // the CaMeL case header alias.
1321 //
1322 // - 'qt_deprecates([module/]<deprecated header file>[,<major.minor>])' indicates that
1323 // this header file replaces the 'deprecated header file'. syncqt will create the
1324 // deprecated header file' with the special deprecation content. Pragma optionally
1325 // accepts the Qt version where file should be removed. If the current Qt version is
1326 // higher than the deprecation version, syncqt displays deprecation warning and skips
1327 // generating the deprecated header. If the module is specified and is different from
1328 // the one this header file belongs to, syncqt attempts to generate header files
1329 // for the specified module. Cross-module deprecation only works within the same repo.
1330 // See the 'generateDeprecatedHeaders' function for details.
1331 //
1332 // - 'qt_no_master_include' indicates that syncqt should avoid including this header
1333 // files into the module master header file.
1334 static const std::regex OnceRegex(R"(^#\s*pragma\s+once$)");
1335 static const std::regex SkipHeaderCheckRegex("^#\\s*pragma qt_sync_skip_header_check$");
1336 static const std::regex StopProcessingRegex("^#\\s*pragma qt_sync_stop_processing$");
1337 static const std::regex SuspendProcessingRegex("^#\\s*pragma qt_sync_suspend_processing$");
1338 static const std::regex ResumeProcessingRegex("^#\\s*pragma qt_sync_resume_processing$");
1339 static const std::regex ExplixitClassPragmaRegex("^#\\s*pragma qt_class\\‍(([^\\‍)]+)\\‍)$");
1340 static const std::regex DeprecatesPragmaRegex("^#\\s*pragma qt_deprecates\\‍(([^\\‍)]+)\\‍)$");
1341 static const std::regex NoMasterIncludePragmaRegex("^#\\s*pragma qt_no_master_include$");
1342
1343 // This regex checks if header contains 'We mean it' disclaimer. All private headers should
1344 // contain them.
1345 static const std::string_view WeMeantItString("We mean it.");
1346
1347 // The regex's check if the content of header files is wrapped with the Qt namespace macros.
1348 static const std::regex BeginNamespaceRegex("^QT_BEGIN_NAMESPACE(_[A-Z_]+)?$");
1349 static const std::regex EndNamespaceRegex("^QT_END_NAMESPACE(_[A-Z_]+)?$");
1350
1351 // This regex checks if line contains the include macro of the following formats:
1352 // - #include <file>
1353 // - #include "file"
1354 // - # include <file>
1355 static const std::regex IncludeRegex("^#\\s*include\\s*[<\"](.+)[>\"]");
1356
1357 // This regex checks if line contains namespace definition.
1358 static const std::regex NamespaceRegex("\\s*namespace ([^ ]*)\\s+");
1359
1360 // This regex checks if line contains the Qt iterator declaration, that need to have
1361 // CaMel case header alias.
1362 static const std::regex DeclareIteratorRegex("^ *Q_DECLARE_\\w*ITERATOR\\‍((\\w+)\\‍);?$");
1363
1364 // This regex checks if header file contains the QT_REQUIRE_CONFIG call.
1365 // The macro argument is used to wrap an include of the header file inside the module master
1366 // header file with the '#if QT_CONFIG(<feature>)' guard.
1367 static const std::regex RequireConfigRegex("^ *QT_REQUIRE_CONFIG\\‍((\\w+)\\‍);?$");
1368
1369 // This regex looks for the ELFVERSION tag this is control key-word for the version script
1370 // content processing.
1371 // ELFVERSION tag accepts the following values:
1372 // - stop - stops the symbols lookup for a version script starting from this line.
1373 // - ignore-next - ignores the line followed by the current one.
1374 // - ignore - ignores the current line.
1375 static const std::regex ElfVersionTagRegex(".*ELFVERSION:(stop|ignore-next|ignore).*");
1376
1377 std::ifstream input(headerFile, std::ifstream::in);
1378 if (!input.is_open()) {
1379 std::cerr << "Unable to open " << headerFile << std::endl;
1380 return false;
1381 }
1382
1383 bool hasQtBeginNamespace = false;
1384 std::string qtBeginNamespace;
1385 std::string qtEndNamespace;
1386 bool hasWeMeantIt = false;
1387 bool isSuspended = false;
1388 bool isMultiLineComment = false;
1389 std::size_t bracesDepth = 0;
1390 std::size_t namespaceCount = 0;
1391 std::string namespaceString;
1392
1393 std::smatch match;
1394
1395 std::string buffer;
1396 std::string line;
1397 std::string tmpLine;
1398 std::size_t linesProcessed = 0;
1399 int faults = NoChecks;
1400
1401 const auto error = [&] () -> decltype(auto) {
1402 return std::cerr << ErrorMessagePreamble << m_currentFileString
1403 << ":" << m_currentFileLineNumber << " ";
1404 };
1405
1406 // Read file line by line
1407 while (std::getline(input, tmpLine)) {
1408 ++m_currentFileLineNumber;
1409 line.append(tmpLine);
1410 if (line.empty() || line.at(line.size() - 1) == '\\') {
1411 continue;
1412 }
1413 buffer.clear();
1414 buffer.reserve(line.size());
1415 // Optimize processing by looking for a special sequences such as:
1416 // - start-end of comments
1417 // - start-end of class/structures
1418 // And avoid processing of the the data inside these blocks.
1419 for (std::size_t i = 0; i < line.size(); ++i) {
1420 if (line[i] == '\r')
1421 continue;
1422 if (bracesDepth == namespaceCount) {
1423 if (line[i] == '/') {
1424 if ((i + 1) < line.size()) {
1425 if (line[i + 1] == '*') {
1426 isMultiLineComment = true;
1427 continue;
1428 } else if (line[i + 1] == '/') { // Single line comment
1429 if (!(skipChecks & WeMeantItChecks)
1430 && line.find(WeMeantItString) != std::string::npos) {
1431 hasWeMeantIt = true;
1432 continue;
1433 }
1434 if (m_versionScriptGeneratorState != Stopped
1435 && std::regex_match(line, match, ElfVersionTagRegex)) {
1436 if (match[1].str() == "ignore")
1437 m_versionScriptGeneratorState = Ignore;
1438 else if (match[1].str() == "ignore-next")
1439 m_versionScriptGeneratorState = IgnoreNext;
1440 else if (match[1].str() == "stop")
1441 m_versionScriptGeneratorState = Stopped;
1442 }
1443 break;
1444 }
1445 }
1446 } else if (line[i] == '*' && (i + 1) < line.size() && line[i + 1] == '/') {
1447 ++i;
1448 isMultiLineComment = false;
1449 continue;
1450 }
1451 }
1452
1453 if (isMultiLineComment) {
1454 if (!(skipChecks & WeMeantItChecks) &&
1455 line.find(WeMeantItString) != std::string::npos) {
1456 hasWeMeantIt = true;
1457 continue;
1458 }
1459 continue;
1460 }
1461
1462 if (line[i] == '{') {
1463 if (std::regex_match(buffer, match, NamespaceRegex)) {
1464 ++namespaceCount;
1465 namespaceString += "::";
1466 namespaceString += match[1].str();
1467 }
1468 ++bracesDepth;
1469 continue;
1470 } else if (line[i] == '}') {
1471 if (namespaceCount > 0 && bracesDepth == namespaceCount) {
1472 namespaceString.resize(namespaceString.rfind("::"));
1473 --namespaceCount;
1474 }
1475 --bracesDepth;
1476 } else if (bracesDepth == namespaceCount) {
1477 buffer += line[i];
1478 }
1479 }
1480 line.clear();
1481
1482 scannerDebug() << m_currentFilename << ": " << buffer << std::endl;
1483
1484 if (m_currentFileType & PrivateHeader) {
1485 parseVersionScriptContent(buffer, result);
1486 }
1487
1488 if (buffer.empty())
1489 continue;
1490
1491 ++linesProcessed;
1492
1493 bool skipSymbols =
1494 (m_currentFileType & PrivateHeader) || (m_currentFileType & QpaHeader) || (m_currentFileType & RhiHeader)
1495 || (m_currentFileType & SsgHeader) || (m_currentFileType & SpiHeader);
1496
1497 // Parse pragmas
1498 if (std::regex_match(buffer, MacroRegex)) {
1499 if (std::regex_match(buffer, SkipHeaderCheckRegex)) {
1500 skipChecks = AllChecks;
1501 faults = NoChecks;
1502 } else if (std::regex_match(buffer, StopProcessingRegex)) {
1503 if (skipChecks == AllChecks)
1504 m_headerCheckExceptions.push_back(m_currentFileString);
1505 return true;
1506 } else if (std::regex_match(buffer, SuspendProcessingRegex)) {
1507 isSuspended = true;
1508 } else if (std::regex_match(buffer, ResumeProcessingRegex)) {
1509 isSuspended = false;
1510 } else if (std::regex_match(buffer, match, ExplixitClassPragmaRegex)) {
1511 if (!skipSymbols) {
1512 updateSymbolDescriptor(match[1].str(), m_currentFilename,
1513 SymbolDescriptor::Pragma);
1514 } else {
1515 // TODO: warn about skipping symbols that are defined explicitly
1516 }
1517 } else if (std::regex_match(buffer, NoMasterIncludePragmaRegex)) {
1518 result.masterInclude = false;
1519 } else if (std::regex_match(buffer, match, DeprecatesPragmaRegex)) {
1520 m_deprecatedHeaders[match[1].str()] = currentFileIncludePath();
1521 } else if (std::regex_match(buffer, OnceRegex)) {
1522 if (!(skipChecks & PragmaOnceChecks)) {
1523 faults |= PragmaOnceChecks;
1524 error() << "\"#pragma once\" is not allowed in installed header files: "
1525 "https://lists.qt-project.org/pipermail/development/2022-October/043121.html"
1526 << std::endl;
1527 }
1528 } else if (std::regex_match(buffer, match, IncludeRegex) && !isSuspended) {
1529 if (!(skipChecks & IncludeChecks)) {
1530 std::string includedHeader = match[1].str();
1531 if (!(skipChecks & PrivateHeaderChecks)
1532 && isHeaderPrivate(std::filesystem::path(includedHeader)
1533 .filename()
1534 .generic_string())) {
1535 faults |= PrivateHeaderChecks;
1536 error() << "includes private header " << includedHeader << std::endl;
1537 }
1538 for (const auto &module : m_commandLineArgs->knownModules()) {
1539 std::string suggestedHeader = "Qt" + module + '/' + includedHeader;
1540 const std::string suggestedHeaderReversePath = "/../" + suggestedHeader;
1541 if (std::filesystem::exists(m_commandLineArgs->includeDir()
1542 + suggestedHeaderReversePath)
1543 || std::filesystem::exists(m_commandLineArgs->installIncludeDir()
1544 + '/' + suggestedHeader)) {
1545 faults |= IncludeChecks;
1546 std::cerr << m_warningMessagePreamble << m_currentFileString
1547 << ":" << m_currentFileLineNumber
1548 << " includes " << includedHeader
1549 << " when it should include "
1550 << suggestedHeader << std::endl;
1551 }
1552 }
1553 }
1554 }
1555 continue;
1556 }
1557
1558 // Logic below this line is affected by the 'qt_sync_suspend_processing' and
1559 // 'qt_sync_resume_processing' pragmas.
1560 if (isSuspended)
1561 continue;
1562
1563 // Look for the symbols in header file.
1564 if (!skipSymbols) {
1565 std::string symbol;
1566 if (checkLineForSymbols(buffer, symbol)) {
1567 if (namespaceCount == 0
1568 || std::regex_match(namespaceString,
1569 m_commandLineArgs->publicNamespaceRegex())) {
1570 updateSymbolDescriptor(symbol, m_currentFilename,
1571 SymbolDescriptor::Declaration);
1572 }
1573 continue;
1574 } else if (std::regex_match(buffer, match, DeclareIteratorRegex)) {
1575 std::string iteratorSymbol = match[1].str() + "Iterator";
1576 updateSymbolDescriptor(std::string("Q") + iteratorSymbol, m_currentFilename,
1577 SymbolDescriptor::Declaration);
1578 updateSymbolDescriptor(std::string("QMutable") + iteratorSymbol,
1579 m_currentFilename, SymbolDescriptor::Declaration);
1580 continue;
1581 } else if (std::regex_match(buffer, match, RequireConfigRegex)) {
1582 result.requireConfig = match[1].str();
1583 continue;
1584 }
1585 }
1586
1587 // Check for both QT_BEGIN_NAMESPACE and QT_END_NAMESPACE macros are present in the
1588 // header file.
1589 if (!(skipChecks & NamespaceChecks)) {
1590 if (std::regex_match(buffer, match, BeginNamespaceRegex)) {
1591 qtBeginNamespace = match[1].str();
1592 hasQtBeginNamespace = true;
1593 } else if (std::regex_match(buffer, match, EndNamespaceRegex)) {
1594 qtEndNamespace = match[1].str();
1595 }
1596 }
1597 }
1598 input.close();
1599
1600 // Error out if namespace checks are failed.
1601 if (!(skipChecks & NamespaceChecks)) {
1602 if (hasQtBeginNamespace) {
1603 if (qtBeginNamespace != qtEndNamespace) {
1604 faults |= NamespaceChecks;
1605 std::cerr << m_warningMessagePreamble << m_currentFileString
1606 << " the begin namespace macro QT_BEGIN_NAMESPACE" << qtBeginNamespace
1607 << " doesn't match the end namespace macro QT_END_NAMESPACE"
1608 << qtEndNamespace << std::endl;
1609 }
1610 } else {
1611 faults |= NamespaceChecks;
1612 std::cerr << m_warningMessagePreamble << m_currentFileString
1613 << " does not include QT_BEGIN_NAMESPACE" << std::endl;
1614 }
1615 }
1616
1617 if (!(skipChecks & WeMeantItChecks) && !hasWeMeantIt) {
1618 faults |= WeMeantItChecks;
1619 std::cerr << m_warningMessagePreamble << m_currentFileString
1620 << " does not have the \"We mean it.\" warning"
1621 << std::endl;
1622 }
1623
1624 scannerDebug() << "linesTotal: " << m_currentFileLineNumber
1625 << " linesProcessed: " << linesProcessed << std::endl;
1626
1627 if (skipChecks == AllChecks)
1628 m_headerCheckExceptions.push_back(m_currentFileString);
1629
1630 // Exit with an error if any of critical checks are present.
1631 return !(faults & m_criticalChecks);
1632 }
1633
1634 // The function checks if line contains the symbol that needs to have a CaMeL-style alias.
1635 [[nodiscard]] bool checkLineForSymbols(const std::string &line, std::string &symbol)
1636 {
1637 scannerDebug() << "checkLineForSymbols: " << line << std::endl;
1638
1639 // This regex checks if line contains class or structure declaration like:
1640 // - <class|stuct> StructName
1641 // - template <> class ClassName
1642 // - class ClassName : [public|protected|private] BaseClassName
1643 // - class ClassName [QT_TEXT_STREAM_FINAL|Q_DECL_FINAL|final|sealed]
1644 // And possible combinations of the above variants.
1645 static const std::regex ClassRegex(
1646 "^ *(template *<.*> *)?(class|struct +)([^<>:]*\\s+)?" // Preceding part
1647 "((?!Q[A-Z_0-9]*_FINAL|final|sealed)Q[a-zA-Z0-9_]+)" // Actual symbol
1648 "(\\s+Q[A-Z_0-9]*_FINAL|\\s+final|\\s+sealed)?\\s*(:|$).*"); // Trailing part
1649
1650 // This regex checks if line contains function pointer typedef declaration like:
1651 // - typedef void (* QFunctionPointerType)(int, char);
1652 static const std::regex FunctionPointerRegex(
1653 "^ *typedef *.*\\‍(\\*(Q[^\\‍)]+)\\‍)\\‍(.*\\‍); *");
1654
1655 // This regex checks if line contains class or structure typedef declaration like:
1656 // - typedef AnySymbol<char> QAnySymbolType;
1657 static const std::regex TypedefRegex("^ *typedef\\s+(.*)\\s+(Q\\w+); *$");
1658
1659 std::smatch match;
1660 if (std::regex_match(line, match, FunctionPointerRegex)) {
1661 symbol = match[1].str();
1662 } else if (std::regex_match(line, match, TypedefRegex)) {
1663 symbol = match[2].str();
1664 } else if (std::regex_match(line, match, ClassRegex)) {
1665 symbol = match[4].str();
1666 } else {
1667 return false;
1668 }
1669 return !symbol.empty();
1670 }
1671
1672 [[nodiscard]] bool isHeaderQpa(const std::string &headerFileName)
1673 {
1674 return std::regex_match(headerFileName, m_commandLineArgs->qpaHeadersRegex());
1675 }
1676
1677 [[nodiscard]] bool isHeaderRhi(const std::string &headerFileName)
1678 {
1679 return std::regex_match(headerFileName, m_commandLineArgs->rhiHeadersRegex());
1680 }
1681
1682 [[nodiscard]] bool isHeaderSsg(const std::string &headerFileName)
1683 {
1684 return std::regex_match(headerFileName, m_commandLineArgs->ssgHeadersRegex());
1685 }
1686
1687 [[nodiscard]] bool isHeaderSpi(const std::string &headerFileName)
1688 {
1689 return std::regex_match(headerFileName, m_commandLineArgs->spiHeadersRegex());
1690 }
1691
1692 [[nodiscard]] bool isHeaderPrivate(const std::string &headerFile)
1693 {
1694 return std::regex_match(headerFile, m_commandLineArgs->privateHeadersRegex());
1695 }
1696
1697 [[nodiscard]] bool isHeaderPublic(const std::string &headerFileName)
1698 {
1699 return !isHeaderPrivate(headerFileName) && !isHeaderQpa(headerFileName)
1700 && !isHeaderRhi(headerFileName) && !isHeaderSsg(headerFileName)
1701 && !isHeaderSpi(headerFileName);
1702 }
1703
1704 [[nodiscard]] bool isHeaderPCH(const std::string &headerFilename)
1705 {
1706 static const std::string pchSuffix("_pch.h");
1707 return headerFilename.find(pchSuffix, headerFilename.size() - pchSuffix.size())
1708 != std::string::npos;
1709 }
1710
1711 [[nodiscard]] bool isHeaderImpl(const std::string &headerFilename) const
1712 {
1713 static const std::string implSuffix("_impl.h");
1714 return headerFilename.find(implSuffix, headerFilename.size() - implSuffix.size())
1715 != std::string::npos;
1716 }
1717
1718 [[nodiscard]] bool isHeaderDeprecated(const std::string &headerFilename) const
1719 {
1720 static const std::string deprecatedSuffix("_deprecated.h");
1721 return headerFilename.find(deprecatedSuffix,
1722 headerFilename.size() - deprecatedSuffix.size())
1723 != std::string::npos;
1724 }
1725
1726 [[nodiscard]] bool isHeader(const std::filesystem::path &path)
1727 {
1728 return path.extension().string() == ".h";
1729 }
1730
1731 [[nodiscard]] bool isDocFileHeuristic(const std::string &headerFilePath)
1732 {
1733 return headerFilePath.find("/doc/") != std::string::npos;
1734 }
1735
1736 [[nodiscard]] bool isHeaderGenerated(const std::string &header)
1737 {
1738 return m_commandLineArgs->generatedHeaders().find(header)
1739 != m_commandLineArgs->generatedHeaders().end();
1740 }
1741
1742 [[nodiscard]] bool generateForwardingHeader(const std::string &outputFilePath,
1743 const std::string &aliasedFilePath,
1744 bool frameworkForwarder = false);
1745
1747 const std::string &outputFilePath, const std::string &aliasedFilePath,
1748 const FileStamp &originalStamp = FileStamp::clock::now());
1749
1750 [[nodiscard]] bool generateModuleMapFile();
1751
1752 bool writeIfDifferent(const std::string &outputFile, const std::string &buffer) const;
1753
1754 [[nodiscard]] bool generateMasterHeader()
1755 {
1756 if (m_masterHeaderContents.empty())
1757 return true;
1758
1759 std::string outputFile =
1760 m_commandLineArgs->includeDir() + '/' + m_commandLineArgs->moduleName();
1761
1762 std::string moduleUpper = utils::asciiToUpper(m_commandLineArgs->moduleName());
1763 std::stringstream buffer;
1764 buffer << "#ifndef QT_" << moduleUpper << "_MODULE_H\n"
1765 << "#define QT_" << moduleUpper << "_MODULE_H\n"
1766 << "#include <" << m_commandLineArgs->moduleName() << "/"
1767 << m_commandLineArgs->moduleName() << "Depends>\n";
1768 for (const auto &headerContents : m_masterHeaderContents) {
1769 if (!headerContents.second.empty()) {
1770 buffer << "#if QT_CONFIG(" << headerContents.second << ")\n"
1771 << "#include <" << m_commandLineArgs->moduleName() << "/"
1772 << headerContents.first << ">\n"
1773 << "#endif\n";
1774 } else {
1775 buffer << "#include <" << m_commandLineArgs->moduleName() << "/"
1776 << headerContents.first << ">\n";
1777 }
1778 }
1779 buffer << "#endif\n";
1780
1781 m_producedHeaders.insert(m_commandLineArgs->moduleName());
1782 m_moduleMapContents.insert({outputFile, {}});
1783 m_masterHeaderBuffer = buffer.str();
1784 return writeIfDifferent(outputFile, m_masterHeaderBuffer);
1785 }
1786
1787 [[nodiscard]] bool generateVersionHeader(const std::string &outputFile)
1788 {
1789 std::string moduleNameUpper = utils::asciiToUpper( m_commandLineArgs->moduleName());
1790 std::string moduleVersion = m_commandLineArgs->moduleVersion();
1791 int majorVersion = m_commandLineArgs->moduleVersionMajor();
1792 int minorVersion = m_commandLineArgs->moduleVersionMinor();
1793 int patchVersion = m_commandLineArgs->moduleVersionPatch();
1794
1795 std::stringstream buffer;
1796 buffer << "/* This file was generated by syncqt. */\n"
1797 << "#ifndef QT_" << moduleNameUpper << "_VERSION_H\n"
1798 << "#define QT_" << moduleNameUpper << "_VERSION_H\n\n"
1799 << "#define " << moduleNameUpper << "_VERSION_STR \"" << moduleVersion << "\"\n\n"
1800 << "#define " << moduleNameUpper << "_VERSION "
1801 << "0x"
1802 << std::hex << std::setfill('0')
1803 << std::setw(2) << majorVersion
1804 << std::setw(2) << minorVersion
1805 << std::setw(2) << patchVersion
1806 << "\n\n"
1807 << "#endif // QT_" << moduleNameUpper << "_VERSION_H\n";
1808
1809 return writeIfDifferent(outputFile, buffer.str());
1810 }
1811
1812 [[nodiscard]] bool generateDeprecatedHeaders()
1813 {
1814 static std::regex cIdentifierSymbolsRegex("[^a-zA-Z0-9_]");
1815 const std::string guard_base = "DEPRECATED_HEADER_" + m_commandLineArgs->moduleName();
1816 bool result = true;
1817 for (auto it = m_deprecatedHeaders.begin(); it != m_deprecatedHeaders.end(); ++it) {
1818 const std::string &descriptor = it->first;
1819 const std::string &replacement = it->second;
1820
1821 const auto separatorPos = descriptor.find(',');
1822 std::string headerPath = descriptor.substr(0, separatorPos);
1823 std::string versionDisclaimer;
1824 if (separatorPos != std::string::npos) {
1825 std::string version = descriptor.substr(separatorPos + 1);
1826 versionDisclaimer = " and will be removed in Qt " + version;
1827 const utils::VersionParseResult parsed = utils::parseVersion(version);
1828 if (!parsed.ok() || parsed.count != 2) {
1829 std::cerr << ErrorMessagePreamble
1830 << "Invalid version format specified for the deprecated header file "
1831 << headerPath << ": '" << version
1832 << "'. Expected format: 'major.minor'.\n";
1833 result = false;
1834 continue;
1835 }
1836 const int major = parsed.parts[0];
1837 const int minor = parsed.parts[1];
1838
1839 if (QT_VERSION_MAJOR > major
1840 || (QT_VERSION_MAJOR == major && QT_VERSION_MINOR >= minor)) {
1841 std::cerr << WarningMessagePreamble << headerPath
1842 << " is marked as deprecated and will not be generated in Qt "
1843 << QT_VERSION_STR
1844 << ". The respective qt_deprecates pragma needs to be removed.\n";
1845 continue;
1846 }
1847 }
1848
1849 const auto moduleSeparatorPos = headerPath.find('/');
1850 std::string headerName = moduleSeparatorPos != std::string::npos
1851 ? headerPath.substr(moduleSeparatorPos + 1)
1852 : headerPath;
1853 const std::string moduleName = moduleSeparatorPos != std::string::npos
1854 ? headerPath.substr(0, moduleSeparatorPos)
1855 : m_commandLineArgs->moduleName();
1856
1857 if (!isHeaderPublic(headerName)) {
1858 std::cerr << ErrorMessagePreamble << "Unable to deprecate " << headerPath
1859 << ": only public header files can be deprecated.\n";
1860 result = false;
1861 continue;
1862 }
1863
1864 bool isCrossModuleDeprecation = moduleName != m_commandLineArgs->moduleName();
1865
1866 std::string qualifiedHeaderName =
1867 std::regex_replace(headerName, cIdentifierSymbolsRegex, "_");
1868 std::string guard = guard_base + "_" + qualifiedHeaderName;
1869 std::string warningText = "Header <" + moduleName + "/" + headerName + "> is deprecated"
1870 + versionDisclaimer + ". Please include <" + replacement + "> instead.";
1871 std::stringstream buffer;
1872 buffer << "#ifndef " << guard << "\n"
1873 << "#define " << guard << "\n"
1874 << "#if defined(__GNUC__)\n"
1875 << "# warning " << warningText << "\n"
1876 << "#elif defined(_MSC_VER)\n"
1877 << "# pragma message (\"" << warningText << "\")\n"
1878 << "#endif\n"
1879 << "#include <" << replacement << ">\n"
1880 << "#endif\n";
1881
1882 const std::string outputDir = isCrossModuleDeprecation
1883 ? m_commandLineArgs->includeDir() + "/../" + moduleName
1884 : m_commandLineArgs->includeDir();
1885 writeIfDifferent(outputDir + '/' + headerName, buffer.str());
1886
1887 // Add header file to staging installation directory for cross-module deprecation case.
1888 if (isCrossModuleDeprecation) {
1889 const std::string stagingDir = outputDir + "/.syncqt_staging/";
1890 writeIfDifferent(stagingDir + headerName, buffer.str());
1891 }
1892 m_producedHeaders.insert(headerName);
1893 }
1894 return result;
1895 }
1896
1898 {
1899 std::stringstream buffer;
1900 for (const auto &header : m_headerCheckExceptions)
1901 buffer << header << ";";
1902 return writeIfDifferent(m_commandLineArgs->binaryDir() + '/'
1903 + m_commandLineArgs->moduleName()
1904 + "_header_check_exceptions",
1905 buffer.str());
1906 }
1907
1908 [[nodiscard]] bool generateLinkerVersionScript()
1909 {
1910 std::stringstream buffer;
1911 for (const auto &content : m_versionScriptContents)
1912 buffer << content;
1913 return writeIfDifferent(m_commandLineArgs->versionScriptFile(), buffer.str());
1914 }
1915
1916 bool updateOrCopy(const std::filesystem::path &src, const std::filesystem::path &dst) noexcept;
1917 void updateSymbolDescriptor(const std::string &symbol, const std::string &file,
1918 SymbolDescriptor::SourceType type);
1919};
1920
1921// The function updates information about the symbol:
1922// - The path and modification time of the file where the symbol was found.
1923// - The source of finding
1924// Also displays a short info about a symbol in show only mode.
1925void SyncScanner::updateSymbolDescriptor(const std::string &symbol, const std::string &file,
1926 SymbolDescriptor::SourceType type)
1927{
1928 if (m_commandLineArgs->showOnly() || m_commandLineArgs->debug())
1929 std::cout << " SYMBOL: " << symbol << std::endl;
1930 m_symbols[symbol].update(file, type);
1931}
1932
1933[[nodiscard]] std::filesystem::path
1934SyncScanner::makeHeaderAbsolute(const std::string &filename) const
1935{
1936 if (std::filesystem::path(filename).is_relative())
1937 return utils::normalizedPath(m_commandLineArgs->sourceDir() + '/' + filename);
1938
1939 return utils::normalizedPath(filename);
1940}
1941
1942bool SyncScanner::updateOrCopy(const std::filesystem::path &src,
1943 const std::filesystem::path &dst) noexcept
1944{
1945 if (m_commandLineArgs->showOnly())
1946 return true;
1947
1948 if (src == dst) {
1949 std::cout << "Source and destination paths are same when copying " << src.string()
1950 << ". Skipping." << std::endl;
1951 return true;
1952 }
1953
1954 std::error_code ec;
1955 std::filesystem::copy(src, dst, std::filesystem::copy_options::update_existing, ec);
1956 if (ec) {
1957 ec.clear();
1958 std::filesystem::remove(dst, ec);
1959 if (ec) {
1960 // On some file systems(e.g. vboxfs) the std::filesystem::copy doesn't support
1961 // std::filesystem::copy_options::overwrite_existing remove file first and then copy.
1962 std::cerr << "Unable to remove file: " << src << " to " << dst << " error: ("
1963 << ec.value() << ")" << ec.message() << std::endl;
1964 return false;
1965 }
1966
1967 std::filesystem::copy(src, dst, std::filesystem::copy_options::overwrite_existing, ec);
1968 if (ec) {
1969 std::cerr << "Unable to copy file: " << src << " to " << dst << " error: ("
1970 << ec.value() << ")" << ec.message() << std::endl;
1971 return false;
1972 }
1973 }
1974 return true;
1975}
1976
1977// The function generates a forwarding header at outputFilePath that includes aliasedFilePath
1978// from the current module (that is, <Module/aliasedFilePath>).
1979bool SyncScanner::generateForwardingHeader(const std::string &outputFilePath,
1980 const std::string &aliasedFilePath,
1981 bool frameworkForwarder)
1982{
1983 if (m_commandLineArgs->showOnly())
1984 return true;
1985
1986 // Safety check: aliasedFilePath should not be empty
1987 if (aliasedFilePath.empty()) {
1988 std::cerr << "ERROR: Empty aliasedFilePath for " << outputFilePath << std::endl;
1989 return false;
1990 }
1991
1992 const std::string include = "<"
1993 + m_commandLineArgs->moduleName() + "/" + aliasedFilePath
1994 + ">";
1995
1996 std::string buffer;
1997 if (frameworkForwarder) {
1998 // We're forwarding from include/QtFoo/qfoo.h into the framework,
1999 // based on someone including <qfoo.h>. But we can't guarantee that
2000 // the framework path comes after the forwarding-path in the build
2001 // flags, nor its relation to a possible naked Qt include/ path in
2002 // the build flags. So we play it safe, and try to first include the
2003 // framework header via the remaining include paths, and otherwise
2004 // restart the header lookup from the start of the include paths.
2005 buffer += "#if __has_include_next(" + include + ")\n";
2006 buffer += "# include_next " + include + " // IWYU pragma: export\n";
2007 buffer += "#else\n";
2008 buffer += "# include " + include + " // IWYU pragma: export\n";
2009 buffer += "#endif\n";
2010 } else {
2011 buffer += "#include " + include + " // IWYU pragma: export\n";
2012 }
2013
2014 return writeIfDifferent(outputFilePath, buffer);
2015}
2016
2017// The function generates aliases for files in source tree. Since the content of these aliases is
2018// always same, it's ok to check only timestamp and touch files in case if stamp of original is
2019// newer than the timestamp of an alias.
2021 const std::string &aliasedFilePath,
2022 const FileStamp &originalStamp)
2023{
2024 if (m_commandLineArgs->showOnly())
2025 return true;
2026
2027 std::filesystem::path aliased(aliasedFilePath);
2028 std::filesystem::path includeDir(m_commandLineArgs->includeDir());
2029
2030 // Check if paths have the same root (drive on Windows).
2031 // If they don't, the alias cannot be inside includeDir, so use absolute path.
2032 bool sameRoot = !aliased.is_absolute() || includeDir.root_name() == aliased.root_name();
2033
2034 auto relativePath = sameRoot ? std::filesystem::relative(aliased, includeDir).generic_string()
2035 : std::string();
2036 bool aliasIsInsideIncludeDir = sameRoot && relativePath.find("../") != 0;
2037
2038 if (std::filesystem::exists({ outputFilePath })
2039 && std::filesystem::last_write_time({ outputFilePath }) >= originalStamp) {
2040 return true;
2041 }
2042 scannerDebug() << "Rewrite " << outputFilePath << std::endl;
2043
2044 std::ofstream ofs;
2045 ofs.open(outputFilePath, std::ofstream::out | std::ofstream::trunc);
2046 if (!ofs.is_open()) {
2047 std::cerr << "Unable to write header file alias: " << outputFilePath << std::endl;
2048 return false;
2049 }
2050
2051 ofs << "#include ";
2052 if (aliasIsInsideIncludeDir)
2053 ofs << "<" << m_commandLineArgs->moduleName() + "/" << relativePath << ">";
2054 else
2055 ofs << "\"" << aliasedFilePath << "\"";
2056 ofs << " // IWYU pragma: export\n";
2057 ofs.close();
2058 return true;
2059}
2060
2062{
2063 std::string content;
2064 for (const auto& [header, aliasHeader] : m_moduleMapContents) {
2065 auto relativePath = std::filesystem::relative(header, m_commandLineArgs->includeDir());
2066 const auto &nonCamelCaseHeader = aliasHeader.empty() ? header : aliasHeader;
2067 resetCurrentFileInfoData(nonCamelCaseHeader);
2068 const bool isPrivate = m_currentFileType & PrivateHeader;
2069 const bool isDeprecated =
2070 m_deprecatedHeaders.find(nonCamelCaseHeader) != m_deprecatedHeaders.end()
2071 || isHeaderDeprecated(nonCamelCaseHeader);
2072
2073 content += " ";
2074 if (isPrivate || isDeprecated)
2075 content += "exclude ";
2076 if (isHeaderImpl(header))
2077 content += "textual ";
2078
2079 content += "header \"";
2080 content += relativePath.string();
2081 content += "\"\n";
2082 }
2083
2084 std::filesystem::path moduleMapsTemplatePath =
2085 m_commandLineArgs->binaryDir() + "/" +
2086 m_commandLineArgs->moduleName() + "." + "module.modulemap.in";
2087 if (!std::filesystem::exists(moduleMapsTemplatePath)) {
2088 std::cerr << "Unable to read the modulemaps template file: " << moduleMapsTemplatePath
2089 << std::endl;
2090 return false;
2091 }
2092
2093 std::ifstream input(moduleMapsTemplatePath, std::ifstream::in);
2094 if (!input.is_open()) {
2095 std::cerr << "Unable to open " << moduleMapsTemplatePath << std::endl;
2096 return false;
2097 }
2098
2099 std::string output;
2100 std::string tmpLine;
2101 while (std::getline(input, tmpLine)) {
2102 if (tmpLine == "@SYNCQT_GENERATED_HEADER_LIST@") {
2103 output += content;
2104 } else {
2105 output += tmpLine;
2106 output += "\n";
2107 }
2108 }
2109
2110 std::string moduleMapsPath = m_commandLineArgs->moduleMapFile();
2111 return writeIfDifferent(moduleMapsPath, output);
2112}
2113
2114
2115bool SyncScanner::writeIfDifferent(const std::string &outputFile, const std::string &buffer) const
2116{
2117 if (m_commandLineArgs->showOnly())
2118 return true;
2119
2120 static const std::streamsize bufferSize = 1025;
2121 bool differs = false;
2122 std::filesystem::path outputFilePath(outputFile);
2123
2124 std::string outputDirectory = outputFilePath.parent_path().string();
2125
2126 if (!utils::createDirectories(outputDirectory, "Unable to create output directory"))
2127 return false;
2128
2129 auto expectedSize = buffer.size();
2130#ifdef _WINDOWS
2131 // File on disk has \r\n instead of just \n
2132 expectedSize += std::count(buffer.begin(), buffer.end(), '\n');
2133#endif
2134
2135 if (std::filesystem::exists(outputFilePath)
2136 && expectedSize == std::filesystem::file_size(outputFilePath)) {
2137 char rdBuffer[bufferSize];
2138 memset(rdBuffer, 0, bufferSize);
2139
2140 std::ifstream ifs(outputFile, std::fstream::in);
2141 if (!ifs.is_open()) {
2142 std::cerr << "Unable to open " << outputFile << " for comparison." << std::endl;
2143 return false;
2144 }
2145 std::streamsize currentPos = 0;
2146
2147 std::size_t bytesRead = 0;
2148 do {
2149 ifs.read(rdBuffer, bufferSize - 1); // Read by 1K
2150 bytesRead = ifs.gcount();
2151 if (buffer.compare(currentPos, bytesRead, rdBuffer) != 0) {
2152 differs = true;
2153 break;
2154 }
2155 currentPos += bytesRead;
2156 memset(rdBuffer, 0, bufferSize);
2157 } while (bytesRead > 0);
2158
2159 ifs.close();
2160 } else {
2161 differs = true;
2162 }
2163
2164 scannerDebug() << "Update: " << outputFile << " " << differs << std::endl;
2165 if (differs) {
2166 std::ofstream ofs;
2167 ofs.open(outputFilePath, std::fstream::out | std::ofstream::trunc);
2168 if (!ofs.is_open()) {
2169 std::cerr << "Unable to write header content to " << outputFilePath << std::endl;
2170 return false;
2171 }
2172 ofs << buffer;
2173
2174 ofs.close();
2175 }
2176 return true;
2177}
2178
2179int main(int argc, char *argv[])
2180{
2181 CommandLineOptions options(argc, argv);
2182 if (!options.isValid())
2183 return InvalidArguments;
2184
2185 if (options.printHelpOnly()) {
2186 options.printHelp();
2187 return NoError;
2188 }
2189
2190 SyncScanner scanner = SyncScanner(&options);
2191 return scanner.sync();
2192}
const std::string & rhiIncludeDir() const
Definition main.cpp:233
const std::string & moduleMapFile() const
Definition main.cpp:243
const std::string & privateIncludeDir() const
Definition main.cpp:229
const std::string & sourceDir() const
Definition main.cpp:221
const std::string & installIncludeDir() const
Definition main.cpp:227
bool copy() const
Definition main.cpp:273
const std::regex & spiHeadersRegex() const
Definition main.cpp:253
const std::string & binaryDir() const
Definition main.cpp:223
int moduleVersionPatch() const
Definition main.cpp:219
int moduleVersionMajor() const
Definition main.cpp:217
bool minimal() const
Definition main.cpp:275
const std::string & ssgIncludeDir() const
Definition main.cpp:235
const std::set< std::string > & generatedHeaders() const
Definition main.cpp:261
bool isValid() const
Definition main.cpp:212
const std::string & moduleName() const
Definition main.cpp:214
bool isInternal() const
Definition main.cpp:265
const std::string & versionScriptFile() const
Definition main.cpp:241
const std::regex & publicNamespaceRegex() const
Definition main.cpp:257
const std::string & stagingDir() const
Definition main.cpp:239
const std::string & qpaIncludeDir() const
Definition main.cpp:231
const std::set< std::string > & knownModules() const
Definition main.cpp:245
const std::string & includeDir() const
Definition main.cpp:225
bool isFramework() const
Definition main.cpp:279
bool isNonQtModule() const
Definition main.cpp:267
const std::string & moduleVersion() const
Definition main.cpp:216
bool debug() const
Definition main.cpp:271
const std::string & spiIncludeDir() const
Definition main.cpp:237
const std::regex & qpaHeadersRegex() const
Definition main.cpp:247
void printHelp() const
Definition main.cpp:283
CommandLineOptions(int argc, char *argv[])
Definition main.cpp:210
const std::regex & ssgHeadersRegex() const
Definition main.cpp:251
const std::regex & privateHeadersRegex() const
Definition main.cpp:255
bool scanAllMode() const
Definition main.cpp:263
bool printHelpOnly() const
Definition main.cpp:269
bool warningsAreErrors() const
Definition main.cpp:281
int moduleVersionMinor() const
Definition main.cpp:218
const std::regex & rhiHeadersRegex() const
Definition main.cpp:249
bool showOnly() const
Definition main.cpp:277
const std::set< std::string > & headers() const
Definition main.cpp:259
bool writeIfDifferent(const std::string &outputFile, const std::string &buffer) const
Definition main.cpp:2115
bool generateVersionHeader(const std::string &outputFile)
Definition main.cpp:1787
bool generateLinkerVersionScript()
Definition main.cpp:1908
std::string currentFileOutputDir() const
Definition main.cpp:1005
bool isHeaderQpa(const std::string &headerFileName)
Definition main.cpp:1672
void parseVersionScriptContent(const std::string buffer, ParsingResult &result)
Definition main.cpp:1215
bool updateOrCopy(const std::filesystem::path &src, const std::filesystem::path &dst) noexcept
Definition main.cpp:1942
bool checkLineForSymbols(const std::string &line, std::string &symbol)
Definition main.cpp:1635
bool isHeaderDeprecated(const std::string &headerFilename) const
Definition main.cpp:1718
std::string currentFileIncludePath() const
Definition main.cpp:1020
void updateSymbolDescriptor(const std::string &symbol, const std::string &file, SymbolDescriptor::SourceType type)
Definition main.cpp:1925
bool isHeaderSpi(const std::string &headerFileName)
Definition main.cpp:1687
bool isHeaderGenerated(const std::string &header)
Definition main.cpp:1736
std::filesystem::path makeHeaderAbsolute(const std::string &filename) const
Definition main.cpp:1934
bool generateModuleMapFile()
Definition main.cpp:2061
bool generateMasterHeader()
Definition main.cpp:1754
bool isHeaderImpl(const std::string &headerFilename) const
Definition main.cpp:1711
bool generateAliasedHeaderFileIfTimestampChanged(const std::string &outputFilePath, const std::string &aliasedFilePath, const FileStamp &originalStamp=FileStamp::clock::now())
Definition main.cpp:2020
ErrorCodes sync()
Definition main.cpp:750
bool isHeader(const std::filesystem::path &path)
Definition main.cpp:1726
bool generateDeprecatedHeaders()
Definition main.cpp:1812
bool copyGeneratedHeadersToStagingDirectory(const std::string &outputDirectory, bool skipCleanup=false)
Definition main.cpp:920
bool isHeaderPublic(const std::string &headerFileName)
Definition main.cpp:1697
bool isHeaderRhi(const std::string &headerFileName)
Definition main.cpp:1677
bool isHeaderSsg(const std::string &headerFileName)
Definition main.cpp:1682
bool generateForwardingHeader(const std::string &outputFilePath, const std::string &aliasedFilePath, bool frameworkForwarder=false)
Definition main.cpp:1979
bool parseHeader(const std::filesystem::path &headerFile, ParsingResult &result, unsigned int skipChecks)
Definition main.cpp:1294
bool isDocFileHeuristic(const std::string &headerFilePath)
Definition main.cpp:1731
bool isHeaderPCH(const std::string &headerFilename)
Definition main.cpp:1704
bool processHeader(const std::filesystem::path &headerFile)
Definition main.cpp:1029
SyncScanner(CommandLineOptions *commandLineArgs)
Definition main.cpp:735
bool generateHeaderCheckExceptions()
Definition main.cpp:1897
void resetCurrentFileInfoData(const std::filesystem::path &headerFile)
Definition main.cpp:974
bool isHeaderPrivate(const std::string &headerFile)
Definition main.cpp:1692
Definition main.cpp:81
VersionParseResult parseVersion(const std::string &version)
Definition main.cpp:107
std::string asciiToLower(std::string s)
Definition main.cpp:82
void printFilesystemError(const std::filesystem::filesystem_error &fserr, std::string_view errorMsg)
Definition main.cpp:153
void printInternalError()
Definition main.cpp:146
std::filesystem::path normalizedPath(const std::string &path)
Definition main.cpp:159
bool createDirectories(const std::string &path, std::string_view errorMsg, bool *exists=nullptr)
Definition main.cpp:170
std::string asciiToUpper(std::string s)
Definition main.cpp:89
static const std::regex GlobalHeaderRegex("^q(.*)global\\.h$")
HeaderChecks
Definition main.cpp:42
@ AllChecks
Definition main.cpp:51
@ NamespaceChecks
Definition main.cpp:44
@ PragmaOnceChecks
Definition main.cpp:48
@ NoChecks
Definition main.cpp:43
@ WeMeantItChecks
Definition main.cpp:47
@ CriticalChecks
Definition main.cpp:50
@ IncludeChecks
Definition main.cpp:46
@ PrivateHeaderChecks
Definition main.cpp:45
ErrorCodes
Definition main.cpp:35
@ SyncFailed
Definition main.cpp:38
@ InvalidArguments
Definition main.cpp:37
@ NoError
Definition main.cpp:36
constexpr std::string_view ErrorMessagePreamble
Definition main.cpp:58
constexpr int LinkerScriptCommentAlignment
Definition main.cpp:54
constexpr std::string_view WarningMessagePreamble
Definition main.cpp:59
bool MasterHeaderIncludeComparator(const std::string &a, const std::string &b)
Definition main.cpp:63
int main(int argc, char *argv[])
[ctor_close]
std::array< int, 3 > parts
Definition main.cpp:98