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
templatepackage.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
5
6#include "config.h"
7
8#include <QtCore/qdir.h>
9#include <QtCore/qfile.h>
10#include <QtCore/qfileinfo.h>
11#include <QtCore/qjsonarray.h>
12#include <QtCore/qjsondocument.h>
13#include <QtCore/qjsonobject.h>
14
15#include <utility>
16
18
19using namespace Qt::StringLiterals;
20
21/*!
22 \struct TemplatePackageInput
23 \internal
24 \inmodule QDoc
25 \brief Supplies engine facts that a template package resolution needs.
26
27 The caller states which optional engine capabilities this QDoc build
28 provides and where the built-in package lives. Production callers keep the
29 embedded resource root; tests can point at a source checkout instead.
30*/
31
32/*!
33 \variable TemplatePackageInput::engineCapabilities
34 \brief The optional capability names this QDoc build can honor.
35
36 A manifest that requires a capability absent from this set is an error.
37 QDoc currently declares no optional capabilities, so the production set is
38 empty until the engine grows an explicitly supported feature.
39*/
40
41/*!
42 \variable TemplatePackageInput::builtinRoot
43 \brief The directory holding the built-in \c{qdoc:default} package.
44
45 The directory must contain a manifest like any other package. The default
46 names the templates embedded in the QDoc executable.
47*/
48
49/*!
50 \struct TemplatePackage
51 \internal
52 \inmodule QDoc
53 \brief Resolves the effective template package declared by a configuration.
54
55 A package is a directory holding a \c{qdoc-template.json} manifest. The
56 manifest declares the manifest schema version, the template API version it
57 was written against, an optional single parent to extend, optional engine
58 capabilities it requires, and the formats it provides. Each format carries
59 a default file extension and maps the page roles QDoc renders to template
60 files. Paths are relative to the manifest that declares them.
61
62 Inheritance is explicit and single-parent. A child inherits every parent
63 format and role mapping and overrides only what it declares. Declaring a
64 format as \c false drops it from the effective package. An override that
65 names a missing file breaks the format rather than falling back to the
66 parent's template. Lists do not concatenate: each manifest's requirements
67 are validated on their own.
68
69 The built-in package is addressed as \c{qdoc:default} and loads through
70 the same code path as an external directory, so QDoc itself carries no
71 branding. Resolution reads files but never writes, never renders, and
72 never emits diagnostics; the caller presents errors before publication.
73*/
74
75/*!
76 \typealias TemplatePackage::Diagnostic
77 \internal
78 \brief Uses the same diagnostic data and severity contract as OutputSelection.
79*/
80
81/*!
82 \variable TemplatePackage::supportedSchemaVersion
83 \brief The manifest syntax version this QDoc reads.
84
85 Manifests must declare exactly this \c{schemaVersion}. A newer or older
86 syntax is an error rather than a best-effort interpretation.
87*/
88
89/*!
90 \variable TemplatePackage::providedTemplateApiVersion
91 \brief The render-data contract version this QDoc offers templates.
92
93 Manifests must declare exactly this \c{templateApiVersion}. A package
94 written against another contract is rejected before any rendering.
95*/
96
97/*!
98 \struct TemplatePackage::Template
99 \internal
100 \inmodule QDoc
101 \brief Names one template file and the manifest that declared it.
102*/
103
104/*!
105 \variable TemplatePackage::Template::path
106 \brief The complete path of the template file, resolved against its manifest directory.
107
108 For the built-in package this is a resource path.
109*/
110
111/*!
112 \variable TemplatePackage::Template::location
113 \brief The manifest that declared this mapping, which may be a parent package.
114*/
115
116/*!
117 \struct TemplatePackage::Format
118 \internal
119 \inmodule QDoc
120 \brief Describes one format the effective package provides.
121
122 Extension and role mappings may come from different manifests in the
123 inheritance chain; each value records its own origin. Values never leak
124 between formats: a format that declares no extension has none, regardless
125 of what sibling formats declare.
126*/
127
128/*!
129 \variable TemplatePackage::Format::format
130 \brief The case-sensitive publication identity, such as \c HTML.
131*/
132
133/*!
134 \variable TemplatePackage::Format::extension
135 \brief The default file extension without a separator, or empty if none was declared.
136
137 OutputSelection applies this as the pipeline default and still honors an
138 explicit \c{<Format>.extension} configuration override.
139*/
140
141/*!
142 \variable TemplatePackage::Format::extensionLocation
143 \brief The manifest that declared the effective extension, if any.
144*/
145
146/*!
147 \variable TemplatePackage::Format::templates
148 \brief The effective role to template mapping, keyed by role name.
149
150 See roles() for the roles every format must map. Several roles may name
151 the same file.
152*/
153
154/*!
155 \variable TemplatePackage::Format::location
156 \brief The most derived manifest that mentions this format.
157*/
158
159/*!
160 \variable TemplatePackage::Format::broken
161 \brief Whether the declaration is incomplete or names a missing template.
162
163 A broken format remains an ownership claim for OutputSelection; it is an
164 error to request it, and QDoc never substitutes another pipeline or an
165 inherited template for it.
166*/
167
168/*!
169 \variable TemplatePackage::id
170 \brief The built-in identifier or the complete directory of the selected package.
171*/
172
173/*!
174 \variable TemplatePackage::location
175 \brief The \c{template.package} declaration, or empty for the implicit built-in package.
176*/
177
178/*!
179 \variable TemplatePackage::loaded
180 \brief Whether every manifest in the inheritance chain was read and validated.
181
182 A loaded package can still carry broken formats; check hasErrors() for the
183 combined verdict.
184*/
185
186/*!
187 \variable TemplatePackage::searchPaths
188 \brief The package directories from the most derived to the root package.
189
190 Consumers resolve template includes against these directories in order, so
191 a child can override a partial without redeclaring the roles that use it.
192*/
193
194/*!
195 \variable TemplatePackage::formats
196 \brief The effective formats in identity order.
197*/
198
199/*!
200 \variable TemplatePackage::diagnostics
201 \brief The errors collected while reading, validating, and merging manifests.
202*/
203
204namespace {
205
206using Diagnostic = TemplatePackage::Diagnostic;
207
208struct FormatDeclaration
209{
210 bool removed = false;
211 bool hasExtension = false;
212 QString extension;
213 QMap<QString, QString> templates;
214 Location location;
215};
216
217struct Manifest
218{
219 QString dir;
220 Location location;
221 QString extends;
222 QMap<QString, FormatDeclaration> formats;
223};
224
225void report(QVector<Diagnostic> &diagnostics, const Location &location, QString message,
226 QString details = {})
227{
228 diagnostics.push_back(
229 Diagnostic{ Diagnostic::Kind::Error, location, std::move(message), std::move(details) });
230}
231
232int lineOfOffset(const QByteArray &text, int offset)
233{
234 return 1 + static_cast<int>(text.left(offset).count('\n'));
235}
236
237QString packageDirectory(const QString &reference, const QString &baseDir,
238 const QString &builtinRoot)
239{
240 if (reference == TemplatePackage::builtinId())
241 return QDir::cleanPath(builtinRoot);
242 if (QDir::isAbsolutePath(reference))
243 return QDir::cleanPath(reference);
244 return QDir::cleanPath(QDir(baseDir).absoluteFilePath(reference));
245}
246
247bool readVersion(const QJsonObject &object, const QString &key, int supported,
248 const QString &subject, const QString &verb, const Location &location,
249 QVector<Diagnostic> &diagnostics)
250{
251 const QJsonValue value = object.value(key);
252 if (value.isUndefined()) {
253 report(diagnostics, location, "Manifest key '%1' is required."_L1.arg(key));
254 return false;
255 }
256 const int actual = value.isDouble() ? value.toInt(-1) : -1;
257 if (actual < 0) {
258 report(diagnostics, location,
259 "Manifest key '%1' must be a non-negative integer."_L1.arg(key));
260 return false;
261 }
262 if (actual != supported) {
263 report(diagnostics, location, "%1 %2 is not supported."_L1.arg(subject).arg(actual),
264 "This QDoc %1 %2 %3."_L1.arg(verb, subject.toLower()).arg(supported));
265 return false;
266 }
267 return true;
268}
269
270bool readFormat(const QString &format, const QJsonValue &value, const QString &dir,
271 const Location &location, QMap<QString, FormatDeclaration> &formats,
272 QVector<Diagnostic> &diagnostics)
273{
274 FormatDeclaration declaration;
275 declaration.location = location;
276 if (value.isBool() && !value.toBool()) {
277 declaration.removed = true;
278 formats.insert(format, declaration);
279 return true;
280 }
281 if (!value.isObject()) {
282 report(diagnostics, location, "Format '%1' must be an object or false."_L1.arg(format),
283 u"Use false to drop an inherited format."_s);
284 return false;
285 }
286
287 bool ok = true;
288 const QJsonObject entry = value.toObject();
289 for (const QString &key : entry.keys()) {
290 if (key != "extension"_L1 && key != "templates"_L1) {
291 report(diagnostics, location,
292 "Unknown key '%1' for format '%2'."_L1.arg(key, format),
293 u"Supported keys: extension, templates."_s);
294 ok = false;
295 }
296 }
297 if (entry.contains("extension"_L1)) {
298 const QJsonValue extension = entry.value("extension"_L1);
299 const QString text = extension.isString() ? extension.toString() : QString();
300 if (text.isEmpty() || text.contains(u'/') || text.contains(u'\\')) {
301 report(diagnostics, location,
302 "Format '%1' declares an invalid or empty extension."_L1.arg(format),
303 u"Provide a non-empty file extension without path separators."_s);
304 ok = false;
305 } else {
306 declaration.hasExtension = true;
307 declaration.extension = text;
308 }
309 }
310 if (entry.contains("templates"_L1)) {
311 const QJsonValue templates = entry.value("templates"_L1);
312 if (!templates.isObject()) {
313 report(diagnostics, location,
314 "Format '%1' must map template roles in a 'templates' object."_L1.arg(format));
315 ok = false;
316 } else {
317 const QStringList roles = TemplatePackage::roles();
318 const QJsonObject mapping = templates.toObject();
319 for (auto role = mapping.constBegin(); role != mapping.constEnd(); ++role) {
320 if (!roles.contains(role.key())) {
321 report(diagnostics, location,
322 "Unknown template role '%1' for format '%2'."_L1.arg(role.key(), format),
323 "Supported roles: %1."_L1.arg(roles.join(u", "_s)));
324 ok = false;
325 continue;
326 }
327 const QString path = role.value().isString() ? role.value().toString() : QString();
328 if (path.isEmpty()) {
329 report(diagnostics, location,
330 "Format '%1' declares an empty template for role '%2'."_L1
331 .arg(format, role.key()));
332 ok = false;
333 continue;
334 }
335 declaration.templates.insert(role.key(),
336 QDir::cleanPath(QDir(dir).absoluteFilePath(path)));
337 }
338 }
339 }
340 if (ok)
341 formats.insert(format, declaration);
342 return ok;
343}
344
345bool readManifest(const QString &dir, const Location &from, const QSet<QString> &capabilities,
346 Manifest &manifest, QVector<Diagnostic> &diagnostics)
347{
348 const QString manifestPath = dir + u'/' + TemplatePackage::manifestFileName();
349 if (!QFileInfo(manifestPath).isFile()) {
350 report(diagnostics, from,
351 "Template package '%1' has no %2 manifest."_L1.arg(dir, TemplatePackage::manifestFileName()),
352 u"A package is a directory containing a manifest."_s);
353 return false;
354 }
355 QFile file(manifestPath);
356 if (!file.open(QIODevice::ReadOnly)) {
357 report(diagnostics, from,
358 "Cannot read template package manifest '%1': %2"_L1.arg(manifestPath,
359 file.errorString()));
360 return false;
361 }
362 const QByteArray raw = file.readAll();
363 const Location location(manifestPath);
364 QJsonParseError parseError;
365 const QJsonDocument document = QJsonDocument::fromJson(raw, &parseError);
366 if (parseError.error != QJsonParseError::NoError) {
367 Location at = location;
368 at.setLineNo(lineOfOffset(raw, parseError.offset));
369 report(diagnostics, at,
370 "Cannot parse template package manifest: %1"_L1.arg(parseError.errorString()));
371 return false;
372 }
373 if (!document.isObject()) {
374 report(diagnostics, location,
375 u"Template package manifest must contain a JSON object."_s);
376 return false;
377 }
378
379 manifest.dir = dir;
380 manifest.location = location;
381 const QJsonObject object = document.object();
382 bool ok = true;
383 static const QSet<QString> knownKeys{ u"schemaVersion"_s, u"templateApiVersion"_s,
384 u"extends"_s, u"requires"_s, u"formats"_s };
385 for (const QString &key : object.keys()) {
386 if (!knownKeys.contains(key)) {
387 report(diagnostics, location, "Unknown manifest key '%1'."_L1.arg(key),
388 u"Supported keys: schemaVersion, templateApiVersion, extends, requires, formats."_s);
389 ok = false;
390 }
391 }
392 if (!readVersion(object, u"schemaVersion"_s, TemplatePackage::supportedSchemaVersion,
393 u"Manifest schema version"_s, u"supports"_s, location, diagnostics))
394 return false;
395 if (!readVersion(object, u"templateApiVersion"_s, TemplatePackage::providedTemplateApiVersion,
396 u"Template API version"_s, u"provides"_s, location, diagnostics))
397 return false;
398
399 if (object.contains("extends"_L1)) {
400 const QJsonValue value = object.value("extends"_L1);
401 if (!value.isString() || value.toString().isEmpty()) {
402 report(diagnostics, location, u"Manifest key 'extends' must name a parent package."_s,
403 "Use a directory relative to this manifest or '%1'."_L1
404 .arg(TemplatePackage::builtinId()));
405 ok = false;
406 } else {
407 manifest.extends = value.toString();
408 }
409 }
410 if (object.contains("requires"_L1)) {
411 const QJsonValue value = object.value("requires"_L1);
412 if (!value.isArray()) {
413 report(diagnostics, location,
414 u"Manifest key 'requires' must be an array of capability names."_s);
415 ok = false;
416 } else {
417 const QJsonArray entries = value.toArray();
418 for (const QJsonValue &entry : entries) {
419 const QString name = entry.isString() ? entry.toString() : QString();
420 if (name.isEmpty()) {
421 report(diagnostics, location,
422 u"Manifest key 'requires' must list non-empty capability names."_s);
423 ok = false;
424 } else if (!capabilities.contains(name)) {
425 report(diagnostics, location,
426 "Template package requires capability '%1', which this QDoc does not provide."_L1
427 .arg(name));
428 ok = false;
429 }
430 }
431 }
432 }
433 if (object.contains("formats"_L1)) {
434 const QJsonValue value = object.value("formats"_L1);
435 if (!value.isObject()) {
436 report(diagnostics, location,
437 u"Manifest key 'formats' must be an object keyed by format identity."_s);
438 ok = false;
439 } else {
440 const QJsonObject formats = value.toObject();
441 for (auto it = formats.constBegin(); it != formats.constEnd(); ++it) {
442 if (!OutputSelection::isValidFormatIdentity(it.key())) {
443 report(diagnostics, location, "Invalid format identity '%1'."_L1.arg(it.key()),
444 u"Format names may contain letters, digits, and underscores only."_s);
445 ok = false;
446 continue;
447 }
448 if (!readFormat(it.key(), it.value(), dir, location, manifest.formats, diagnostics))
449 ok = false;
450 }
451 }
452 }
453 return ok;
454}
455
456} // namespace
457
458/*!
459 Returns the identifier of the package built into QDoc.
460*/
461QString TemplatePackage::builtinId()
462{
463 return u"qdoc:default"_s;
464}
465
466/*!
467 Returns the file name a package directory must contain.
468*/
469QString TemplatePackage::manifestFileName()
470{
471 return u"qdoc-template.json"_s;
472}
473
474/*!
475 Returns the roles every format must map to a template, in rendering order.
476
477 The roles mirror the generator's entry points: a documentation page, a
478 collection page, a C++ reference page, a QML type page, a member list, and
479 an obsolete member list.
480*/
481QStringList TemplatePackage::roles()
482{
483 return { u"page"_s, u"collection"_s, u"cppref"_s, u"qmltype"_s, u"members"_s,
484 u"obsolete"_s };
485}
486
487/*!
488 Resolves the package that \a config selects through \c{template.package},
489 or the built-in package when the setting is absent, using the engine facts
490 in \a input.
491
492 A relative package path is taken from the directory of the configuration
493 file that declared it. Returns diagnostics as data; the caller must check
494 hasErrors() before trusting formats or capabilities().
495*/
497{
498 TemplatePackage result;
499 QString reference = builtinId();
500 QString baseDir = config.currentDir();
501 if (config.contains(CONFIG_TEMPLATEPACKAGE)) {
502 const ConfigVar &var = config.get(CONFIG_TEMPLATEPACKAGE);
503 result.location = var.location();
504 const QStringList values = var.asStringList();
505 if (values.size() > 1) {
506 report(result.diagnostics, result.location,
507 "%1 must contain a single value."_L1.arg(CONFIG_TEMPLATEPACKAGE),
508 "Name one package directory or '%1'."_L1.arg(builtinId()));
509 return result;
510 }
511 reference = values.value(0);
512 if (reference.isEmpty()) {
513 report(result.diagnostics, result.location,
514 "%1 is empty."_L1.arg(CONFIG_TEMPLATEPACKAGE),
515 "Name a package directory relative to the declaring configuration file, or '%1'."_L1
516 .arg(builtinId()));
517 return result;
518 }
519 if (!var.path().isEmpty())
520 baseDir = var.path();
521 }
522
523 QVector<Manifest> chain;
524 QStringList visited;
525 Location from = result.location;
526 for (;;) {
527 if (reference.startsWith("qdoc:"_L1) && reference != builtinId()) {
528 report(result.diagnostics, from,
529 "Unknown built-in template package '%1'."_L1.arg(reference),
530 "QDoc provides '%1'."_L1.arg(builtinId()));
531 return result;
532 }
533 const QString dir = packageDirectory(reference, baseDir, input.builtinRoot);
534 if (chain.isEmpty())
535 result.id = reference == builtinId() ? builtinId() : dir;
536 if (visited.contains(dir)) {
537 visited.append(dir);
538 report(result.diagnostics, from,
539 "Template package inheritance cycle: %1."_L1.arg(visited.join(u" extends "_s)),
540 u"A package may extend one parent and may not extend itself, directly or indirectly."_s);
541 return result;
542 }
543 visited.append(dir);
544 Manifest manifest;
545 if (!readManifest(dir, from, input.engineCapabilities, manifest, result.diagnostics))
546 return result;
547 chain.append(manifest);
548 if (manifest.extends.isEmpty())
549 break;
550 reference = manifest.extends;
551 baseDir = manifest.dir;
552 from = manifest.location;
553 }
554 result.loaded = true;
555 for (const Manifest &manifest : std::as_const(chain))
556 result.searchPaths.append(manifest.dir);
557
558 QMap<QString, Format> effective;
559 for (auto manifest = chain.crbegin(); manifest != chain.crend(); ++manifest) {
560 for (auto it = manifest->formats.constBegin(); it != manifest->formats.constEnd(); ++it) {
561 const FormatDeclaration &declaration = it.value();
562 if (declaration.removed) {
563 effective.remove(it.key());
564 continue;
565 }
566 Format &format = effective[it.key()];
567 format.format = it.key();
568 format.location = declaration.location;
569 if (declaration.hasExtension) {
570 format.extension = declaration.extension;
571 format.extensionLocation = declaration.location;
572 }
573 for (auto role = declaration.templates.constBegin();
574 role != declaration.templates.constEnd(); ++role) {
575 format.templates.insert(role.key(), Template{ role.value(), declaration.location });
576 }
577 }
578 }
579
580 const QStringList allRoles = roles();
581 for (Format &format : effective) {
582 for (const QString &role : allRoles) {
583 if (!format.templates.contains(role)) {
584 report(result.diagnostics, format.location,
585 "Format '%1' declares no template for role '%2'."_L1.arg(format.format, role),
586 u"Declare every role or inherit it from a parent package."_s);
587 format.broken = true;
588 }
589 }
590 for (auto it = format.templates.constBegin(); it != format.templates.constEnd(); ++it) {
591 if (!QFileInfo(it.value().path).isFile()) {
592 report(result.diagnostics, it.value().location,
593 "Template '%1' for role '%2' of format '%3' does not exist."_L1
594 .arg(it.value().path, it.key(), format.format),
595 u"QDoc does not fall back to an inherited template for a failed override."_s);
596 format.broken = true;
597 }
598 }
599 result.formats.append(format);
600 }
601 return result;
602}
603
604/*!
605 Returns \c true if any diagnostic blocks use of the package.
606*/
608{
609 for (const auto &diagnostic : diagnostics) {
610 if (diagnostic.kind == Diagnostic::Kind::Error)
611 return true;
612 }
613 return false;
614}
615
616/*!
617 Returns the effective entry for the case-sensitive identity \a format, or
618 \c{nullptr} if the package does not provide it.
619
620 The pointer borrows storage from this package and remains valid only while
621 that storage is alive and unchanged. A returned entry may be broken.
622*/
623const TemplatePackage::Format *TemplatePackage::findFormat(const QString &format) const
624{
625 for (const auto &entry : formats) {
626 if (entry.format == format)
627 return &entry;
628 }
629 return nullptr;
630}
631
632/*!
633 Returns the template pipeline's capabilities as OutputSelection expects them.
634
635 The pipeline is available when every manifest loaded. Complete formats are
636 supported, broken formats remain declared ownership claims, and declared
637 extensions become the pipeline defaults.
638*/
640{
643 result.available = loaded;
644 for (const Format &format : formats) {
645 if (format.broken)
646 result.brokenFormats.insert(format.format);
647 else
648 result.supportedFormats.insert(format.format);
649 if (!format.extension.isEmpty())
650 result.formatExtensions.insert(format.format, format.extension);
651 }
652 return result;
653}
654
655QT_END_NAMESPACE
contains all the information for a single config variable in a .qdocconf file.
Definition config.h:43
const Location & location() const
Definition config.h:55
The Config class contains the configuration variables for controlling how qdoc produces documentation...
Definition config.h:95
The Location class provides a way to mark a location in a file.
Definition location.h:20
void setLineNo(int no)
Definition location.h:42
#define CONFIG_TEMPLATEPACKAGE
Definition config.h:464
Combined button and popup list for selecting options.
Kind
Distinguishes blocking errors from migration advice.
Describes a pipeline without constructing generators or loading packages.
Supplies engine facts that a template package resolution needs.
\variable TemplatePackage::Template::path
\typealias TemplatePackage::Diagnostic
\variable TemplatePackageInput::engineCapabilities
OutputSelection::Diagnostic Diagnostic
bool hasErrors() const
Returns true if any diagnostic blocks use of the package.
PipelineCapabilities capabilities() const
Returns the template pipeline's capabilities as OutputSelection expects them.
static TemplatePackage resolve(const Config &config, const TemplatePackageInput &input={})
Resolves the package that config selects through {template.package}, or the built-in package when the...
const Format * findFormat(const QString &format) const
Returns the effective entry for the case-sensitive identity format, or {nullptr} if the package does ...