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
contentbuilder.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
7#include "sorting.h"
8
9#include "../atom.h"
10#include "../tree.h"
11
13
14using namespace Qt::Literals::StringLiterals;
15
16static QString stripCodeMarkerTags(const QString &markedCode)
17{
18 static const QRegularExpression tag(u"</?@[^>]*>"_s);
19 QString t = markedCode;
20 t.replace(tag, QString());
21 t.replace(u"&quot;"_s, u"\""_s);
22 t.replace(u"&gt;"_s, u">"_s);
23 t.replace(u"&lt;"_s, u"<"_s);
24 t.replace(u"&amp;"_s, u"&"_s);
25 return t;
26}
27
28static QString genusToString(Genus genus)
29{
30 switch (genus) {
31 case Genus::CPP: return u"cpp"_s;
32 case Genus::QML: return u"qml"_s;
33 case Genus::DOC: return u"doc"_s;
34 case Genus::API: return u"api"_s;
35 case Genus::DontCare: return {};
36 }
37 return {};
38}
39
41{
42 // DocParser is the only producer of Atom::AnnotatedList and
43 // Atom::GeneratedList, and both build them with at most two
44 // strings: the command argument at index 0 and the optional
45 // bracketed sort directive at index 1. Reading args.at(1) is
46 // therefore the sort slot, not "the last string."
47 const QStringList &args = atom->strings();
48 const QString directive = args.size() > 1 ? args.at(1) : QString();
49 return Sorting::parseSortOrder(directive) == Qt::DescendingOrder
50 ? u"descending"_s : u"ascending"_s;
51}
52
53namespace IR {
54
55/*!
56 \class IR::ContentBuilder
57 \internal
58 \brief Converts Atom chains to QList<IR::ContentBlock> trees.
59
60 ContentBuilder walks a linked list of Atom nodes (QDoc's internal
61 documentation representation) and produces a structured tree of
62 ContentBlock and InlineContent values suitable for template rendering.
63
64 Handled atom types:
65 \list
66 \li ParaLeft, ParaRight -- Paragraph blocks.
67 \li String -- Text inline content.
68 \li C -- Inline code spans.
69 \li Code, CodeBad, Qml -- Code blocks with language attribute.
70 \li SectionLeft, SectionRight -- Section containers.
71 \li SectionHeadingLeft, SectionHeadingRight -- Section headings with
72 level.
73 \li FormattingLeft, FormattingRight -- Bold, italic, teletype,
74 underline, subscript, superscript, parameter, uicontrol, trademark,
75 link, index, notranslate, span.
76 \li ListLeft, ListRight -- Ordered and unordered lists.
77 \li ListItemLeft, ListItemRight -- List items.
78 \li ListItemNumber -- List start number metadata.
79 \li NoteLeft, NoteRight -- Note admonition blocks.
80 \li WarningLeft, WarningRight -- Warning admonition blocks.
81 \li ImportantLeft, ImportantRight -- Important admonition blocks.
82 \li BriefLeft, BriefRight -- Brief exclusion (skipped by default,
83 or emitted as Paragraph with BriefHandling::Include).
84 \li Link, NavLink -- Explicit links with unresolved target.
85 \li AutoLink, NavAutoLink -- Auto-linked type names with unresolved
86 target.
87 \li BR -- Line break inline.
88 \li HR -- Horizontal rule block.
89 \li Nop -- No-operation (skipped).
90 \li BaseName -- No-operation (skipped).
91 \li TableLeft, TableRight -- Table containers with style attribute.
92 \li TableHeaderLeft, TableHeaderRight -- Table header rows.
93 \li TableRowLeft, TableRowRight -- Table data rows.
94 \li TableItemLeft, TableItemRight -- Table cells with optional
95 colspan/rowspan.
96 \li Image -- Block-level image (wrapping Paragraph with centerAlign).
97 \li InlineImage -- Inline image within a paragraph.
98 \li ImageText -- Alt text consumed by the preceding Image or
99 InlineImage handler.
100 \li CaptionLeft, CaptionRight -- Caption content as a Paragraph
101 block with a figCaption class attribute (the legacy HTML
102 figCaption semantics), typically following an Image.
103 \li ListTagLeft, ListTagRight -- Value list tag items (ListItem
104 blocks).
105 \li SinceTagLeft, SinceTagRight -- Version tag items (skipped).
106 \li AnnotatedList -- Typed ListPlaceholder block carrying a
107 \c{ListPlaceholderVariant} discriminator, the group
108 argument, and a parsed sort directive.
109 \li GeneratedList -- Typed ListPlaceholder block for the
110 recognized variants (annotatedexamples, annotatedclasses,
111 classes, classes \e {<rootname>}); a Div fallback retains
112 the legacy attribute bag for unknown variants.
113 \endlist
114
115 Format-conditional atoms (FormatIf, FormatElse, FormatEndif) are
116 skipped unconditionally. The template generator builds a
117 format-agnostic IR that serves all output formats from a single
118 build pass.
119
120 The optional BriefHandling parameter controls whether brief
121 content (between BriefLeft and BriefRight atoms) is included in
122 the output. The default is BriefHandling::Skip, which suppresses
123 brief content. BriefHandling::Include causes brief content to be
124 emitted as a Paragraph block.
125
126 ContentBuilder depends only on Atom (for reading the chain) and IR types
127 (for producing output).
128
129 \sa ContentBlock, InlineContent
130*/
131
132/*!
133 Constructs a ContentBuilder.
134
135 The \a briefHandling parameter controls whether content between
136 BriefLeft and BriefRight atoms is emitted as a Paragraph block
137 (BriefHandling::Include) or suppressed (BriefHandling::Skip).
138
139 The \a headingOffset parameter shifts section heading levels to
140 account for the page structure. QDoc's \\section1 maps to level 1,
141 but pages already use \c{<h1>} for the title and \c{<h2>} for
142 major sections. The legacy generators apply an offset derived from
143 the node type; callers pass that same offset here so the IR
144 produces correct heading levels without depending on \b Node.
145*/
146ContentBuilder::ContentBuilder(BriefHandling briefHandling, int headingOffset,
147 DiagnosticHandler diagnosticHandler)
148 : m_briefHandling(briefHandling), m_headingOffset(headingOffset),
150{
151}
152
153static InlineType formattingToInlineType(const QString &formatting)
154{
155 if (formatting == ATOM_FORMATTING_BOLD)
156 return InlineType::Bold;
157 if (formatting == ATOM_FORMATTING_ITALIC)
158 return InlineType::Italic;
159 if (formatting == ATOM_FORMATTING_TELETYPE)
161 if (formatting == ATOM_FORMATTING_UNDERLINE)
163 if (formatting == ATOM_FORMATTING_SUBSCRIPT)
165 if (formatting == ATOM_FORMATTING_SUPERSCRIPT)
167 if (formatting == ATOM_FORMATTING_PARAMETER)
169 return InlineType::Text;
170}
171
172/*!
173 Walks the atom chain starting at \a firstAtom and returns a list
174 of ContentBlock trees representing the structured documentation body.
175
176 Returns an empty list if \a firstAtom is \nullptr.
177
178 The builder is reset before processing, so a single ContentBuilder
179 instance can be reused for multiple build() calls.
180*/
182{
183 m_result.clear();
184 m_blockPath.clear();
185 m_inlinePath.clear();
186 m_inlineBaseDepths.clear();
187 m_inBrief = false;
188 m_inLink = false;
189
190 if (!firstAtom)
191 return {};
192
193 processAtoms(firstAtom);
194
195 // Malformed atom chain recovery: auto-close remaining blocks in
196 // release builds, assert in debug to surface the source error.
197 while (!m_blockPath.isEmpty())
198 closeBlock();
199 m_inlinePath.clear();
200 m_inlineBaseDepths.clear();
201 m_inLink = false;
202 m_inBrief = false;
203
204 return m_result;
205}
206
207/*!
208 Walks the full atom chain starting at \a atom, building the
209 content tree. FormatIf..FormatEndif blocks are skipped
210 unconditionally via skipFormatIfBlock(). Stray FormatElse and
211 FormatEndif atoms outside any FormatIf context are ignored.
212*/
213void ContentBuilder::processAtoms(const Atom *atom)
214{
215 while (atom) {
216 if (atom->type() == Atom::FormatIf) {
217 atom = skipFormatIfBlock(atom);
218 continue;
219 }
221 atom = atom->next();
222 continue;
223 }
224 atom = dispatchAtom(atom);
225 if (!atom)
226 return;
227 atom = atom->next();
228 }
229}
230
231/*!
232 Skips an entire FormatIf..FormatEndif block, including any nested
233 FormatIf blocks and FormatElse branches. The scan only tracks
234 FormatIf and FormatEndif for depth counting; all other atom types
235 (including FormatElse) are treated as inert content and walked
236 past without dispatch.
237
238 The template generator builds a format-agnostic IR, so
239 format-conditional content is unconditionally excluded.
240
241 Returns a pointer to the atom after FormatEndif, or \nullptr if
242 the chain ends before FormatEndif is found.
243*/
244const Atom *ContentBuilder::skipFormatIfBlock(const Atom *atom)
245{
246 Q_ASSERT(atom->type() == Atom::FormatIf);
247 int depth = 1;
248 atom = atom->next();
249 while (atom && depth > 0) {
250 if (atom->type() == Atom::FormatIf)
251 ++depth;
252 else if (atom->type() == Atom::FormatEndif)
253 --depth;
254 atom = atom->next();
255 }
256 return atom;
257}
258
259/*!
260 Dispatches a single atom to the content model. Returns the last
261 atom consumed — usually \a atom itself, but some atom types may
262 consume subsequent atoms.
263*/
264const Atom *ContentBuilder::dispatchAtom(const Atom *atom)
265{
267 return atom->find(Atom::DeprecatedRight);
269 return atom;
270 if (atom->type() == Atom::BriefLeft) {
271 m_inBrief = true;
272 if (m_briefHandling == BriefHandling::Include)
273 openBlock(BlockType::Paragraph);
274 return atom;
275 }
276 if (atom->type() == Atom::BriefRight) {
277 if (m_briefHandling == BriefHandling::Include)
278 closeBlock();
279 m_inBrief = false;
280 return atom;
281 }
282 if (m_inBrief && m_briefHandling != BriefHandling::Include)
283 return atom;
284
285 switch (atom->type()) {
286
287 case Atom::ParaLeft:
288 openBlock(BlockType::Paragraph);
289 break;
290
291 case Atom::ParaRight:
292 closeBlock();
293 break;
294
295 case Atom::String:
296 addLeafInline(InlineType::Text, atom->string());
297 break;
298
299 case Atom::C:
300 addLeafInline(InlineType::Code, stripCodeMarkerTags(atom->string()));
301 break;
302
303 case Atom::Code:
304 case Atom::CodeBad:
305 case Atom::Qml: {
306 QJsonObject attrs;
307 if (atom->type() == Atom::Qml) {
308 attrs["language"_L1] = u"qml"_s;
309 } else if (atom->type() == Atom::CodeBad) {
310 attrs["language"_L1] = u"text"_s;
311 attrs["bad"_L1] = true;
312 } else if (atom->count() >= 2 && !atom->string(1).isEmpty()) {
313 attrs["language"_L1] = atom->string(1);
314 } else {
315 attrs["language"_L1] = u"cpp"_s;
316 }
317
318 openBlock(BlockType::CodeBlock, attrs);
319 addLeafInline(InlineType::Text, stripCodeMarkerTags(atom->string()));
320 closeBlock();
321 break;
322 }
323
324 case Atom::AutoLink:
325 case Atom::NavAutoLink: {
326 // href values are not author-controlled. They are produced by QDoc
327 // link resolution (\l, autolinks) against the node tree, or by
328 // \image path handling. They don't contain arbitrary schemes (e.g.
329 // javascript:). Only link text originates from user-authored docs
330 // and must be HTML-escaped in templates.
331 InlineContent link;
333 link.href = atom->string();
335 if (atom->isLinkAtom()) {
336 const auto *linkAtom = static_cast<const LinkAtom *>(atom);
337 link.link->sourceLocation = InlineContent::SourceLocation{
338 linkAtom->location.filePath(),
339 linkAtom->location.lineNo()
340 };
341 }
342 link.children.append({ InlineType::Text, atom->string(), {}, {}, {}, {}, {} });
343 addInline(std::move(link));
344 break;
345 }
346
347 case Atom::Link:
348 case Atom::NavLink: {
349 if (m_blockPath.isEmpty())
350 openBlock(BlockType::Paragraph);
351
352 m_inLink = true;
353
354 InlineContent link;
356 link.href = atom->string();
358
359 if (atom->isLinkAtom()) {
360 // genus() and domain() are non-const but non-mutating;
361 // the same const_cast pattern is used in qdocdatabase.cpp.
362 auto *mutableAtom = const_cast<Atom *>(atom);
363 Genus genus = mutableAtom->genus();
364 QString genusStr = genusToString(genus);
365 if (!genusStr.isEmpty())
366 link.attributes["linkGenus"_L1] = genusStr;
367 if (Tree *domain = mutableAtom->domain())
368 link.attributes["linkModule"_L1] = domain->physicalModuleName();
369 if (int flags = mutableAtom->flags())
370 link.attributes["linkFlags"_L1] = flags;
371
372 const auto *linkAtom = static_cast<const LinkAtom *>(mutableAtom);
373 link.link->sourceLocation = InlineContent::SourceLocation{
374 linkAtom->location.filePath(),
375 linkAtom->location.lineNo()
376 };
377 }
378
379 pushInlineContainer(std::move(link));
380
381 // Link atoms are always followed by FormattingLeft("link");
382 // skip it to avoid double-processing.
384 && atom->next()->string() == ATOM_FORMATTING_LINK) {
385 return atom->next();
386 }
387 break;
388 }
389
391 const QString &fmt = atom->string();
392
393 if (fmt == ATOM_FORMATTING_INDEX || fmt.startsWith(u"span "_s))
394 break;
395
396 if (fmt == ATOM_FORMATTING_LINK)
397 break;
398
400 break;
401
402 if (fmt == ATOM_FORMATTING_UICONTROL) {
403 InlineContent bold;
405 pushInlineContainer(std::move(bold));
406 break;
407 }
408
409 InlineType type = formattingToInlineType(fmt);
410 if (type == InlineType::Text)
411 break;
412
413 InlineContent container;
414 container.type = type;
415 pushInlineContainer(std::move(container));
416 break;
417 }
418
420 const QString &fmt = atom->string();
421
422 if (fmt == ATOM_FORMATTING_LINK) {
423 if (m_inLink) {
424 const qsizetype base = m_inlineBaseDepths.isEmpty() ? 0 : m_inlineBaseDepths.last();
425 if (m_inlinePath.size() > base) {
426 Q_ASSERT(resolveInline()->type == InlineType::Link);
427 m_inlinePath.removeLast();
428 }
429 m_inLink = false;
430 }
431 break;
432 }
433
435 || fmt.startsWith(u"span "_s) || fmt == ATOM_FORMATTING_TRADEMARK) {
436 break;
437 }
438
439 const qsizetype base = m_inlineBaseDepths.isEmpty() ? 0 : m_inlineBaseDepths.last();
440 if (m_inlinePath.size() > base)
441 m_inlinePath.removeLast();
442 break;
443 }
444
445 case Atom::SectionLeft:
446 openBlock(BlockType::Section);
447 break;
448
450 closeBlock();
451 break;
452
454 QJsonObject attrs;
455 attrs["level"_L1] = atom->string().toInt() + m_headingOffset;
456 // SectionHeadingLeft carries the heading level at string(0) and the
457 // anchor identifier at string(1). The second payload is populated
458 // only when a heading-level macro (\sectionN) emits an explicit ref.
459 if (atom->count() >= 2)
460 attrs["sectionRef"_L1] = atom->string(1);
461 openBlock(BlockType::SectionHeading, attrs);
462 break;
463 }
464
466 closeBlock();
467 break;
468
469 case Atom::ListLeft: {
470 QJsonObject attrs;
471 const QString &listType = atom->string();
472 attrs["listType"_L1] = listType;
473 if (listType == ATOM_LIST_TAG || listType == ATOM_LIST_VALUE)
474 openBlock(BlockType::DefinitionList, attrs);
475 else
476 openBlock(BlockType::List, attrs);
477 break;
478 }
479
480 case Atom::ListRight:
481 closeBlock();
482 break;
483
484 case Atom::ListItemLeft: {
485 ContentBlock *parent = resolveBlock();
486 if (parent->type == BlockType::DefinitionList)
487 openBlock(BlockType::DefinitionDescription);
488 else
489 openBlock(BlockType::ListItem);
490 break;
491 }
492
494 closeBlock();
495 break;
496
498 // Start-number metadata is not yet represented in the IR.
499 break;
500
501 case Atom::NoteLeft:
502 openBlock(BlockType::Note);
503 break;
504
505 case Atom::NoteRight:
506 closeBlock();
507 break;
508
509 case Atom::WarningLeft:
510 openBlock(BlockType::Warning);
511 break;
512
514 closeBlock();
515 break;
516
517 case Atom::ImportantLeft:
518 openBlock(BlockType::Important);
519 break;
520
522 closeBlock();
523 break;
524
525 case Atom::BR:
526 addLeafInline(InlineType::LineBreak, {});
527 break;
528
529 case Atom::HR:
530 openBlock(BlockType::HorizontalRule);
531 closeBlock();
532 break;
533
534 case Atom::AnnotatedList: {
535 QJsonObject attrs;
536 attrs["variant"_L1] = toString(ListPlaceholderVariant::AnnotatedGroup);
537 attrs["argument"_L1] = atom->string();
538 attrs["sort"_L1] = placeholderSortAttribute(atom);
539 openBlock(BlockType::ListPlaceholder, attrs);
540 closeBlock();
541 break;
542 }
543
544 case Atom::GeneratedList: {
545 const QString arg = atom->string();
546 QJsonObject attrs;
547 attrs["argument"_L1] = arg;
548 attrs["sort"_L1] = placeholderSortAttribute(atom);
549
550 static constexpr auto classesPrefix = "classes "_L1;
551 if (arg == "annotatedexamples"_L1) {
552 attrs["variant"_L1] = toString(ListPlaceholderVariant::AnnotatedExamples);
553 } else if (arg == "annotatedclasses"_L1) {
554 attrs["variant"_L1] = toString(ListPlaceholderVariant::AnnotatedClasses);
555 } else if (arg == "classes"_L1 || arg.startsWith(classesPrefix)) {
556 attrs["variant"_L1] = toString(ListPlaceholderVariant::CompactClasses);
557 if (arg.startsWith(classesPrefix)) {
558 const QString rootName = arg.sliced(classesPrefix.size()).trimmed();
559 if (!rootName.isEmpty())
560 attrs["rootName"_L1] = rootName;
561 }
562 } else {
563 // Unknown \generatelist variant: keep the legacy attribute-bag
564 // Div so deferred variants continue to render as they do today.
565 // Remove this branch when those variants acquire their own
566 // ListPlaceholderVariant entries in a follow-up phase.
567 QJsonObject fallback;
568 fallback["generatedList"_L1] = arg;
569 openBlock(BlockType::Div, fallback);
570 closeBlock();
571 break;
572 }
573
574 openBlock(BlockType::ListPlaceholder, attrs);
575 closeBlock();
576 break;
577 }
578
579 case Atom::TableLeft: {
580 QJsonObject attrs;
581 QString tableStyle = u"generic"_s;
582 QString width;
583
584 for (int i = 0; i < atom->count(); ++i) {
585 const QString &arg = atom->string(i);
586 if (arg == "borderless"_L1)
587 tableStyle = arg;
588 else if (arg.contains('%'_L1))
589 width = arg;
590 }
591
592 // Handle "100 %" (space before percent) — the percent arrives
593 // as a separate atom argument, reconstruct the width value.
594 if (width == "%"_L1) {
595 bool ok = false;
596 int pct = atom->string(0).toInt(&ok);
597 width = ok ? QString::number(pct) + '%'_L1 : QString();
598 }
599
600 attrs["style"_L1] = tableStyle;
601 if (!width.isEmpty())
602 attrs["width"_L1] = width;
603 openBlock(BlockType::Table, attrs);
604 break;
605 }
606
607 case Atom::TableRight:
608 closeBlock();
609 break;
610
611 case Atom::TableHeaderLeft:
612 openBlock(BlockType::TableHeaderRow);
613 break;
614
616 closeBlock();
617 break;
618
619 case Atom::TableRowLeft:
620 openBlock(BlockType::TableRow);
621 break;
622
624 closeBlock();
625 break;
626
627 case Atom::TableItemLeft: {
628 QJsonObject attrs;
629 const QString &spec = atom->string();
630 if (!spec.isEmpty()) {
631 const auto parts = QStringView{spec}.split(u',');
632 if (parts.size() >= 2) {
633 int colspan = qMax(1, parts[0].toInt());
634 int rowspan = qMax(1, parts[1].toInt());
635 if (colspan > 1)
636 attrs["colspan"_L1] = colspan;
637 if (rowspan > 1)
638 attrs["rowspan"_L1] = rowspan;
639 }
640 }
641 openBlock(BlockType::TableCell, attrs);
642 break;
643 }
644
646 closeBlock();
647 break;
648
649 case Atom::ListTagLeft:
650 openBlock(BlockType::DefinitionTerm);
651 break;
652
654 closeBlock();
655 break;
656
657 case Atom::Image: {
658 QJsonObject attrs;
659 attrs["class"_L1] = u"centerAlign"_s;
660 openBlock(BlockType::Paragraph, attrs);
661
662 InlineContent img;
664 img.href = atom->string();
665 if (atom->next() && atom->next()->type() == Atom::ImageText)
666 img.title = atom->next()->string();
667 addInline(std::move(img));
668
669 closeBlock();
670
671 if (atom->next() && atom->next()->type() == Atom::ImageText)
672 return atom->next();
673 break;
674 }
675
676 case Atom::InlineImage: {
677 if (Q_UNLIKELY(m_blockPath.isEmpty()))
678 break;
679
680 InlineContent img;
682 img.href = atom->string();
683 if (atom->next() && atom->next()->type() == Atom::ImageText)
684 img.title = atom->next()->string();
685 addInline(std::move(img));
686
687 if (atom->next() && atom->next()->type() == Atom::ImageText)
688 return atom->next();
689 break;
690 }
691
692 case Atom::ImageText:
693 break;
694
695 case Atom::CaptionLeft: {
696 QJsonObject attrs;
697 attrs["class"_L1] = u"figCaption"_s;
698 openBlock(BlockType::Paragraph, attrs);
699 break;
700 }
701
703 closeBlock();
704 break;
705
708 break;
709
710 case Atom::Nop:
711 case Atom::BaseName:
712 break;
713
714 default:
715 break;
716 }
717 return atom;
718}
719
720/*!
721 Opens a new block of type \a type with optional \a attrs.
722
723 If the block path is empty, the block is added to the top-level
724 result list. Otherwise it is added as a child of the current
725 container block.
726*/
727void ContentBuilder::openBlock(BlockType type, QJsonObject attrs)
728{
729 ContentBlock block;
730 block.type = type;
731 block.attributes = std::move(attrs);
732
733 m_inlineBaseDepths.append(m_inlinePath.size());
734
735 if (m_blockPath.isEmpty()) {
736 m_result.append(std::move(block));
737 m_blockPath.append(m_result.size() - 1);
738 } else {
739 auto *parent = resolveBlock();
740 parent->children.append(std::move(block));
741 m_blockPath.append(parent->children.size() - 1);
742 }
743}
744
745/*!
746 Closes the current block by popping it from the block path.
747
748 Verifies that the inline path depth matches the depth recorded
749 when this block was opened (all formatting pairs balanced).
750 In release builds, the inline path is restored to the expected
751 depth as a safety measure against malformed atom chains.
752*/
753void ContentBuilder::closeBlock()
754{
755 if (!m_blockPath.isEmpty()) {
756 if (Q_UNLIKELY(m_inlineBaseDepths.isEmpty())) {
757 m_inlinePath.clear();
758 m_blockPath.clear();
759 m_inlineBaseDepths.clear();
760 m_inLink = false;
761 return;
762 }
763 const qsizetype expectedDepth = m_inlineBaseDepths.last();
764 if (m_inLink && m_inlinePath.size() > expectedDepth)
765 m_inLink = false;
766 m_inlinePath.resize(expectedDepth);
767 m_inlinePath.resize(expectedDepth);
768 m_inlineBaseDepths.removeLast();
769 m_blockPath.removeLast();
770 }
771}
772
773/*!
774 Adds \a inline_ to the current block's inline content.
775
776 If there is an active inline container (from FormattingLeft or
777 Link atom), the inline is added to that container's children
778 instead.
779
780 If no block is open, the inline is dropped. This shouldn't happen
781 with well-formed atom chains (text is always wrapped in
782 ParaLeft/ParaRight), and is asserted in debug builds.
783*/
784void ContentBuilder::addInline(InlineContent inline_)
785{
786 if (!m_inlinePath.isEmpty()) {
787 resolveInline()->children.append(std::move(inline_));
788 } else if (!m_blockPath.isEmpty()) {
789 resolveBlock()->inlineContent.append(std::move(inline_));
790 } else {
791 if (m_diagnose)
792 m_diagnose(QtWarningMsg, u"Dropping inline content outside any block"_s);
793 }
794}
795
796/*!
797 Convenience method: creates a leaf InlineContent of the given
798 \a type with \a text and appends it via addInline().
799*/
800void ContentBuilder::addLeafInline(InlineType type, const QString &text)
801{
802 InlineContent ic;
803 ic.type = type;
804 ic.text = text;
805 addInline(std::move(ic));
806}
807
808/*!
809 Pushes \a container as a new inline container. Subsequent
810 addInline() and pushInlineContainer() calls will nest
811 their content inside this container.
812
813 Unlike addInline(), which only appends leaf inlines, this method
814 also updates m_inlinePath to enable nesting. It respects the
815 existing inline path: if we are already inside a Link or formatting
816 container, the new container is added as a child of that container.
817*/
818void ContentBuilder::pushInlineContainer(InlineContent container)
819{
820 if (!m_inlinePath.isEmpty()) {
821 auto *parent = resolveInline();
822 parent->children.append(std::move(container));
823 m_inlinePath.append(parent->children.size() - 1);
824 } else if (!m_blockPath.isEmpty()) {
825 auto *block = resolveBlock();
826 block->inlineContent.append(std::move(container));
827 m_inlinePath.append(block->inlineContent.size() - 1);
828 }
829}
830
831/*!
832 Resolves the current block path to a ContentBlock pointer.
833
834 The returned pointer is valid only until the next QList mutation
835 on any list in the path. Callers must use the pointer within a
836 single expression and discard it before appending to any QList.
837*/
838ContentBlock *ContentBuilder::resolveBlock()
839{
840 Q_ASSERT(!m_blockPath.isEmpty());
841 Q_ASSERT(m_blockPath[0] >= 0 && m_blockPath[0] < m_result.size());
842 ContentBlock *block = &m_result[m_blockPath[0]];
843 for (qsizetype i = 1; i < m_blockPath.size(); ++i) {
844 Q_ASSERT(m_blockPath[i] >= 0 && m_blockPath[i] < block->children.size());
845 block = &block->children[m_blockPath[i]];
846 }
847 return block;
848}
849
850/*!
851 Resolves the current inline path to an InlineContent pointer.
852
853 Walks the block path first (via resolveBlock()), then descends
854 through the block's inlineContent and nested children lists
855 using the indices in m_inlinePath.
856*/
857InlineContent *ContentBuilder::resolveInline()
858{
859 ContentBlock *block = resolveBlock();
860 Q_ASSERT(!m_inlinePath.isEmpty());
861 Q_ASSERT(m_inlinePath[0] >= 0 && m_inlinePath[0] < block->inlineContent.size());
862 InlineContent *ic = &block->inlineContent[m_inlinePath[0]];
863 for (qsizetype i = 1; i < m_inlinePath.size(); ++i) {
864 Q_ASSERT(m_inlinePath[i] >= 0 && m_inlinePath[i] < ic->children.size());
865 ic = &ic->children[m_inlinePath[i]];
866 }
867 return ic;
868}
869
870} // namespace IR
871
872QT_END_NAMESPACE
#define ATOM_FORMATTING_TELETYPE
Definition atom.h:206
#define ATOM_FORMATTING_UNDERLINE
Definition atom.h:209
#define ATOM_FORMATTING_NOTRANSLATE
Definition atom.h:201
#define ATOM_LIST_TAG
Definition atom.h:212
#define ATOM_FORMATTING_SUBSCRIPT
Definition atom.h:204
#define ATOM_FORMATTING_BOLD
Definition atom.h:197
#define ATOM_FORMATTING_TRADEMARK
Definition atom.h:207
#define ATOM_LIST_VALUE
Definition atom.h:213
#define ATOM_FORMATTING_ITALIC
Definition atom.h:199
#define ATOM_FORMATTING_LINK
Definition atom.h:200
#define ATOM_FORMATTING_SUPERSCRIPT
Definition atom.h:205
#define ATOM_FORMATTING_INDEX
Definition atom.h:198
#define ATOM_FORMATTING_UICONTROL
Definition atom.h:208
#define ATOM_FORMATTING_PARAMETER
Definition atom.h:202
The Atom class is the fundamental unit for representing documents internally.
Definition atom.h:19
AtomType type() const
Return the type of this atom.
Definition atom.h:146
@ CaptionLeft
Definition atom.h:29
@ TableRight
Definition atom.h:99
@ GeneratedList
Definition atom.h:54
@ BriefRight
Definition atom.h:27
@ TableHeaderRight
Definition atom.h:101
@ FormatElse
Definition atom.h:49
@ InlineImage
Definition atom.h:60
@ TableRowRight
Definition atom.h:103
@ Nop
Definition atom.h:76
@ WarningRight
Definition atom.h:113
@ ListTagRight
Definition atom.h:70
@ CaptionRight
Definition atom.h:30
@ NavLink
Definition atom.h:75
@ ListItemNumber
Definition atom.h:68
@ SinceTagRight
Definition atom.h:93
@ CodeBad
Definition atom.h:32
@ AnnotatedList
Definition atom.h:22
@ SectionRight
Definition atom.h:86
@ SectionHeadingLeft
Definition atom.h:87
@ TableLeft
Definition atom.h:98
@ ListItemRight
Definition atom.h:72
@ DeprecatedLeft
Definition atom.h:37
@ Image
Definition atom.h:56
@ TableItemRight
Definition atom.h:105
@ ListItemLeft
Definition atom.h:71
@ ImportantRight
Definition atom.h:59
@ Code
Definition atom.h:31
@ ListLeft
Definition atom.h:67
@ NavAutoLink
Definition atom.h:74
@ BriefLeft
Definition atom.h:26
@ ImageText
Definition atom.h:57
@ ListRight
Definition atom.h:73
@ ParaRight
Definition atom.h:80
@ Qml
Definition atom.h:81
@ FormattingLeft
Definition atom.h:52
@ FormattingRight
Definition atom.h:53
@ SectionHeadingRight
Definition atom.h:88
@ Link
Definition atom.h:65
@ FormatEndif
Definition atom.h:50
@ SinceTagLeft
Definition atom.h:92
@ AutoLink
Definition atom.h:23
@ DeprecatedRight
Definition atom.h:38
@ TableItemLeft
Definition atom.h:104
@ NoteRight
Definition atom.h:78
@ BaseName
Definition atom.h:24
@ FormatIf
Definition atom.h:51
virtual bool isLinkAtom() const
Definition atom.h:154
const Atom * next() const
Return the next atom in the atom list.
Definition atom.h:143
virtual Genus genus()
Definition atom.h:155
Converts Atom chains to QList<IR::ContentBlock> trees.
QList< ContentBlock > build(const Atom *firstAtom)
Walks the atom chain starting at firstAtom and returns a list of ContentBlock trees representing the ...
ContentBuilder(BriefHandling briefHandling=BriefHandling::Skip, int headingOffset=0, DiagnosticHandler diagnosticHandler={})
Constructs a ContentBuilder.
static QString genusToString(Genus genus)
static QString stripCodeMarkerTags(const QString &markedCode)
static QString placeholderSortAttribute(const Atom *atom)
Definition builder.cpp:14
LinkState
LinkOrigin
BriefHandling
BlockType
static InlineType formattingToInlineType(const QString &formatting)
InlineType
Combined button and popup list for selecting options.
Represents a structural block element in documentation.
LinkData(LinkOrigin o, LinkState s, std::optional< SourceLocation > loc=std::nullopt)
Represents inline content within a documentation block.