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
injabridge.cpp
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include "injabridge.h"
5
6#include "textutils.h"
7
8#include <QtCore/qlogging.h>
9
10#include <cmath>
11#include <functional>
12#include <utility>
13
14QT_BEGIN_NAMESPACE
15
16using namespace Qt::Literals;
17
19namespace {
20
21InjaBridge::RenderContext activeRenderContext;
22
23// Makes a render's context the one qdocFatalTemplateRenderError() reports
24// while that render runs, and restores the enclosing render's context when
25// a nested render returns.
26class RenderContextScope
27{
28 Q_DISABLE_COPY_MOVE(RenderContextScope)
29
30public:
31 explicit RenderContextScope(const InjaBridge::RenderContext &context)
32 : m_previous(std::exchange(activeRenderContext, context))
33 {
34 }
35 ~RenderContextScope() { activeRenderContext = std::move(m_previous); }
36
37private:
38 InjaBridge::RenderContext m_previous;
39};
40
41} // namespace
42#endif // !QDOC_TEMPLATE_LIBS_THROW
43
44/*!
45 \brief Formats \a message with the failing render's \a context.
46*/
47QString InjaBridge::renderErrorText(const RenderContext &context, const QString &message)
48{
49 const auto name = [](const QString &value) { return value.isEmpty() ? u"<unknown>"_s : value; };
50 return u"Failed to render page '"_s + name(context.page) + u"' with template '"_s
51 + name(context.templatePath) + u"' in format '"_s + name(context.format) + u"': "_s
52 + message;
53}
54
56/*!
57 \internal
58 The error-reporting entry point for template library errors in a
59 no-exceptions build. The header redefines INJA_THROW and
60 JSON_THROW_USER, the error-reporting entry points of Inja and
61 nlohmann::json, to this function before including the libraries, so
62 a library error terminates the run with the diagnostic for the
63 render in progress instead of a bare abort.
64*/
65[[noreturn]] void qdocFatalTemplateRenderError(const char *what)
66{
67 qFatal("%s", qPrintable(InjaBridge::renderErrorText(activeRenderContext,
68 QString::fromUtf8(what))));
69}
70#endif // !QDOC_TEMPLATE_LIBS_THROW
71
72static InjaBridge::RenderResult renderWithPolicy(const InjaBridge::RenderContext &context,
73 const std::function<QString()> &render)
74{
76 Q_UNUSED(context);
77 try {
78 return render();
79 } catch (const std::exception &e) {
80 return InjaBridge::RenderFailure{ QString::fromUtf8(e.what()) };
81 }
82#else
83 const RenderContextScope scope(context);
84 return render();
85#endif
86}
87
88static std::string escapeHtml(const std::string &input)
89{
90 std::string buffer;
91 buffer.reserve(input.size() + input.size() / 8);
92 for (char c : input) {
93 switch (c) {
94 case '&':
95 buffer += "&amp;";
96 break;
97 case '"':
98 buffer += "&quot;";
99 break;
100 case '\'':
101 buffer += "&apos;";
102 break;
103 case '<':
104 buffer += "&lt;";
105 break;
106 case '>':
107 buffer += "&gt;";
108 break;
109 default:
110 buffer += c;
111 break;
112 }
113 }
114 return buffer;
115}
116
117// Render a single link span for either output surface. HTML escapes both the
118// visible text and the href; a span with no usable href degrades to plain text
119// rather than a dangling link. Markdown emits a bracket-paren link with the
120// text and URL as-is: the concept names and generated hrefs in scope here carry
121// no Markdown-special characters, and general Markdown escaping is out of scope.
122static std::string renderLinkSpan(const std::string &text, const std::string &href,
123 bool hasHref, bool isMarkdown)
124{
125 if (isMarkdown)
126 return hasHref ? "[" + text + "](" + href + ")" : text;
127 if (hasHref)
128 return "<a href=\"" + escapeHtml(href) + "\">" + escapeHtml(text) + "</a>";
129 return escapeHtml(text);
130}
131
132// Render a span subtree as native Markdown. Any span carrying an href — a
133// concept link, a linked type, an external reference — becomes a Markdown
134// link; every other role contributes its text and recurses into its children,
135// so structural roles (type, name, template-decl, the [signal]/[slot] tags)
136// stay plain text instead of HTML markup. Markdown-special characters in the
137// signature text are not escaped here; see the Markdown-first-class follow-up.
138static std::string renderSpanMarkdown(const nlohmann::json &s)
139{
140 const auto text = s.value("text", "");
141 const auto href = s.value("href", "");
142 const bool hasHref = s.contains("href") && !href.empty();
143 if (hasHref)
144 return renderLinkSpan(text, href, hasHref, /*isMarkdown=*/true);
145
146 std::string result = text;
147 if (s.contains("children") && s["children"].is_array()) {
148 for (const auto &c : s["children"])
149 result += renderSpanMarkdown(c);
150 }
151 return result;
152}
153
154static std::string renderSignatureSpans(const nlohmann::json &spans, const QString &format)
155{
156 if (!spans.is_array()) {
157 qWarning("render_signature_spans: expected JSON array, got %s",
158 spans.type_name());
159 return {};
160 }
161
162 const bool isMarkdown = format.contains("markdown"_L1, Qt::CaseInsensitive);
163
164 std::string result;
165 for (const auto &s : spans) {
166 if (isMarkdown) {
167 result += renderSpanMarkdown(s);
168 continue;
169 }
170 const auto role = s.value("role", "");
171 const auto text = s.value("text", "");
172 const bool hasHref = s.contains("href");
173 const auto href = s.value("href", "");
174
175 if (role == "extra") {
176 result += R"(<code class="details extra" translate="no">)";
177 if (s.contains("children") && s["children"].is_array()) {
178 for (const auto &c : s["children"]) {
179 if (c.value("role", "") == "external-ref")
180 result += "<a href=\"" + c.value("href", "") + "\">"
181 + escapeHtml(c.value("text", "")) + "</a>";
182 else
183 result += escapeHtml(c.value("text", ""));
184 }
185 } else {
186 result += escapeHtml(text);
187 }
188 result += "</code>";
189 } else if (role == "type") {
190 result += R"(<span class="type">)";
191 if (hasHref)
192 result += "<a href=\"" + href + "\">";
193 result += escapeHtml(text);
194 if (hasHref)
195 result += "</a>";
196 result += "</span>";
197 } else if (role == "name") {
198 result += R"(<span class="name">)";
199 if (hasHref)
200 result += "<a href=\"" + href + "\">";
201 result += escapeHtml(text);
202 if (hasHref)
203 result += "</a>";
204 result += "</span>";
205 } else if (role == "parameter") {
206 result += "<i>" + escapeHtml(text) + "</i>";
207 } else if (role == "external-ref") {
208 result += "<a href=\"" + href + "\">" + escapeHtml(text) + "</a>";
209 } else if (role == "template-decl") {
210 result += R"(<span class="template-decl">)";
211 result += escapeHtml(text);
212 if (s.contains("children") && s["children"].is_array()) {
213 for (const auto &c : s["children"]) {
214 const auto childRole = c.value("role", "");
215 const auto childText = c.value("text", "");
216 const bool childHasHref = c.contains("href");
217 const auto childHref = c.value("href", "");
218 if (childRole == "type") {
219 result += R"(<span class="type">)" + escapeHtml(childText)
220 + "</span>";
221 } else if (childRole == "link") {
222 result += renderLinkSpan(childText, childHref, childHasHref, isMarkdown);
223 } else {
224 result += escapeHtml(childText);
225 }
226 }
227 }
228 result += "</span>";
229 } else if (role == "link") {
230 result += renderLinkSpan(text, href, hasHref, isMarkdown);
231 } else {
232 result += escapeHtml(text);
233 }
234 }
235 return result;
236}
237
238// Inja has no recursive macros. Expose a depth-first sequence of opening and
239// closing events so templates can style arbitrarily nested inline content.
240static void appendInlineEvents(const nlohmann::json &inlines, nlohmann::json &events)
241{
242 for (const auto &item : inlines) {
243 auto event = item;
244 event.erase("children");
245 const auto children = item.find("children");
246 const bool hasChildren = children != item.end() && !children->empty();
247 if (hasChildren)
248 event["text"] = "";
249 event["closing"] = false;
250 events.push_back(event);
251 if (hasChildren)
252 appendInlineEvents(*children, events);
253 event["closing"] = true;
254 events.push_back(std::move(event));
255 }
256}
257
258static void registerCallbacks(inja::Environment &env, const QString &format)
259{
260 env.add_callback("escape_html", 1, [](inja::Arguments &args) {
261 return escapeHtml(args.at(0)->get<std::string>());
262 });
263
264 env.add_callback("render_signature_spans", 1, [format](inja::Arguments &args) {
265 return renderSignatureSpans(*args.at(0), format);
266 });
267
268 env.add_callback("inline_events", 1, [](inja::Arguments &args) {
269 auto events = nlohmann::json::array();
270 appendInlineEvents(*args.at(0), events);
271 return events;
272 });
273
274 // English-list punctuation for templates that iterate over a list of
275 // items. Emit {{ list_separator(loop.index, length(items)) }} after
276 // each item instead of a literal comma or period so the rendered
277 // output matches the legacy HTML generator's prose (for instance
278 // "See also a(), b(), and c." rather than a comma-less concatenation).
279 // loop.index is zero-based in Inja; TextUtils::separator expects the
280 // same convention.
281 env.add_callback("list_separator", 2, [](inja::Arguments &args) {
282 const auto pos = args.at(0)->get<qsizetype>();
283 const auto total = args.at(1)->get<qsizetype>();
284 return TextUtils::separator(pos, total).toStdString();
285 });
286
287 env.add_callback("escape_md_table", 1, [](inja::Arguments &args) {
288 auto input = args.at(0)->get<std::string>();
289 std::string buffer;
290 buffer.reserve(input.size() + input.size() / 8);
291 for (char c : input) {
292 switch (c) {
293 case '|':
294 buffer += "\\|";
295 break;
296 case '\n':
297 buffer += ' ';
298 break;
299 case '\r':
300 break;
301 default:
302 buffer += c;
303 break;
304 }
305 }
306 return buffer;
307 });
308
309 // Parity helper for alternating-row table styling. Templates use
310 // {{ is_odd(loop.index1) }} to choose between "odd" and "even"
311 // class names, matching the legacy HtmlGenerator's tr.odd / tr.even
312 // contract. Implemented as a callback rather than relying on Inja's
313 // expression grammar so the parity check is unambiguous regardless
314 // of which arithmetic operators Inja supports in any given release.
315 env.add_callback("is_odd", 1, [](inja::Arguments &args) {
316 return args.at(0)->get<qsizetype>() % 2 != 0;
317 });
318}
319
320/*!
321 \class InjaBridge
322 \brief Adapter for converting Qt JSON types to Inja template engine format.
323
324 InjaBridge provides static methods to convert between Qt's native JSON types
325 (QJsonObject, QJsonArray, QJsonValue) and nlohmann::json, which is the data
326 format expected by the Inja template engine.
327
328 This adapter allows QDoc to maintain its Qt-native API while leveraging
329 Inja for template-based documentation generation. All JSON data in QDoc's
330 intermediate representation (IR) uses Qt types, and InjaBridge handles the
331 conversion when rendering templates.
332
333 \note All numbers in QJsonValue are stored as doubles. Whole-number doubles
334 (e.g., 30.0, 2.0) are converted to int64_t so that template output renders
335 them as integers (e.g., "30" not "30.0"). Fractional values pass through
336 as doubles.
337
338 \note Inja and nlohmann::json may report template or data errors, such as
339 a user template accessing an IR field that a given page does not carry.
340 With exceptions, the render methods return a RenderFailure so the caller
341 can report the error and continue with later pages. Without exceptions,
342 both libraries' error-reporting entry points terminate the run with the
343 same contextual diagnostic.
344
345 All render methods register template callbacks:
346 \list
347 \li \c{escape_html()} escapes HTML special characters (\c{&}, \c{<},
348 \c{>}, \c{"}, \c{'}).
349 \li \c{escape_md_table()} escapes pipe characters and collapses newlines
350 for safe use inside Markdown table cells.
351 \li \c{render_signature_spans()} converts a JSON array of signature spans
352 (from SignatureSpan IR) into semantic HTML with role-based markup
353 (\c{<span class="type">}, \c{<span class="name">}, etc.).
354 \li \c{inline_events()} traverses inline content in depth-first order.
355 Each item has opening and closing events, distinguished by
356 \c{closing}. Container text is empty; its children supply the text.
357 Templates choose the markup for each event.
358 \endlist
359 Escaping callbacks keep format-specific logic under template author control.
360 The \c{render_signature_spans()} callback centralizes signature rendering
361 that was previously duplicated across multiple templates.
362
363 \sa QJsonObject, QJsonArray, QJsonValue
364*/
365
366/*!
367 \struct InjaBridge::RenderContext
368 \brief Identifies the render a template error belongs to.
369
370 A \c RenderContext carries the \c format, \c page, and
371 \c templatePath of one render call.
372*/
373
374/*!
375 \variable InjaBridge::RenderContext::format
376 \brief The output format being rendered.
377*/
378
379/*!
380 \variable InjaBridge::RenderContext::page
381 \brief The output file name of the page being rendered.
382*/
383
384/*!
385 \variable InjaBridge::RenderContext::templatePath
386 \brief The location the template was loaded from.
387
388 This is the absolute path of an override in the configured template
389 directory or the Qt resource path of a built-in template.
390*/
391
392/*!
393 \struct InjaBridge::RenderFailure
394 \brief Carries the error reported by the template engine.
395*/
396
397/*!
398 \variable InjaBridge::RenderFailure::message
399 \brief The error message reported by the template engine.
400*/
401
402/*!
403 \typedef InjaBridge::RenderResult
404 \brief A rendered string or a template render failure.
405
406 An empty string is a successful result.
407*/
408
409/*!
410 \brief Converts a QJsonValue, \a value, to nlohmann::json.
411
412 Handles all QJsonValue types: Null, Bool, Double, String, Array, Object,
413 and Undefined. Undefined values are treated as null.
414
415 Returns the equivalent nlohmann::json representation.
416*/
417nlohmann::json InjaBridge::toInjaJson(const QJsonValue &value)
418{
419 switch (value.type()) {
420 case QJsonValue::Null:
421 return nullptr;
422 case QJsonValue::Bool:
423 return value.toBool();
424 case QJsonValue::Double: {
425 double d = value.toDouble();
426 if (std::fmod(d, 1.0) == 0.0)
427 return static_cast<int64_t>(d);
428 return d;
429 }
430 case QJsonValue::String:
431 return value.toString().toUtf8().toStdString();
432 case QJsonValue::Array:
433 return toInjaJson(value.toArray());
434 case QJsonValue::Object:
435 return toInjaJson(value.toObject());
436 case QJsonValue::Undefined:
437 return nullptr;
438 }
439 return nullptr;
440}
441
442/*!
443 \brief Converts a QJsonObject, \a obj, to nlohmann::json.
444
445 Recursively converts all values in the object, preserving the key-value
446 structure. Nested objects and arrays are handled correctly.
447
448 Returns the equivalent nlohmann::json object.
449*/
450nlohmann::json InjaBridge::toInjaJson(const QJsonObject &obj)
451{
452 nlohmann::json result = nlohmann::json::object();
453
454 for (const auto &[key, value] : obj.asKeyValueRange())
455 result[key.toString().toUtf8().toStdString()] = toInjaJson(value);
456
457 return result;
458}
459
460/*!
461 \brief Converts a QJsonArray, \a array, to nlohmann::json.
462
463 Recursively converts all elements in the array, preserving order.
464 Mixed-type arrays are supported.
465
466 Returns the equivalent nlohmann::json array.
467*/
468nlohmann::json InjaBridge::toInjaJson(const QJsonArray &array)
469{
470 nlohmann::json result = nlohmann::json::array();
471
472 for (const QJsonValue &value : array)
473 result.push_back(toInjaJson(value));
474
475 return result;
476}
477
478/*!
479 \brief Renders a template string, \a templateStr, with provided \a data.
480
481 Uses Inja to render the template with the given JSON data. The data
482 is automatically converted from QJsonObject to nlohmann::json.
483
484 The Inja template string, \a templateStr, supports Jinja2 syntax. \a data is
485 the JSON data to use for rendering. \a context identifies the render for
486 error reporting; see \l RenderContext.
487
488 Returns the rendered template or a render failure.
489*/
490InjaBridge::RenderResult InjaBridge::render(const QString &templateStr, const QJsonObject &data,
491 const RenderContext &context)
492{
493 auto render = [&] {
494 inja::Environment env;
495 // Replace Inja's default "##" line statement prefix, which conflicts
496 // with Markdown headings. "%!" echoes Jinja2's "%" (statement) and
497 // QDoc's "!" (documentation marker), and is inert in both HTML and
498 // Markdown.
499 env.set_line_statement("%!");
500 env.set_trim_blocks(true);
501 env.set_lstrip_blocks(true);
502 registerCallbacks(env, context.format);
503 nlohmann::json jsonData = toInjaJson(data);
504 std::string templateUtf8 = templateStr.toUtf8().toStdString();
505 return QString::fromUtf8(env.render(templateUtf8, jsonData).c_str());
506 };
507 return renderWithPolicy(context, render);
508}
509
510/*!
511 \brief Renders a template string, \a templateStr, with provided \a data,
512 using \a includeCallback to resolve \c{{% include %}} directives.
513
514 This overload configures the Inja environment with a custom include
515 callback so that templates can use \c{{% include "name" %}} directives.
516 The \a includeCallback receives the include name and returns the partial's
517 content. An empty string is a valid partial; no value means the include
518 wasn't found and reports a render failure.
519
520 This enables Inja's include mechanism to work with Qt's resource system,
521 where \c{std::ifstream} cannot open \c{:/} paths.
522
523 \a context identifies the render for error reporting; see \l RenderContext.
524
525 Returns the rendered template or a render failure.
526*/
527InjaBridge::RenderResult InjaBridge::render(const QString &templateStr, const QJsonObject &data,
528 const IncludeCallback &includeCallback,
529 const RenderContext &context)
530{
531 auto render = [&] {
532 inja::Environment env;
533 env.set_line_statement("%!");
534 env.set_trim_blocks(true);
535 env.set_lstrip_blocks(true);
536 registerCallbacks(env, context.format);
537 env.set_search_included_templates_in_files(false);
538 env.set_include_callback(
539 [&includeCallback, &env](const std::filesystem::path & /*path*/,
540 const std::string &name) -> inja::Template {
541 const auto content = includeCallback(QString::fromStdString(name));
542 if (!content)
543 INJA_THROW(inja::FileError("include not found: '" + name + "'"));
544 return env.parse(content->toUtf8().toStdString());
545 });
546
547 nlohmann::json jsonData = toInjaJson(data);
548 std::string templateUtf8 = templateStr.toUtf8().toStdString();
549 return QString::fromUtf8(env.render(templateUtf8, jsonData).c_str());
550 };
551 return renderWithPolicy(context, render);
552}
553
554/*!
555 \brief Renders a template file with provided data.
556
557 Loads and renders a template from the filesystem, using \a templatePath
558 which holds the absolute path to the template file. The file should use
559 Inja/Jinja2 syntax. \a data is the JSON data to use for rendering.
560
561 \a context identifies the render for error reporting; see \l RenderContext.
562
563 Returns the rendered template or a render failure.
564*/
565InjaBridge::RenderResult InjaBridge::renderFile(const QString &templatePath,
566 const QJsonObject &data,
567 const RenderContext &context)
568{
569 auto render = [&] {
570 inja::Environment env;
571 env.set_line_statement("%!");
572 env.set_trim_blocks(true);
573 env.set_lstrip_blocks(true);
574 registerCallbacks(env, context.format);
575 nlohmann::json jsonData = toInjaJson(data);
576 std::string pathUtf8 = templatePath.toUtf8().toStdString();
577 return QString::fromUtf8(env.render_file(pathUtf8, jsonData).c_str());
578 };
579 return renderWithPolicy(context, render);
580}
581
582QT_END_NAMESPACE
static std::string renderSignatureSpans(const nlohmann::json &spans, const QString &format)
static void appendInlineEvents(const nlohmann::json &inlines, nlohmann::json &events)
static std::string escapeHtml(const std::string &input)
static void registerCallbacks(inja::Environment &env, const QString &format)
static InjaBridge::RenderResult renderWithPolicy(const InjaBridge::RenderContext &context, const std::function< QString()> &render)
static std::string renderSpanMarkdown(const nlohmann::json &s)
static std::string renderLinkSpan(const std::string &text, const std::string &href, bool hasHref, bool isMarkdown)
#define QDOC_TEMPLATE_LIBS_THROW
Definition injabridge.h:13