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) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
5#include "codemarker.h"
6#include "codeparser.h"
7#include "config.h"
9#include "doc.h"
11#include "htmlgenerator.h"
14#include "outputproducer.h"
15#include "location.h"
16#include "locationplan.h"
19#include "puredocparser.h"
20#include "qdocdatabase.h"
21#include "qmlcodemarker.h"
22#include "qmlcodeparser.h"
24#include "utilities.h"
25#ifdef QDOC_TEMPLATE_GENERATOR_ENABLED
26#include "templategenerator.h"
27#endif
28#include "tokenizer.h"
29#include "tree.h"
31
32#include "filesystem/fileresolver.h"
33#include "boundaries/filesystem/directorypath.h"
35
36#include <QtCore/qcompilerdetection.h>
37#include <QtCore/qdatetime.h>
38#include <QtCore/qdebug.h>
39#include <QtCore/qglobal.h>
40#include <QtCore/qhashfunctions.h>
41
42#include <set>
43
44#ifndef QT_BOOTSTRAPPED
45# include <QtCore/qcoreapplication.h>
46#endif
47
48#include <algorithm>
49#include <cstdlib>
50#include <memory>
51#include <vector>
52
54
55using namespace Qt::StringLiterals;
56
57bool creationTimeBefore(const QFileInfo &fi1, const QFileInfo &fi2)
58{
59 return fi1.lastModified() < fi2.lastModified();
60}
61
62/*!
63 \internal
64 Inspects each file path in \a sources. File paths with a known
65 source file type are parsed to extract user-provided
66 documentation and information about source code level elements.
67
68 \note Unknown source file types are silently ignored.
69
70 The validity or availability of the file paths may or may not cause QDoc
71 to generate warnings; this depends on the implementation of
72 parseSourceFile() for the relevant parser.
73
74 \sa CodeParser::parserForSourceFile, CodeParser::sourceFileNameFilter
75*/
76static void parseSourceFiles(
77 std::vector<QString>&& sources,
78 SourceFileParser& source_file_parser,
79 CppCodeParser& cpp_code_parser
80) {
81 ParserErrorHandler error_handler{};
82 std::stable_sort(sources.begin(), sources.end());
83
84 sources.erase (
85 std::unique(sources.begin(), sources.end()),
86 sources.end()
87 );
88
89 sources.erase(std::remove_if(sources.begin(), sources.end(),
90 [](const QString &source) {
91 return Utilities::isGeneratedFile(source);
92 }),
93 sources.end());
94
95 auto qml_sources =
96 std::stable_partition(sources.begin(), sources.end(), [](const QString& source){
97 return CodeParser::parserForSourceFile(source) == CodeParser::parserForLanguage("QML");
98 });
99
100
101 std::for_each(qml_sources, sources.end(),
102 [&source_file_parser, &cpp_code_parser, &error_handler](const QString& source){
103 qCDebug(lcQdoc, "Parsing %s", qPrintable(source));
104
105 auto [untied_documentation, tied_documentation] = source_file_parser(tag_source_file(source));
106 std::vector<FnMatchError> errors{};
107
108 for (const auto &untied : std::as_const(untied_documentation)) {
109 auto result = cpp_code_parser.processTopicArgs(untied);
110 tied_documentation.insert(tied_documentation.end(), result.first.begin(), result.first.end());
111 errors.insert(errors.end(), result.second.begin(), result.second.end());
112 };
113
114 cpp_code_parser.processMetaCommands(tied_documentation);
115
116 // Process errors that occurred during parsing
117 for (const auto &e : errors)
118 error_handler(e);
119 });
120
121 std::for_each(sources.begin(), qml_sources, [&cpp_code_parser](const QString& source){
122 auto *codeParser = CodeParser::parserForSourceFile(source);
123 if (!codeParser) return;
124
125 qCDebug(lcQdoc, "Parsing %s", qPrintable(source));
126 codeParser->parseSourceFile(Config::instance().location(), source, cpp_code_parser);
127 });
128
129}
130
131/*!
132 Read some XML indexes containing definitions from other
133 documentation sets. \a config contains a variable that
134 lists directories where index files can be found. It also
135 contains the \c depends variable, which lists the modules
136 that the current module depends on. \a formats contains
137 a list of output formats; each format may have a different
138 output subdirectory where index files are located.
139*/
140static void loadIndexFiles(const QSet<QString> &formats)
141{
142 Config &config = Config::instance();
144 QStringList indexFiles{config.getCanonicalPathList(CONFIG_INDEXES, Config::Validate)};
145 bool warn = !config.get(CONFIG_NOLINKERRORS).asBool();
146
147 config.dependModules() += config.get(CONFIG_DEPENDS).asStringList();
148 config.dependModules().removeDuplicates();
149 bool useNoSubDirs = false;
150 QSet<QString> subDirs;
151
152 // Add format-specific output subdirectories to the set of
153 // subdirectories where we look for index files
154 for (const auto &format : formats) {
155 if (config.get(format + Config::dot + "nosubdirs").asBool()) {
156 useNoSubDirs = true;
157 const auto singleOutputSubdir{QDir(config.getOutputDir(format)).dirName()};
158 if (!singleOutputSubdir.isEmpty())
159 subDirs << singleOutputSubdir;
160 }
161 }
162
163 if (!config.dependModules().empty()) {
164 if (!config.indexDirs().empty()) {
165 for (auto &dir : config.indexDirs()) {
166 if (dir.startsWith("..")) {
167 const QString prefix(QDir(config.currentDir())
168 .relativeFilePath(config.previousCurrentDir()));
169 if (!prefix.isEmpty())
170 dir.prepend(prefix + QLatin1Char('/'));
171 }
172 }
173 /*
174 Load all dependencies:
175 Either add all subdirectories of the indexdirs as dependModules,
176 when an asterisk is used in the 'depends' list, or
177 when <format>.nosubdirs is set, we need to look for all .index files
178 in the output subdirectory instead.
179 */
180 bool asteriskUsed = false;
181 if (config.dependModules().contains("*")) {
182 config.dependModules().removeOne("*");
183 asteriskUsed = true;
184 if (useNoSubDirs) {
185 std::for_each(formats.begin(), formats.end(), [&](const QString &format) {
186 QDir scanDir(config.getOutputDir(format));
187 QStringList foundModules =
188 scanDir.entryList(QStringList("*.index"), QDir::Files);
189 std::transform(
190 foundModules.begin(), foundModules.end(), foundModules.begin(),
191 [](const QString &index) { return QFileInfo(index).baseName(); });
192 config.dependModules() << foundModules;
193 });
194 } else {
195 for (const auto &indexDir : config.indexDirs()) {
196 QDir scanDir = QDir(indexDir);
197 scanDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
198 QFileInfoList dirList = scanDir.entryInfoList();
199 for (const auto &dir : dirList)
200 config.dependModules().append(dir.fileName());
201 }
202 }
203 // Remove self-dependencies and possible duplicates
204 QString project{config.get(CONFIG_PROJECT).asString()};
205 config.dependModules().removeAll(project.toLower());
206 config.dependModules().removeDuplicates();
207 qCCritical(lcQdoc) << "Configuration file for"
208 << project << "has depends = *; loading all"
209 << config.dependModules().size()
210 << "index files found";
211 }
212 for (const auto &module : config.dependModules()) {
213 QList<QFileInfo> foundIndices;
214 // Always look in module-specific subdir, even with *.nosubdirs config
215 bool useModuleSubDir = !subDirs.contains(module);
216 subDirs << module;
217
218 for (const auto &dir : config.indexDirs()) {
219 for (const auto &subDir : std::as_const(subDirs)) {
220 QString fileToLookFor = dir + QLatin1Char('/') + subDir + QLatin1Char('/')
221 + module.toLower() + ".index";
222 if (QFile::exists(fileToLookFor)) {
223 QFileInfo tempFileInfo(fileToLookFor);
224 if (!foundIndices.contains(tempFileInfo))
225 foundIndices.append(tempFileInfo);
226 }
227 }
228 }
229 // Clear the temporary module-specific subdir
230 if (useModuleSubDir)
231 subDirs.remove(module);
232 std::sort(foundIndices.begin(), foundIndices.end(), creationTimeBefore);
233 QString indexToAdd;
234 if (foundIndices.size() > 1) {
235 /*
236 QDoc should always use the last entry in the multimap when there are
237 multiple index files for a module, since the last modified file has the
238 highest UNIX timestamp.
239 */
240 QStringList indexPaths;
241 indexPaths.reserve(foundIndices.size());
242 for (const auto &found : std::as_const(foundIndices))
243 indexPaths << found.absoluteFilePath();
244 if (warn) {
245 Location().warning(
246 QString("Multiple index files found for dependency \"%1\":\n%2")
247 .arg(module, indexPaths.join('\n')));
248 Location().warning(
249 QString("Using %1 as index file for dependency \"%2\"")
250 .arg(foundIndices[foundIndices.size() - 1].absoluteFilePath(),
251 module));
252 }
253 indexToAdd = foundIndices[foundIndices.size() - 1].absoluteFilePath();
254 } else if (foundIndices.size() == 1) {
255 indexToAdd = foundIndices[0].absoluteFilePath();
256 }
257 if (!indexToAdd.isEmpty()) {
258 if (!indexFiles.contains(indexToAdd))
259 indexFiles << indexToAdd;
260 } else if (!asteriskUsed && warn) {
261 Location().warning(
262 QString(R"("%1" Cannot locate index file for dependency "%2")")
263 .arg(config.get(CONFIG_PROJECT).asString(), module));
264 }
265 }
266 } else if (warn) {
267 Location().warning(
268 QLatin1String("Dependent modules specified, but no index directories were set. "
269 "There will probably be errors for missing links."));
270 }
271 }
272 qdb->readIndexes(indexFiles);
273}
274
275/*!
276 \internal
277 Prints to stderr the name of the project that QDoc is running for,
278 in which mode and which phase.
279
280 If QDoc is not running in debug mode or --log-progress command line
281 option is not set, do nothing.
282 */
283void logStartEndMessage(const QLatin1String &startStop, Config &config)
284{
285 if (!config.get(CONFIG_LOGPROGRESS).asBool())
286 return;
287
288 const QString runName = " qdoc for "
289 + config.get(CONFIG_PROJECT).asString()
290 + QLatin1String(" in ")
291 + QLatin1String(config.singleExec() ? "single" : "dual")
292 + QLatin1String(" process mode: ")
293 + QLatin1String(config.preparing() ? "prepare" : "generate")
294 + QLatin1String(" phase.");
295
296 const QString msg = startStop + runName;
297 qCInfo(lcQdoc) << msg.toUtf8().data();
298}
299
300/*!
301 \internal
302 Generates the index file for the current project.
303
304 Index files contain documentation metadata used for cross-module linking.
305 Index hrefs are relative paths to HTML files, so the index file must be
306 co-located with HTML output for correct link resolution. The \a plan
307 supplies every entity and example-file location; it was planned before
308 any format rendered, so the export never consults a generator.
309
310 Index generation only occurs during the prepare phase (single-exec mode)
311 or when not in generate-only mode (dual-exec mode).
312 */
313static void generateIndexFile(const Config &config, const LocationPlan &plan)
314{
315 if (config.generating())
316 return;
317
318 const QString project = config.get(CONFIG_PROJECT).asString();
319 const QString url = config.get(CONFIG_URL).asString();
320 const QString description = config.get(CONFIG_DESCRIPTION)
321 .asString(project + " Reference Documentation"_L1);
322
323 // Index files must be co-located with HTML files for correct href resolution.
324 // Use HTML output directory when available; this handles HTML.outputsubdir.
325 QString outputDirPath;
326 if (config.getOutputFormats().contains(u"HTML"_s)) {
327 outputDirPath = config.getOutputDir(u"HTML"_s);
328 } else {
329 // Fallback for non-HTML builds (e.g., DocBook-only)
330 outputDirPath = Config::overrideOutputDir.isNull()
331 ? config.get(CONFIG_OUTPUTDIR).asString()
333 if (config.singleExec())
334 outputDirPath += '/'_L1 + project.toLower();
335 }
336
337 const QString fileBase = project.toLower().simplified().replace(' '_L1, '-'_L1);
338
339 OutputDirectory outputDir = OutputDirectory::ensure(outputDirPath, Location());
340 const QString indexFileName = fileBase + ".index"_L1;
341 const QString indexPath = outputDir.absoluteFilePath(indexFileName);
342
344 context.documentLocation = [&plan](const Node *node) { return plan.documentLocation(node); };
345 context.exampleFileLocation = [&plan](const QString &file) { return plan.exampleFile(file); };
346 context.inclusionPolicy = config.createInclusionPolicy();
347 context.project = project;
349
350 QDocDatabase::qdocDB()->generateIndex(indexPath, url, description, context);
351}
352
353/*!
354 Processes the qdoc config file \a fileName. This is the controller for all
355 of QDoc. The \a config instance represents the configuration data for QDoc.
356 All other classes are initialized with the same config.
357 */
358static void processQdocconfFile(const QString &fileName)
359{
360 Config &config = Config::instance();
361 config.setPreviousCurrentDir(QDir::currentPath());
362
363 /*
364 With the default configuration values in place, load
365 the qdoc configuration file. Note that the configuration
366 file may include other configuration files.
367
368 The Location class keeps track of the current location
369 in the file being processed, mainly for error reporting
370 purposes.
371 */
373 config.load(fileName);
374 QString project{config.get(CONFIG_PROJECT).asString()};
375 if (project.isEmpty()) {
376 qCCritical(lcQdoc) << QLatin1String("qdoc can't run; no project set in qdocconf file");
377 exit(1);
378 }
380
381 config.setCurrentDir(QFileInfo(fileName).path());
382 if (!config.currentDir().isEmpty())
383 QDir::setCurrent(config.currentDir());
384
385 logStartEndMessage(QLatin1String("Start"), config);
386
387 if (config.getDebug()) {
388 Utilities::startDebugging(QString("command line"));
389 qCDebug(lcQdoc).noquote() << "Arguments:" << QCoreApplication::arguments();
390 }
391
392 // <<TODO: [cleanup-temporary-kludges]
393 // The underlying validation should be performed at the
394 // configuration level during parsing.
395 // This cannot be done straightforwardly with how the Config class
396 // is implemented.
397 // When the Config class will be deprived of logic and
398 // restructured, the compiler will notify us of this kludge, but
399 // remember to reevaluate the code itself considering the new
400 // data-flow and the possibility for optimizations as this is not
401 // done for temporary code. Indeed some of the code is visibly wasteful.
402 // Similarly, ensure that the loose definition that we use here is
403 // not preserved.
404
405 QStringList search_directories{config.getCanonicalPathList(CONFIG_EXAMPLEDIRS)};
406 QStringList image_search_directories{config.getCanonicalPathList(CONFIG_IMAGEDIRS)};
407
408 const auto& [excludedDirs, excludedFiles] = config.getExcludedPaths();
409
410 qCDebug(lcQdoc, "Adding doc/image dirs found in exampledirs to imagedirs");
411 QSet<QString> exampleImageDirs;
412 QStringList exampleImageList = config.getExampleImageFiles(excludedDirs, excludedFiles);
413 for (const auto &image : exampleImageList) {
414 if (image.contains("doc/images")) {
415 QString t = image.left(image.lastIndexOf("doc/images") + 10);
416 if (!exampleImageDirs.contains(t))
417 exampleImageDirs.insert(t);
418 }
419 }
420
421 // REMARK: The previous system discerned between search directories based on the kind of file that was searched for.
422 // For example, an image search was bounded to some directories
423 // that may or may not be the same as the ones where examples are
424 // searched for.
425 // The current Qt documentation does not use this feature. That
426 // is, the output of QDoc when a unified search list is used is
427 // the same as the output for that of separated lists.
428 // For this reason, we currently simplify the process, albeit this
429 // may at some point change, by joining the various lists into a
430 // single search list and a unified interface.
431 // Do note that the configuration still allows for those
432 // parameters to be user defined in a split-way as this will not
433 // be able to be changed until Config itself is looked upon.
434 // Hence, we join the various directory sources into one list for the time being.
435 // Do note that this means that the amount of searched directories for a file is now increased.
436 // This shouldn't matter as the amount of directories is expected
437 // to be generally small and the search routine complexity is
438 // linear in the amount of directories.
439 // There are some complications that may arise in very specific
440 // cases by this choice (some of which where there before under
441 // possibly different circumstances), making some files
442 // unreachable.
443 // See the remarks in FileResolver for more infomration.
444 std::copy(image_search_directories.begin(), image_search_directories.end(), std::back_inserter(search_directories));
445 std::copy(exampleImageDirs.begin(), exampleImageDirs.end(), std::back_inserter(search_directories));
446
447 std::vector<DirectoryPath> validated_search_directories{};
448 for (const QString& path : search_directories) {
449 auto maybe_validated_path{DirectoryPath::refine(path)};
450 if (!maybe_validated_path)
451 // TODO: [uncentralized-admonition]
452 qCDebug(lcQdoc).noquote() << u"%1 is not a valid path, it will be ignored when resolving a file"_s.arg(path);
453 else validated_search_directories.push_back(*maybe_validated_path);
454 }
455
456 // TODO>>
457
458 FileResolver file_resolver{std::move(validated_search_directories)};
459
460 // REMARK: The constructor for generators doesn't actually perform
461 // initialization of their content.
462 // Indeed, Generators use the general antipattern of the static
463 // initialize-terminate non-scoped mutable state that we see in
464 // many parts of QDoc.
465 // In their constructor, Generators mainly register themselves into a static list.
466 // Previously, this was done at the start of main.
467 // To be able to pass a correct FileResolver or other systems, we
468 // need to construct them after the configuration has been read
469 // and has been destructured.
470 // For this reason, their construction was moved here.
471 // This function may be called more than once for some of QDoc's
472 // call, albeit this should not actually happen in Qt's
473 // documentation.
474 // Then, constructing the generators here might provide for some
475 // unexpected behavior as new generators are appended to the list
476 // and never used, considering that the list is searched in a
477 // linearly fashion and each generator of some type T, in the
478 // current codebase, will always be found if another instance of
479 // that same type would have been found.
480 // Furthermore, those instances would be destroyed by then, such
481 // that accessing them would be erroneous.
482 // To avoid this, the static list was made to be cleared in
483 // Generator::terminate, which, in theory, will be called before
484 // the generators will be constructed again.
485 // We could have used the initialize method for this, but this
486 // would force us into a limited and more complex semantic, see an
487 // example of this in DocParser, and would restrain us further to
488 // the initialize-terminate idiom which is expect to be purged in
489 // the future.
490 HtmlGenerator htmlGenerator{file_resolver};
491 WebXMLGenerator webXMLGenerator{file_resolver};
492 DocBookGenerator docBookGenerator{file_resolver};
493#ifdef QDOC_TEMPLATE_GENERATOR_ENABLED
494 // Create a TemplateGenerator instance for each template-based output format.
495 // Convention: any format whose name starts with "template" (case-insensitive)
496 // is recognized as template-based. This includes the legacy "template" format
497 // and multi-format names such as "TemplateHTML" or "TemplateMarkdown".
498 // Per-format config keys (e.g., TemplateHTML.extension) must match the format
499 // name exactly — config lookups are case-sensitive.
500 // Each instance self-registers with OutputProducerRegistry and unregisters
501 // on destruction, so the registry stays clean across runs.
502 // Formats are sorted for deterministic registration order.
503 auto configuredFormats = config.getOutputFormats().values();
504 std::sort(configuredFormats.begin(), configuredFormats.end(),
505 [](const QString &a, const QString &b) {
506 return QString::compare(a, b, Qt::CaseInsensitive) < 0;
507 });
508 std::vector<std::unique_ptr<TemplateGenerator>> templateGenerators;
509 templateGenerators.reserve(configuredFormats.size());
510 const auto reportTemplateRenderFailure = [](const QString &message) {
511 Location{}.error(message);
512 Location::increaseErrorCount();
513 };
514 for (const auto &fmt : configuredFormats) {
515 if (fmt.startsWith("template"_L1, Qt::CaseInsensitive))
516 templateGenerators.push_back(
517 std::make_unique<TemplateGenerator>(file_resolver, *QDocDatabase::qdocDB(),
518 fmt, reportTemplateRenderFailure));
519 }
520#endif
521
523
524 /*
525 Initialize the qdoc database, where all the parsed source files
526 will be stored. The database includes a tree of nodes, which gets
527 built as the source files are parsed. The documentation output is
528 generated by traversing that tree.
529
530 Note: qdocDB() allocates a new instance only if no instance exists.
531 So it is safe to call qdocDB() any time.
532 */
534 qdb->setVersion(config.get(CONFIG_VERSION).asString());
535 /*
536 By default, the only output format is HTML.
537 */
538 const QSet<QString> outputFormats = config.getOutputFormats();
539
541 if (!config.singleExec()) {
542 if (!config.preparing()) {
543 qCDebug(lcQdoc, " loading index files");
544 loadIndexFiles(outputFormats);
545 qCDebug(lcQdoc, " done loading index files");
546 }
547 qdb->newPrimaryTree(project);
548 } else if (config.preparing())
549 qdb->newPrimaryTree(project);
550 else
551 qdb->setPrimaryTree(project);
552
553 // Retrieve the dependencies if loadIndexFiles() was not called
554 if (config.dependModules().isEmpty()) {
555 config.dependModules() = config.get(CONFIG_DEPENDS).asStringList();
556 config.dependModules().removeDuplicates();
557 }
558 qdb->setSearchOrder(config.dependModules());
559
560 // Store the title of the index (landing) page
562 if (root) {
563 QString title{config.get(CONFIG_NAVIGATION + Config::dot + CONFIG_LANDINGPAGE).asString()};
564 root->tree()->setIndexTitle(
565 config.get(CONFIG_NAVIGATION + Config::dot + CONFIG_LANDINGTITLE).asString(std::move(title)));
566 }
567
568
569 std::vector<QByteArray> include_paths{};
570 {
571 auto args = config.getCanonicalPathList(CONFIG_INCLUDEPATHS,
573#ifdef Q_OS_MACOS
574 args.append(Utilities::getInternalIncludePaths(QStringLiteral("clang++")));
575#elif defined(Q_OS_LINUX)
576 args.append(Utilities::getInternalIncludePaths(QStringLiteral("g++")));
577#endif
578
579 for (const auto &path : std::as_const(args)) {
580 if (!path.isEmpty())
581 include_paths.push_back(path.toUtf8());
582 }
583
584 include_paths.erase(std::unique(include_paths.begin(), include_paths.end()),
585 include_paths.end());
586 }
587
588 QList<QByteArray> clang_defines{};
589 {
590 const QStringList config_defines{config.get(CONFIG_DEFINES).asStringList()};
591 for (const QString &def : config_defines) {
592 if (!def.contains(QChar('*'))) {
593 QByteArray tmp("-D");
594 tmp.append(def.toUtf8());
595 clang_defines.append(tmp.constData());
596 }
597 }
598 }
599
600 /*
601 Initialize all the classes and data structures with the
602 qdoc configuration. This is safe to do for each qdocconf
603 file processed, because all the data structures created
604 are either cleared after they have been used, or they
605 are cleared in the terminate() functions below.
606
607 NOTE: This must happen before buildPCH() because during
608 header parsing, auto-generated documentation may be created
609 that uses QDoc markup commands (e.g., \a for parameters).
610 Those commands require Doc::initialize() to have populated
611 the command hash.
612 */
617 Doc::initialize(file_resolver);
618
619 std::optional<PCHFile> pch = std::nullopt;
620 if (Config::parseCppComments && (config.dualExec() || config.preparing())) {
621 const QString moduleHeader = config.get(CONFIG_MODULEHEADER).asString();
622 pch = buildPCH(
623 QDocDatabase::qdocDB(),
624 moduleHeader.isNull() ? project : moduleHeader,
625 Config::instance().getHeaderFiles(),
626 include_paths,
627 clang_defines,
628 Config::instance().createInclusionPolicy()
629 );
630 }
631
632 ClangCodeParser clangParser(QDocDatabase::qdocDB(), Config::instance(), include_paths, clang_defines, pch);
633 PureDocParser docParser{config.location()};
634
635 if (config.dualExec() || config.preparing()) {
636 QStringList sourceList;
637
638 qCDebug(lcQdoc, "Reading sourcedirs");
639
641 sourceList += config.getAllFiles(CONFIG_HEADERS, CONFIG_HEADERDIRS, excludedDirs,
642 excludedFiles);
643 }
644 sourceList +=
645 config.getAllFiles(CONFIG_SOURCES, CONFIG_SOURCEDIRS, excludedDirs, excludedFiles);
646
647 std::vector<QString> sources{};
648 for (const auto &source : sourceList) {
649 if (!source.contains(QLatin1String("doc/snippets")))
650 sources.emplace_back(source);
651 }
652 /*
653 Find all the qdoc files in the example dirs, and add
654 them to the source files to be parsed.
655 */
656 qCDebug(lcQdoc, "Reading exampledirs");
657 QStringList exampleQdocList = config.getExampleQdocFiles(excludedDirs, excludedFiles);
658 for (const auto &example : exampleQdocList) {
659 if (!example.contains(QLatin1String("doc/snippets")))
660 sources.emplace_back(example);
661 }
662
663 /*
664 Parse each source text file in the set using the appropriate parser and
665 add it to the big tree.
666 */
667 if (config.get(CONFIG_LOGPROGRESS).asBool())
668 qCInfo(lcQdoc) << "Parse source files for" << project;
669
670
671 auto headers = config.getHeaderFiles();
672 CppCodeParser cpp_code_parser(FnCommandParser(qdb, headers, clang_defines, pch));
673
674 SourceFileParser source_file_parser{clangParser, docParser};
675 parseSourceFiles(std::move(sources), source_file_parser, cpp_code_parser);
676
677 if (config.get(CONFIG_LOGPROGRESS).asBool())
678 qCInfo(lcQdoc) << "Source files parsed for" << project;
679 }
680 /*
681 Now the primary tree has been built from all the header and
682 source files. Resolve all the class names, function names,
683 targets, URLs, links, and other stuff that needs resolving.
684 */
685 qCDebug(lcQdoc, "Resolving stuff prior to generating docs");
687
688 /*
689 Plan publication locations once, before any format renders. The
690 exchange index exports these locations, so they must not depend on
691 which generator runs or on what it writes. The exchange still names
692 HTML pages, so the plan uses the HTML extension.
693 */
694 const LocationPlan locationPlan =
696 // This driver still selects compatibility formats. The publication set
697 // exposes legacy HTML only when it is selected, independently of the
698 // HTML-shaped index above. New-mode callers pass their resolved layout.
699 const auto publications = LocationPlanSet::build(config, qdb->primaryTree(),
700 OutputConfiguration{});
701#ifdef QDOC_TEMPLATE_GENERATOR_ENABLED
702 for (const auto &producer : templateGenerators)
703 producer->planLocations(publications);
704#endif
705
706 /*
707 The primary tree is built and all the stuff that needed
708 resolving has been resolved. Now traverse the tree and
709 generate the documentation output. More than one output
710 format can be requested. The tree is traversed for each
711 one.
712 */
713 qCDebug(lcQdoc, "Generating docs");
714 int producedFormats = 0;
715 for (const auto &format : outputFormats) {
716 auto *generator = Generator::generatorForFormat(format);
717 if (generator) {
718 generator->initializeFormat();
719 generator->generateDocs();
720 ++producedFormats;
721 } else if (auto *producer = OutputProducerRegistry::instance().producerForFormat(format)) {
722 if (!config.preparing()) {
723 producer->prepare();
724 producer->produce();
725 producer->finalize();
726 }
727 ++producedFormats;
728 } else {
729 config.get(CONFIG_OUTPUTFORMATS)
730 .location()
731 .warning(QStringLiteral("QDoc: Unknown output format '%1'; skipping. "
732 "Check for typos or ensure the corresponding "
733 "generator is enabled in this QDoc build.")
734 .arg(format));
735 }
736 }
737
738 if (!outputFormats.isEmpty() && producedFormats == 0) {
739 config.get(CONFIG_OUTPUTFORMATS)
741 .fatal(QStringLiteral("QDoc: None of the configured output formats could be produced; aborting"));
742 }
743
744 generateIndexFile(config, locationPlan);
745
746 qCDebug(lcQdoc, "Terminating qdoc classes");
748 Utilities::stopDebugging(project);
749
750 logStartEndMessage(QLatin1String("End"), config);
751 QDocDatabase::qdocDB()->setVersion(QString());
758 QDir::setCurrent(config.previousCurrentDir());
759
760 qCDebug(lcQdoc, "qdoc classes terminated");
761}
762
763/*!
764 \internal
765 For each file in \a qdocFiles, first clear the configured module
766 dependencies and then pass the file to processQdocconfFile().
767
768 \sa processQdocconfFile(), singleExecutionMode(), dualExecutionMode()
769*/
770static void clearModuleDependenciesAndProcessQdocconfFile(const QStringList &qdocFiles)
771{
772 for (const auto &file : std::as_const(qdocFiles)) {
773 Config::instance().dependModules().clear();
774 processQdocconfFile(file);
775 }
776}
777
778/*!
779 \internal
780
781 A single QDoc process for prepare and generate phases.
782 The purpose is to first generate all index files for all documentation
783 projects that combined make out the documentation set being generated.
784 This allows QDoc to link to all content contained in all projects, e.g.
785 user-defined types or overview documentation, regardless of the project
786 that content belongs to when generating the final output.
787*/
789{
790 const QStringList qdocFiles = Config::loadMaster(Config::instance().qdocFiles().at(0));
791
792 Config::instance().setQDocPass(Config::Prepare);
793 clearModuleDependenciesAndProcessQdocconfFile(qdocFiles);
794
795 Config::instance().setQDocPass(Config::Generate);
797 clearModuleDependenciesAndProcessQdocconfFile(qdocFiles);
798}
799
800/*!
801 \internal
802
803 Process each .qdocconf-file passed as command line argument(s).
804*/
805static void dualExecutionMode()
806{
807 const QStringList qdocFiles = Config::instance().qdocFiles();
808 clearModuleDependenciesAndProcessQdocconfFile(qdocFiles);
809}
810
812
813int main(int argc, char **argv)
814{
815 QT_USE_NAMESPACE
816
817 // Initialize Qt:
818#ifndef QT_BOOTSTRAPPED
819 // use deterministic hash seed
820 QHashSeed::setDeterministicGlobalSeed();
821#endif
822 QCoreApplication app(argc, argv);
823 app.setApplicationVersion(QLatin1String(QT_VERSION_STR));
824
825 // Instantiate various singletons (used via static methods):
826 /*
827 Create code parsers for the languages to be parsed,
828 and create a tree for C++.
829 */
830 QmlCodeParser qmlParser;
831
832 /*
833 Create code markers for plain text, C++,
834 and QML.
835
836 The plain CodeMarker must be instantiated first because it is used as
837 fallback when the other markers cannot be used.
838
839 Each marker instance is prepended to the CodeMarker::markers list by the
840 base class constructor.
841 */
842 CodeMarker fallbackMarker;
843 CppCodeMarker cppMarker;
844 QmlCodeMarker qmlMarker;
845
846 Config::instance().init("QDoc", app.arguments());
847
848 if (Config::instance().qdocFiles().isEmpty())
849 Config::instance().showHelp();
850
851 if (Config::instance().singleExec()) {
853 } else {
855 }
856
857 // Tidy everything away:
861}
static void initialize()
All the code markers in the static list are initialized here, after the qdoc configuration file has b...
static void terminate()
All the code markers in the static list are terminated here.
virtual void parseSourceFile(const Location &location, const QString &filePath, CppCodeParser &cpp_code_parser)=0
static CodeParser * parserForSourceFile(const QString &filePath)
static void initialize()
All the code parsers in the static list are initialized here, after the qdoc configuration variables ...
static void terminate()
All the code parsers in the static list are terminated here.
const Location & location() const
Definition config.h:55
bool asBool() const
Returns this config variable as a boolean.
Definition config.cpp:317
The Config class contains the configuration variables for controlling how qdoc produces documentation...
Definition config.h:95
static const QString dot
Definition config.h:181
static bool parseCppComments
Definition config.h:184
InclusionPolicy createInclusionPolicy() const
Definition config.cpp:1678
bool singleExec() const
Definition config.h:480
@ Validate
Definition config.h:114
@ IncludePaths
Definition config.h:115
const Location & location() const
Definition config.h:137
const ExcludedPaths & getExcludedPaths()
Definition config.cpp:1509
bool dualExec() const
Definition config.h:485
bool preparing() const
Definition config.h:201
bool generating() const
Definition config.h:202
bool getDebug() const
Definition config.h:119
static QString overrideOutputDir
Definition config.h:186
CppCodeParser(FnCommandParser &&parser)
static void processMetaCommands(const Doc &doc, Node *node)
The topic command has been processed, and now doc and node are passed to this function to get the met...
DocBookGenerator(FileResolver &file_resolver)
Definition doc.h:32
static void initialize(FileResolver &file_resolver)
Definition doc.cpp:363
static void terminate()
All the heap allocated variables are deleted.
Definition doc.cpp:416
Encapsulate the logic that QDoc uses to find files whose path is provided by the user and that are re...
static void initialize()
static void terminate()
HtmlGenerator(FileResolver &file_resolver)
static LocationPlanSet build(const Config &config, const Tree *tree, const OutputConfiguration &output)
Builds plans for requested publications in output.
\variable PublicationLocation::path
static LocationPlan build(LocationRules rules, const Tree *tree)
Plans the locations of every entity in tree under rules.
The Location class provides a way to mark a location in a file.
Definition location.h:20
static int exitCode()
Returns the error code QDoc should exit with.
Definition location.cpp:298
static void initialize()
Gets several parameters from the config, including tab size, program name, and a regular expression t...
Definition location.cpp:363
Location()
Constructs an empty location.
Definition location.cpp:50
static void terminate()
Apparently, all this does is delete the regular expression used for intercepting certain error messag...
Definition location.cpp:510
This class represents a C++ namespace.
Tree * tree() const override
Returns a pointer to the Tree that contains this NamespaceNode.
Represents an output directory that has been verified to exist.
PureDocParser(const Location &location)
This class provides exclusive access to the qdoc database, which consists of a forrest of trees and a...
static void destroyQdocDB()
Destroys the singleton.
static QDocDatabase * qdocDB()
Creates the singleton.
NamespaceNode * primaryTreeRoot()
Returns a pointer to the root node of the primary tree.
void processForest()
This function calls a set of functions for each tree in the forest that has not already been analyzed...
void clearSearchOrder()
void resolveStuff()
Performs several housekeeping tasks prior to generating the documentation.
Tree * primaryTree()
static void terminate()
Clear the static maps so that subsequent runs don't try to use contents from a previous run.
SourceFileParser(ClangCodeParser &clang_parser, PureDocParser &pure_parser)
static void terminate()
The heap allocated variables are freed here.
static void initialize()
WebXMLGenerator(FileResolver &file_resolver)
#define CONFIG_SOURCES
Definition config.h:458
#define CONFIG_OUTPUTDIR
Definition config.h:436
#define CONFIG_VERSION
Definition config.h:470
#define CONFIG_EXAMPLEDIRS
Definition config.h:398
#define CONFIG_URL
Definition config.h:468
#define CONFIG_INDEXES
Definition config.h:422
#define CONFIG_DEFINES
Definition config.h:392
#define CONFIG_DEPENDS
Definition config.h:393
#define CONFIG_NOLINKERRORS
Definition config.h:435
#define CONFIG_LOGPROGRESS
Definition config.h:427
#define CONFIG_DESCRIPTION
Definition config.h:394
#define CONFIG_IMAGEDIRS
Definition config.h:416
#define CONFIG_PROJECT
Definition config.h:444
#define CONFIG_SOURCEDIRS
Definition config.h:456
#define CONFIG_HEADERS
Definition config.h:407
#define CONFIG_DOCUMENTATIONINHEADERS
Definition config.h:396
#define CONFIG_NAVIGATION
Definition config.h:434
#define CONFIG_LANDINGPAGE
Definition config.h:423
#define CONFIG_OUTPUTFORMATS
Definition config.h:437
#define CONFIG_LOCATIONINFO
Definition config.h:426
#define CONFIG_LANDINGTITLE
Definition config.h:424
#define CONFIG_MODULEHEADER
Definition config.h:432
#define CONFIG_HEADERDIRS
Definition config.h:406
#define CONFIG_INCLUDEPATHS
Definition config.h:418
Combined button and popup list for selecting options.
This namespace holds QDoc-internal utility methods.
Definition utilities.h:21
bool debugging()
Definition utilities.cpp:39
static void parseSourceFiles(std::vector< QString > &&sources, SourceFileParser &source_file_parser, CppCodeParser &cpp_code_parser)
Definition main.cpp:76
static void singleExecutionMode()
Definition main.cpp:788
void logStartEndMessage(const QLatin1String &startStop, Config &config)
Definition main.cpp:283
static void processQdocconfFile(const QString &fileName)
Processes the qdoc config file fileName.
Definition main.cpp:358
static void generateIndexFile(const Config &config, const LocationPlan &plan)
Definition main.cpp:313
static void clearModuleDependenciesAndProcessQdocconfFile(const QStringList &qdocFiles)
Definition main.cpp:770
static void dualExecutionMode()
Definition main.cpp:805
bool creationTimeBefore(const QFileInfo &fi1, const QFileInfo &fi2)
Definition main.cpp:57
static void loadIndexFiles(const QSet< QString > &formats)
Read some XML indexes containing definitions from other documentation sets.
Definition main.cpp:140
int main(int argc, char *argv[])
[ctor_close]
Holds the configuration a format needs to name its published files.
static LocationRules fromConfig(const Config &config, const QString &fileExtension)
Reads the naming configuration from config for pages that use fileExtension.
The Node class is the base class for all the nodes in QDoc's parse tree.
Processes parser errors and outputs warnings for them.
Definition parsererror.h:20