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
docparser.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#include "docparser.h"
4
5#include "codemarker.h"
6#include "doc.h"
7#include "docprivate.h"
8#include "editdistance.h"
9#include "macro.h"
10#include "openedlist.h"
11#include "tokenizer.h"
12
13#include <QtCore/qfile.h>
14#include <QtCore/qregularexpression.h>
15#include <QtCore/qtextstream.h>
16
17#include <cctype>
18#include <climits>
19#include <functional>
20
22
23using namespace Qt::StringLiterals;
24
25DocUtilities &DocParser::s_utilities = DocUtilities::instance();
26
27enum {
132};
133
134static struct
135{
136 const char *name;
137 int no;
138 bool is_formatting_command { false };
139} cmds[] = { { "a", CMD_A, true },
140 { "annotatedlist", CMD_ANNOTATEDLIST },
141 { "b", CMD_B, true },
142 { "badcode", CMD_BADCODE },
143 { "bold", CMD_BOLD, true },
144 { "br", CMD_BR },
145 { "brief", CMD_BRIEF },
146 { "c", CMD_C, true },
147 { "caption", CMD_CAPTION },
148 { "code", CMD_CODE },
149 { "codeline", CMD_CODELINE },
150 { "compareswith", CMD_COMPARESWITH },
151 { "details", CMD_DETAILS },
152 { "div", CMD_DIV },
153 { "dots", CMD_DOTS },
154 { "e", CMD_E, true },
155 { "else", CMD_ELSE },
156 { "endcode", CMD_ENDCODE },
157 { "endcompareswith", CMD_ENDCOMPARESWITH },
158 { "enddetails", CMD_ENDDETAILS },
159 { "enddiv", CMD_ENDDIV },
160 { "endfootnote", CMD_ENDFOOTNOTE },
161 { "endif", CMD_ENDIF },
162 { "endlegalese", CMD_ENDLEGALESE },
163 { "endlink", CMD_ENDLINK },
164 { "endlist", CMD_ENDLIST },
165 { "endmapref", CMD_ENDMAPREF },
166 { "endomit", CMD_ENDOMIT },
167 { "endquotation", CMD_ENDQUOTATION },
168 { "endraw", CMD_ENDRAW },
169 { "endsection1", CMD_ENDSECTION1 }, // ### don't document for now
170 { "endsection2", CMD_ENDSECTION2 }, // ### don't document for now
171 { "endsection3", CMD_ENDSECTION3 }, // ### don't document for now
172 { "endsection4", CMD_ENDSECTION4 }, // ### don't document for now
173 { "endsidebar", CMD_ENDSIDEBAR },
174 { "endtable", CMD_ENDTABLE },
175 { "footnote", CMD_FOOTNOTE },
176 { "generatelist", CMD_GENERATELIST },
177 { "header", CMD_HEADER },
178 { "hr", CMD_HR },
179 { "i", CMD_I, true },
180 { "if", CMD_IF },
181 { "image", CMD_IMAGE },
182 { "important", CMD_IMPORTANT },
183 { "include", CMD_INCLUDE },
184 { "inlineimage", CMD_INLINEIMAGE },
185 { "index", CMD_INDEX }, // ### don't document for now
186 { "input", CMD_INPUT },
187 { "keyword", CMD_KEYWORD },
188 { "l", CMD_L },
189 { "legalese", CMD_LEGALESE },
190 { "li", CMD_LI },
191 { "link", CMD_LINK },
192 { "list", CMD_LIST },
193 { "meta", CMD_META },
194 { "note", CMD_NOTE },
195 { "notranslate", CMD_NOTRANSLATE },
196 { "o", CMD_O },
197 { "omit", CMD_OMIT },
198 { "omitvalue", CMD_OMITVALUE },
199 { "overload", CMD_OVERLOAD },
200 { "printline", CMD_PRINTLINE },
201 { "printto", CMD_PRINTTO },
202 { "printuntil", CMD_PRINTUNTIL },
203 { "quotation", CMD_QUOTATION },
204 { "quotefile", CMD_QUOTEFILE },
205 { "quotefromfile", CMD_QUOTEFROMFILE },
206 { "raw", CMD_RAW },
207 { "row", CMD_ROW },
208 { "sa", CMD_SA },
209 { "section1", CMD_SECTION1 },
210 { "section2", CMD_SECTION2 },
211 { "section3", CMD_SECTION3 },
212 { "section4", CMD_SECTION4 },
213 { "sidebar", CMD_SIDEBAR },
214 { "sincelist", CMD_SINCELIST },
215 { "skipline", CMD_SKIPLINE },
216 { "skipto", CMD_SKIPTO },
217 { "skipuntil", CMD_SKIPUNTIL },
218 { "snippet", CMD_SNIPPET },
219 { "span", CMD_SPAN },
220 { "sub", CMD_SUB, true },
221 { "sup", CMD_SUP, true },
222 { "table", CMD_TABLE },
223 { "tableofcontents", CMD_TABLEOFCONTENTS },
224 { "target", CMD_TARGET },
225 { "title", CMD_TITLE },
226 { "tm", CMD_TM, true },
227 { "toc", CMD_TOC },
228 { "tocentry", CMD_TOCENTRY },
229 { "endtoc", CMD_ENDTOC },
230 { "tt", CMD_TT, true },
231 { "uicontrol", CMD_UICONTROL, true },
232 { "underline", CMD_UNDERLINE, true },
233 { "unicode", CMD_UNICODE },
234 { "value", CMD_VALUE },
235 { "warning", CMD_WARNING },
236 { "qml", CMD_QML },
237 { "endqml", CMD_ENDQML },
238 { "cpp", CMD_CPP },
239 { "endcpp", CMD_ENDCPP },
240 { "cpptext", CMD_CPPTEXT },
241 { "endcpptext", CMD_ENDCPPTEXT },
242 { nullptr, 0 } };
243
247bool DocParser::s_quoting = false;
248FileResolver *DocParser::file_resolver{ nullptr };
249static void processComparesWithCommand(DocPrivate *priv, const Location &location);
250
251/*!
252 Returns a cleaned version of the given \a link text. This replaces escaped
253 hash characters (\\#) with hash characters (#) and removes the URL scheme
254 prefix, if present.
255*/
256static QString cleanLink(const QString &link)
257{
258 qsizetype colonPos = link.indexOf(':');
259 QString cleaned{link};
260 cleaned.replace("\\#"_L1, "#"_L1);
261 if ((colonPos == -1) || (!link.startsWith("file:") && !link.startsWith("mailto:")))
262 return cleaned;
263 return cleaned.mid(colonPos + 1).simplified();
264}
265
266void DocParser::initialize(const Config &config, FileResolver &file_resolver)
267{
268 s_tabSize = config.get(CONFIG_TABSIZE).asInt();
269 s_allowedLanguages = config.get(CONFIG_CODELANGUAGES).asStringList();
270 s_ignoreWords = config.get(CONFIG_IGNOREWORDS).asStringList();
271
272 int i = 0;
273 while (cmds[i].name) {
274 s_utilities.cmdHash.insert(cmds[i].name, cmds[i].no);
275
276 if (cmds[i].no != i)
277 Location::internalError(QStringLiteral("command %1 missing").arg(i));
278 ++i;
279 }
280
281 // If any of the formats define quotinginformation, activate quoting
282 DocParser::s_quoting = config.get(CONFIG_QUOTINGINFORMATION).asBool();
283 const auto &outputFormats = config.getOutputFormats();
284 for (const auto &format : outputFormats)
285 DocParser::s_quoting = DocParser::s_quoting
286 || config.get(format + Config::dot + CONFIG_QUOTINGINFORMATION).asBool();
287
288 // KLUDGE: file_resolver is temporarily a pointer. See the
289 // comment for file_resolver in the header file for more context.
290 DocParser::file_resolver = &file_resolver;
291}
292
293/*!
294 Parse the \a source string to build a Text data structure
295 in \a docPrivate. The Text data structure is a linked list
296 of Atoms.
297
298 \a metaCommandSet is the set of metacommands that may be
299 found in \a source. These metacommands are not markup text
300 commands. They are topic commands and related metacommands.
301 */
302void DocParser::parse(const QString &source, DocPrivate *docPrivate,
303 const QSet<QString> &metaCommandSet, const QSet<QString> &possibleTopics)
304{
305 m_input = source;
306 m_position = 0;
307 m_inputLength = m_input.size();
308 m_cachedLocation = docPrivate->m_start_loc;
309 m_cachedPosition = 0;
310 m_private = docPrivate;
311 m_private->m_text << Atom::Nop;
312 m_private->m_topics.clear();
313
314 m_paragraphState = OutsideParagraph;
315 m_inTableHeader = false;
316 m_inTableRow = false;
317 m_inTableItem = false;
318 m_indexStartedParagraph = false;
319 m_pendingParagraphLeftType = Atom::Nop;
320 m_pendingParagraphRightType = Atom::Nop;
321
322 m_braceDepth = 0;
323 m_currentSection = Doc::NoSection;
324 m_openedCommands.push(CMD_OMIT);
325 m_quoter.reset();
326
327 CodeMarker *marker = nullptr;
328 Atom *currentLinkAtom = nullptr;
329 QString p1, p2;
330 QStack<bool> preprocessorSkipping;
331 int numPreprocessorSkipping = 0;
332
333 // The code language is set by commands that accept an optional language
334 // argument, such as \code, \snippet, \quotefile and \quotefromfile.
335 // It is also used by the \print* commands which require a value to have
336 // been set first for reasonable output. The language is lower case.
337 QString codeLanguage;
338
339 while (m_position < m_inputLength) {
340 QChar ch = m_input.at(m_position);
341
342 switch (ch.unicode()) {
343 case '\\': {
344 QString cmdStr;
345 m_backslashPosition = m_position;
346 ++m_position;
347 while (m_position < m_inputLength) {
348 ch = m_input.at(m_position);
349 if (ch.isLetterOrNumber()) {
350 cmdStr += ch;
351 ++m_position;
352 } else {
353 break;
354 }
355 }
356 m_endPosition = m_position;
357 if (cmdStr.isEmpty()) {
358 if (m_position < m_inputLength) {
359 QChar nextCh = m_input.at(m_position);
360 if (nextCh == '\\') {
361 appendEscapedIdentifier();
362 } else if (nextCh.isSpace()) {
363 enterPara();
364 skipAllSpaces();
365 appendChar(QLatin1Char(' '));
366 } else {
367 enterPara();
368 appendChar(m_input.at(m_position++));
369 }
370 }
371 } else {
372 // Ignore quoting atoms to make appendToCode()
373 // append to the correct atom.
374 if (!s_quoting || !isQuote(m_private->m_text.lastAtom()))
375 m_lastAtom = m_private->m_text.lastAtom();
376
377 int cmd = s_utilities.cmdHash.value(cmdStr, NOT_A_CMD);
378 switch (cmd) {
379 case CMD_A:
380 enterPara();
381 p1 = getArgument();
383 appendAtom(Atom(Atom::String, p1));
385 m_private->m_params.insert(p1);
386 break;
387 case CMD_BADCODE:
388 leavePara();
389 appendAtom(Atom(Atom::CodeBad,
390 getCode(CMD_BADCODE, marker, getMetaCommandArgument(cmdStr))));
391 break;
392 case CMD_BR:
393 enterPara();
394 appendAtom(Atom(Atom::BR));
395 break;
396 case CMD_BOLD:
397 location().warning(QStringLiteral("'\\bold' is deprecated. Use '\\b'"));
398 Q_FALLTHROUGH();
399 case CMD_B:
400 startFormat(ATOM_FORMATTING_BOLD, cmd);
401 break;
402 case CMD_BRIEF:
403 leavePara();
404 enterPara(Atom::BriefLeft, Atom::BriefRight);
405 break;
406 case CMD_C:
407 enterPara();
408 p1 = untabifyEtc(getArgument(ArgumentParsingOptions::Verbatim));
409 marker = CodeMarker::markerForCode(p1);
410 appendAtom(Atom(Atom::C, marker->markedUpCode(p1, nullptr, location())));
411 break;
412 case CMD_CAPTION:
413 leavePara();
414 enterPara(Atom::CaptionLeft, Atom::CaptionRight);
415 break;
416 case CMD_CODE:
417 // Only allow arguments on the same line as the command.
418 codeLanguage = getLanguageArgument(&marker);
419 leavePara();
420 // Store the code language in the atom, if specified, for
421 // the HTML and DocBook generators to use.
422 appendAtom(Atom(Atom::Code, getCode(CMD_CODE, marker, getMetaCommandArgument(cmdStr)), codeLanguage));
423 break;
424 case CMD_QML:
425 leavePara();
426 appendAtom(Atom(Atom::Qml,
427 getCode(CMD_QML, CodeMarker::markerForLanguage(QLatin1String("QML")),
428 getMetaCommandArgument(cmdStr))));
429 break;
430 case CMD_DETAILS:
431 leavePara();
432 appendAtom(Atom(Atom::DetailsLeft));
433 if (!isBlankLine()) {
434 if (isLeftBraceAhead()) {
435 enterPara(Atom::DetailsSummaryLeft, Atom::DetailsSummaryRight);
436 } else {
437 location().warning(u"Expected '{' when parsing \\%1 argument"_s.arg(cmdName(cmd)));
438 std::ignore = getRestOfLine();
439 }
440 }
441 m_openedCommands.push(cmd);
442 break;
443 case CMD_ENDDETAILS:
444 leavePara();
445 appendAtom(Atom(Atom::DetailsRight));
446 closeCommand(cmd);
447 break;
448 case CMD_DIV:
449 leavePara();
450 p1 = getArgument(ArgumentParsingOptions::Verbatim);
451 appendAtom(Atom(Atom::DivLeft, p1));
452 m_openedCommands.push(cmd);
453 break;
454 case CMD_ENDDIV:
455 leavePara();
456 appendAtom(Atom(Atom::DivRight));
457 closeCommand(cmd);
458 break;
459 case CMD_CODELINE:
460 if (s_quoting) {
461 appendAtom(Atom(Atom::CodeQuoteCommand, cmdStr));
462 appendAtom(Atom(Atom::CodeQuoteArgument, " "));
463 }
464 if (isCode(m_lastAtom) && m_lastAtom->string().endsWith("\n\n"))
465 m_lastAtom->chopString();
466 appendToCode("\n");
467 break;
468 case CMD_DOTS: {
469 QString arg = getOptionalArgument();
470 if (arg.isEmpty())
471 arg = "4";
472 if (s_quoting) {
473 appendAtom(Atom(Atom::CodeQuoteCommand, cmdStr));
474 appendAtom(Atom(Atom::CodeQuoteArgument, arg));
475 }
476 if (isCode(m_lastAtom) && m_lastAtom->string().endsWith("\n\n"))
477 m_lastAtom->chopString();
478
479 int indent = arg.toInt();
480 for (int i = 0; i < indent; ++i)
481 appendToCode(" ");
482 appendToCode("...\n");
483 break;
484 }
485 case CMD_ELSE:
486 if (!preprocessorSkipping.empty()) {
487 if (preprocessorSkipping.top()) {
488 --numPreprocessorSkipping;
489 } else {
490 ++numPreprocessorSkipping;
491 }
492 preprocessorSkipping.top() = !preprocessorSkipping.top();
493 (void)getRestOfLine(); // ### should ensure that it's empty
494 if (numPreprocessorSkipping)
495 skipToNextPreprocessorCommand();
496 } else {
497 location().warning(
498 QStringLiteral("Unexpected '\\%1'").arg(cmdName(CMD_ELSE)));
499 }
500 break;
501 case CMD_ENDCODE:
502 closeCommand(cmd);
503 break;
504 case CMD_ENDQML:
505 closeCommand(cmd);
506 break;
507 case CMD_ENDFOOTNOTE:
508 if (closeCommand(cmd)) {
509 leavePara();
510 appendAtom(Atom(Atom::FootnoteRight));
511 }
512 break;
513 case CMD_ENDIF:
514 if (preprocessorSkipping.size() > 0) {
515 if (preprocessorSkipping.pop())
516 --numPreprocessorSkipping;
517 (void)getRestOfLine(); // ### should ensure that it's empty
518 if (numPreprocessorSkipping)
519 skipToNextPreprocessorCommand();
520 } else {
521 location().warning(
522 QStringLiteral("Unexpected '\\%1'").arg(cmdName(CMD_ENDIF)));
523 }
524 break;
525 case CMD_ENDLEGALESE:
526 if (closeCommand(cmd)) {
527 leavePara();
528 appendAtom(Atom(Atom::LegaleseRight));
529 }
530 break;
531 case CMD_ENDLINK:
532 if (closeCommand(cmd)) {
534 && m_private->m_text.lastAtom()->string().endsWith(QLatin1Char(' ')))
537 }
538 break;
539 case CMD_ENDLIST:
540 if (closeCommand(cmd)) {
541 leavePara();
542 if (m_openedLists.top().isStarted()) {
543 appendAtom(Atom(Atom::ListItemRight, m_openedLists.top().styleString()));
544 appendAtom(Atom(Atom::ListRight, m_openedLists.top().styleString()));
545 }
546 m_openedLists.pop();
547 }
548 break;
549 case CMD_ENDOMIT:
550 closeCommand(cmd);
551 break;
552 case CMD_ENDQUOTATION:
553 if (closeCommand(cmd)) {
554 leavePara();
555 appendAtom(Atom(Atom::QuotationRight));
556 }
557 break;
558 case CMD_ENDRAW:
559 location().warning(
560 QStringLiteral("Unexpected '\\%1'").arg(cmdName(CMD_ENDRAW)));
561 break;
562 case CMD_ENDSECTION1:
563 endSection(Doc::Section1, cmd);
564 break;
565 case CMD_ENDSECTION2:
566 endSection(Doc::Section2, cmd);
567 break;
568 case CMD_ENDSECTION3:
569 endSection(Doc::Section3, cmd);
570 break;
571 case CMD_ENDSECTION4:
572 endSection(Doc::Section4, cmd);
573 break;
574 case CMD_ENDSIDEBAR:
575 if (closeCommand(cmd)) {
576 leavePara();
577 appendAtom(Atom(Atom::SidebarRight));
578 }
579 break;
580 case CMD_ENDTABLE:
581 if (closeCommand(cmd)) {
582 leaveTableRow();
583 appendAtom(Atom(Atom::TableRight));
584 }
585 break;
586 case CMD_FOOTNOTE:
587 if (openCommand(cmd)) {
588 enterPara();
589 appendAtom(Atom(Atom::FootnoteLeft));
590 }
591 break;
592 case CMD_ANNOTATEDLIST: {
593 // Optional sorting directive [ascending|descending]
594 if (isLeftBracketAhead())
595 p2 = getBracketedArgument();
596 else
597 p2.clear();
598 appendAtom(Atom(Atom::AnnotatedList, getArgument(), p2));
599 } break;
600 case CMD_SINCELIST:
601 leavePara();
602 appendAtom(Atom(Atom::SinceList, getRestOfLine().simplified()));
603 break;
604 case CMD_GENERATELIST: {
605 // Optional sorting directive [ascending|descending]
606 if (isLeftBracketAhead())
607 p2 = getBracketedArgument();
608 else
609 p2.clear();
610 QString arg1 = getArgument();
611 QString arg2 = getOptionalArgument();
612 if (!arg2.isEmpty())
613 arg1 += " " + arg2;
614 appendAtom(Atom(Atom::GeneratedList, arg1, p2));
615 } break;
616 case CMD_HEADER:
617 if (m_openedCommands.top() == CMD_TABLE) {
618 leaveTableRow();
619 appendAtom(Atom(Atom::TableHeaderLeft));
620 m_inTableHeader = true;
621 } else {
622 if (m_openedCommands.contains(CMD_TABLE))
623 location().warning(QStringLiteral("Cannot use '\\%1' within '\\%2'")
624 .arg(cmdName(CMD_HEADER),
625 cmdName(m_openedCommands.top())));
626 else
627 location().warning(
628 QStringLiteral("Cannot use '\\%1' outside of '\\%2'")
629 .arg(cmdName(CMD_HEADER), cmdName(CMD_TABLE)));
630 }
631 break;
632 case CMD_I:
633 location().warning(QStringLiteral(
634 "'\\i' is deprecated. Use '\\e' for italic or '\\li' for list item"));
635 Q_FALLTHROUGH();
636 case CMD_E:
637 startFormat(ATOM_FORMATTING_ITALIC, cmd);
638 break;
639 case CMD_HR:
640 leavePara();
641 appendAtom(Atom(Atom::HR));
642 break;
643 case CMD_IF:
644 preprocessorSkipping.push(!Tokenizer::isTrue(getRestOfLine()));
645 if (preprocessorSkipping.top())
646 ++numPreprocessorSkipping;
647 if (numPreprocessorSkipping)
648 skipToNextPreprocessorCommand();
649 break;
650 case CMD_IMAGE:
651 cmd_image(cmd);
652 break;
653 case CMD_IMPORTANT:
654 leavePara();
655 enterPara(Atom::ImportantLeft, Atom::ImportantRight);
656 break;
657 case CMD_INCLUDE:
658 case CMD_INPUT: {
659 QString fileName = getArgument();
660 QStringList parameters;
661 QString identifier;
662 if (isLeftBraceAhead()) {
663 identifier = getArgument();
664 while (isLeftBraceAhead() && parameters.size() < 9)
665 parameters << getArgument();
666 } else {
667 identifier = getRestOfLine();
668 }
669 include(fileName, identifier, parameters);
670 break;
671 }
672 case CMD_INLINEIMAGE:
673 cmd_image(cmd);
674 break;
675 case CMD_INDEX:
676 if (m_paragraphState == OutsideParagraph) {
677 enterPara();
678 m_indexStartedParagraph = true;
679 } else {
680 const Atom *last = m_private->m_text.lastAtom();
681 if (m_indexStartedParagraph
683 || last->string() != ATOM_FORMATTING_INDEX))
684 m_indexStartedParagraph = false;
685 }
686 startFormat(ATOM_FORMATTING_INDEX, cmd);
687 break;
688 case CMD_KEYWORD:
689 leavePara();
690 insertKeyword(getRestOfLine());
691 break;
692 case CMD_TOCENTRY:
693 if (m_openedCommands.top() != CMD_TOC) {
694 location().warning("Command '\\%1' outside of '\\%2'"_L1
695 .arg(cmdName(cmd), cmdName(CMD_TOC)));
696 break;
697 }
698 Q_FALLTHROUGH(); // \tocentry is functionally a link command
699 case CMD_L:
700 enterPara();
701 if (isLeftBracketAhead())
702 p2 = getBracketedArgument();
703
704 p1 = getArgument();
705
706 appendAtom(LinkAtom(p1, p2, location()));
707
708 if (isLeftBraceAhead()) {
709 currentLinkAtom = m_private->m_text.lastAtom();
710 startFormat(ATOM_FORMATTING_LINK, cmd);
711 } else {
713 appendAtom(Atom(Atom::String, cleanLink(p1)));
715 }
716
717 p2.clear();
718
719 break;
720 case CMD_LEGALESE:
721 leavePara();
722 if (openCommand(cmd))
723 appendAtom(Atom(Atom::LegaleseLeft));
724 docPrivate->m_hasLegalese = true;
725 break;
726 case CMD_LINK:
727 if (openCommand(cmd)) {
728 enterPara();
729 p1 = getArgument();
730 appendAtom(LinkAtom(p1, {}, location()));
732 skipSpacesOrOneEndl();
733 }
734 break;
735 case CMD_LIST:
736 if (openCommand(cmd)) {
737 leavePara();
738 m_openedLists.push(OpenedList(location(), getOptionalArgument()));
739 }
740 break;
741 case CMD_META:
742 m_private->constructExtra();
743 p1 = getArgument();
744 m_private->extra->m_metaMap.insert(p1, getArgument());
745 break;
746 case CMD_NOTE:
747 leavePara();
748 enterPara(Atom::NoteLeft, Atom::NoteRight);
749 break;
750 case CMD_NOTRANSLATE:
751 startFormat(ATOM_FORMATTING_NOTRANSLATE, cmd);
752 break;
753 case CMD_O:
754 location().warning(QStringLiteral("'\\o' is deprecated. Use '\\li'"));
755 Q_FALLTHROUGH();
756 case CMD_LI:
757 leavePara();
758 if (m_openedCommands.top() == CMD_LIST) {
759 if (m_openedLists.top().isStarted())
760 appendAtom(Atom(Atom::ListItemRight, m_openedLists.top().styleString()));
761 else
762 appendAtom(Atom(Atom::ListLeft, m_openedLists.top().styleString()));
763 m_openedLists.top().next();
764 appendAtom(Atom(Atom::ListItemNumber, m_openedLists.top().numberString()));
765 appendAtom(Atom(Atom::ListItemLeft, m_openedLists.top().styleString()));
766 enterPara();
767 } else if (m_openedCommands.top() == CMD_TABLE) {
768 p1 = "1,1";
769 p2.clear();
770 if (isLeftBraceAhead()) {
771 p1 = getArgument();
772 if (isLeftBraceAhead())
773 p2 = getArgument();
774 }
775
776 if (!m_inTableHeader && !m_inTableRow) {
777 location().warning(
778 QStringLiteral("Missing '\\%1' or '\\%2' before '\\%3'")
779 .arg(cmdName(CMD_HEADER), cmdName(CMD_ROW),
780 cmdName(CMD_LI)));
781 appendAtom(Atom(Atom::TableRowLeft));
782 m_inTableRow = true;
783 } else if (m_inTableItem) {
784 appendAtom(Atom(Atom::TableItemRight));
785 m_inTableItem = false;
786 }
787
788 appendAtom(Atom(Atom::TableItemLeft, p1, p2));
789 m_inTableItem = true;
790 } else
791 location().warning(
792 QStringLiteral("Command '\\%1' outside of '\\%2' and '\\%3'")
793 .arg(cmdName(cmd), cmdName(CMD_LIST), cmdName(CMD_TABLE)));
794 break;
795 case CMD_OMIT:
796 getUntilEnd(cmd);
797 break;
798 case CMD_OMITVALUE: {
799 leavePara();
800 p1 = getArgument();
801 if (!m_private->m_enumItemList.contains(p1))
802 m_private->m_enumItemList.append(p1);
803 if (!m_private->m_omitEnumItemList.contains(p1))
804 m_private->m_omitEnumItemList.append(p1);
805 skipSpacesOrOneEndl();
806 // Skip potential description paragraph
807 while (m_position < m_inputLength && !isBlankLine()) {
808 skipAllSpaces();
809 if (qsizetype pos = m_position; pos < m_input.size()
810 && m_input.at(pos++).unicode() == '\\') {
811 QString nextCmdStr;
812 while (pos < m_input.size() && m_input[pos].isLetterOrNumber())
813 nextCmdStr += m_input[pos++];
814 int nextCmd = s_utilities.cmdHash.value(cmdStr, NOT_A_CMD);
815 if (nextCmd == cmd || nextCmd == CMD_VALUE)
816 break;
817 }
818 getRestOfLine();
819 }
820 break;
821 }
822 case CMD_COMPARESWITH:
823 leavePara();
824 p1 = getRestOfLine();
825 if (openCommand(cmd))
826 appendAtom(Atom(Atom::ComparesLeft, p1));
827 break;
829 if (closeCommand(cmd)) {
830 leavePara();
831 appendAtom(Atom(Atom::ComparesRight));
832 processComparesWithCommand(m_private, location());
833 }
834 break;
835 case CMD_PRINTLINE:
836 case CMD_PRINTTO:
837 case CMD_PRINTUNTIL: {
838 leavePara();
839
840 Atom::AtomType atomType = marker ? marker->atomType() : Atom::Code;
841 QString rest = getRestOfLine();
842 if (s_quoting) {
843 appendAtom(Atom(Atom::CodeQuoteCommand, cmdStr));
844 appendAtom(Atom(Atom::CodeQuoteArgument, rest));
845 }
846 if (cmd == CMD_PRINTLINE)
847 appendToCode(m_quoter.quoteLine(location(), cmdStr, rest), atomType, codeLanguage);
848 else if (cmd == CMD_PRINTTO)
849 appendToCode(m_quoter.quoteTo(location(), cmdStr, rest), atomType, codeLanguage);
850 else
851 appendToCode(m_quoter.quoteUntil(location(), cmdStr, rest), atomType, codeLanguage);
852 break;
853 }
854 case CMD_QUOTATION:
855 if (openCommand(cmd)) {
856 leavePara();
857 appendAtom(Atom(Atom::QuotationLeft));
858 }
859 break;
860 case CMD_QUOTEFILE:
861 case CMD_QUOTEFROMFILE: {
862 // A language argument must be on the same line as the command.
863 codeLanguage = getLanguageArgument(&marker);
864 leavePara();
865
866 QString fileName = getArgument();
867 if (s_quoting) {
868 appendAtom(Atom(Atom::CodeQuoteCommand, cmdStr));
869 appendAtom(Atom(Atom::CodeQuoteArgument, fileName));
870 }
871 if (!marker)
872 marker = CodeMarker::markerForFileName(fileName);
873
874 quoteFromFile(fileName, marker);
875 if (cmd == CMD_QUOTEFILE) {
876 appendAtom(Atom(Atom::Code, m_quoter.quoteTo(location(), cmdStr, QString()), codeLanguage));
877 m_quoter.reset();
878 }
879 break;
880 }
881 case CMD_RAW:
882 leavePara();
883 p1 = getRestOfLine();
884 if (p1.isEmpty())
885 location().warning(QStringLiteral("Missing format name after '\\%1'")
886 .arg(cmdName(CMD_RAW)));
887 appendAtom(Atom(Atom::FormatIf, p1));
888 appendAtom(Atom(Atom::RawString, untabifyEtc(getUntilEnd(cmd))));
889 appendAtom(Atom(Atom::FormatElse));
890 appendAtom(Atom(Atom::FormatEndif));
891 break;
892 case CMD_ROW:
893 if (m_openedCommands.top() == CMD_TABLE) {
894 p1.clear();
895 if (isLeftBraceAhead())
896 p1 = getArgument(ArgumentParsingOptions::Verbatim);
897 leaveTableRow();
898 appendAtom(Atom(Atom::TableRowLeft, p1));
899 m_inTableRow = true;
900 } else {
901 if (m_openedCommands.contains(CMD_TABLE))
902 location().warning(QStringLiteral("Cannot use '\\%1' within '\\%2'")
903 .arg(cmdName(CMD_ROW),
904 cmdName(m_openedCommands.top())));
905 else
906 location().warning(QStringLiteral("Cannot use '\\%1' outside of '\\%2'")
907 .arg(cmdName(CMD_ROW), cmdName(CMD_TABLE)));
908 }
909 break;
910 case CMD_SA:
911 parseAlso();
912 break;
913 case CMD_SECTION1:
914 startSection(Doc::Section1, cmd);
915 break;
916 case CMD_SECTION2:
917 startSection(Doc::Section2, cmd);
918 break;
919 case CMD_SECTION3:
920 startSection(Doc::Section3, cmd);
921 break;
922 case CMD_SECTION4:
923 startSection(Doc::Section4, cmd);
924 break;
925 case CMD_SIDEBAR:
926 if (openCommand(cmd)) {
927 leavePara();
928 appendAtom(Atom(Atom::SidebarLeft));
929 }
930 break;
931 case CMD_SKIPLINE: {
932 leavePara();
933 QString rest = getRestOfLine();
934 if (s_quoting) {
935 appendAtom(Atom(Atom::CodeQuoteCommand, cmdStr));
936 appendAtom(Atom(Atom::CodeQuoteArgument, rest));
937 }
938 m_quoter.quoteLine(location(), cmdStr, rest);
939 break;
940 }
941 case CMD_SKIPTO: {
942 leavePara();
943 QString rest = getRestOfLine();
944 if (s_quoting) {
945 appendAtom(Atom(Atom::CodeQuoteCommand, cmdStr));
946 appendAtom(Atom(Atom::CodeQuoteArgument, rest));
947 }
948 m_quoter.quoteTo(location(), cmdStr, rest);
949 break;
950 }
951 case CMD_SKIPUNTIL: {
952 leavePara();
953 QString rest = getRestOfLine();
954 if (s_quoting) {
955 appendAtom(Atom(Atom::CodeQuoteCommand, cmdStr));
956 appendAtom(Atom(Atom::CodeQuoteArgument, rest));
957 }
958 m_quoter.quoteUntil(location(), cmdStr, rest);
959 break;
960 }
961 case CMD_SPAN:
962 p1 = ATOM_FORMATTING_SPAN + getArgument(ArgumentParsingOptions::Verbatim);
963 startFormat(p1, cmd);
964 break;
965 case CMD_SNIPPET: {
966 // A language argument must be on the same line as the command.
967 codeLanguage = getLanguageArgument(&marker);
968
969 leavePara();
970 QString snippet = getArgument();
971 QString identifier = getRestOfLine();
972 if (s_quoting) {
973 appendAtom(Atom(Atom::SnippetCommand, cmdStr));
974 appendAtom(Atom(Atom::SnippetLocation, snippet));
975 appendAtom(Atom(Atom::SnippetIdentifier, identifier));
976 }
977 if (!marker)
978 marker = CodeMarker::markerForFileName(snippet);
979
980 quoteFromFile(snippet, marker);
981 appendToCode(m_quoter.quoteSnippet(location(), identifier), marker->atomType(), codeLanguage);
982 break;
983 }
984 case CMD_SUB:
985 startFormat(ATOM_FORMATTING_SUBSCRIPT, cmd);
986 break;
987 case CMD_SUP:
988 startFormat(ATOM_FORMATTING_SUPERSCRIPT, cmd);
989 break;
990 case CMD_TABLE:
991 leaveValueList();
992 p1 = getOptionalArgument();
993 p2 = getOptionalArgument();
994 if (openCommand(cmd)) {
995 leavePara();
996 appendAtom(Atom(Atom::TableLeft, p1, p2));
997 m_inTableHeader = false;
998 m_inTableRow = false;
999 m_inTableItem = false;
1000 }
1001 break;
1003 location().report("\\%1 is deprecated and will be removed in a future version."_L1.arg(cmdName(cmd)));
1004 if (isLeftBraceAhead())
1005 getArgument();
1006 break;
1007 case CMD_TARGET:
1008 if (m_openedCommands.top() == CMD_TABLE && !m_inTableItem) {
1009 location().warning("Found a \\target command outside table item in a table.\n"
1010 "Move the \\target inside the \\li to resolve this warning.");
1011 }
1012 insertTarget(getRestOfLine());
1013 break;
1014 case CMD_TITLE:
1015 leavePara();
1016 enterPara(Atom::TitleLeft, Atom::TitleRight);
1017 break;
1018 case CMD_TM:
1019 // Ignore command while parsing \section<N> or \title argument
1020 if (m_paragraphState != InSingleLineParagraph)
1021 startFormat(ATOM_FORMATTING_TRADEMARK, cmd);
1022 break;
1023 case CMD_TOC:
1024 if (openCommand(cmd)) {
1025 leavePara();
1026 appendAtom(Atom(Atom::TableOfContentsLeft));
1027 }
1028 break;
1029 case CMD_ENDTOC:
1030 if (closeCommand(cmd)) {
1031 leavePara();
1032 appendAtom(Atom(Atom::TableOfContentsRight));
1033 }
1034 break;
1035 case CMD_TT:
1036 startFormat(ATOM_FORMATTING_TELETYPE, cmd);
1037 break;
1038 case CMD_UICONTROL:
1039 startFormat(ATOM_FORMATTING_UICONTROL, cmd);
1040 break;
1041 case CMD_UNDERLINE:
1042 startFormat(ATOM_FORMATTING_UNDERLINE, cmd);
1043 break;
1044 case CMD_UNICODE: {
1045 enterPara();
1046 p1 = getArgument();
1047 bool ok;
1048 uint unicodeChar = p1.toUInt(&ok, 0);
1049 if (!ok || (unicodeChar == 0x0000) || (unicodeChar > 0xFFFE))
1050 location().warning(
1051 QStringLiteral("Invalid Unicode character '%1' specified with '%2'")
1052 .arg(p1, cmdName(CMD_UNICODE)));
1053 else
1054 appendAtom(Atom(Atom::String, QChar(unicodeChar)));
1055 break;
1056 }
1057 case CMD_VALUE:
1058 leaveValue();
1059 if (m_openedLists.top().style() == OpenedList::Value) {
1060 QString p2;
1061 p1 = getArgument();
1062 if (p1.startsWith(QLatin1String("[since "))
1063 && p1.endsWith(QLatin1String("]"))) {
1064 p2 = p1.mid(7, p1.size() - 8);
1065 p1 = getArgument();
1066 }
1067 if (!m_private->m_enumItemList.contains(p1))
1068 m_private->m_enumItemList.append(p1);
1069
1070 m_openedLists.top().next();
1071 appendAtom(Atom(Atom::ListTagLeft, ATOM_LIST_VALUE));
1072 appendAtom(Atom(Atom::String, p1));
1073 appendAtom(Atom(Atom::ListTagRight, ATOM_LIST_VALUE));
1074 if (!p2.isEmpty()) {
1075 appendAtom(Atom(Atom::SinceTagLeft, ATOM_LIST_VALUE));
1076 appendAtom(Atom(Atom::String, p2));
1077 appendAtom(Atom(Atom::SinceTagRight, ATOM_LIST_VALUE));
1078 }
1079 appendAtom(Atom(Atom::ListItemLeft, ATOM_LIST_VALUE));
1080
1081 skipSpacesOrOneEndl();
1082 if (isBlankLine())
1083 appendAtom(Atom(Atom::Nop));
1084 } else {
1085 // ### unknown problems
1086 }
1087 break;
1088 case CMD_WARNING:
1089 leavePara();
1090 enterPara(Atom::WarningLeft, Atom::WarningRight);
1091 break;
1092 case CMD_OVERLOAD:
1093 cmd_overload();
1094 break;
1095 case NOT_A_CMD:
1096 if (metaCommandSet.contains(cmdStr)) {
1097 if (m_pendingParagraphLeftType == Atom::DeprecatedLeft)
1098 leavePara();
1099 QString arg;
1100 QString bracketedArg;
1101 const bool isDeprecation = cmdStr == "deprecated"_L1
1102 || cmdStr == "obsolete"_L1;
1103 m_private->m_metacommandsUsed.insert(cmdStr);
1104 if (isDeprecation ? isLeftBracketAhead(0) : isLeftBracketAhead())
1105 bracketedArg = getBracketedArgument();
1106 if (isDeprecation) {
1107 leavePara();
1108 skipSpacesOnLine();
1109 // An optional reason must start on the command line.
1110 // Once started, it follows the normal paragraph rules.
1111 if (m_position < m_inputLength && m_input.at(m_position) != u'\n')
1112 enterPara(Atom::DeprecatedLeft, Atom::DeprecatedRight);
1113 } else {
1114 arg = getMetaCommandArgument(cmdStr);
1115 }
1116 m_private->m_metaCommandMap[cmdStr].append(ArgPair(arg, bracketedArg));
1117 if (possibleTopics.contains(cmdStr)) {
1118 if (!cmdStr.endsWith(QLatin1String("propertygroup")))
1119 m_private->m_topics.append(Topic(cmdStr, std::move(arg)));
1120 }
1121 } else if (s_utilities.macroHash.contains(cmdStr)) {
1122 const Macro &macro = s_utilities.macroHash.value(cmdStr);
1123 QStringList macroArgs;
1124 int numPendingFi = 0;
1125 int numFormatDefs = 0;
1126 for (auto it = macro.m_otherDefs.constBegin();
1127 it != macro.m_otherDefs.constEnd(); ++it) {
1128 if (it.key() != "match") {
1129 if (numFormatDefs == 0)
1130 macroArgs = getMacroArguments(cmdStr, macro);
1131 appendAtom(Atom(Atom::FormatIf, it.key()));
1132 expandMacro(*it, macroArgs);
1133 ++numFormatDefs;
1134 if (it == macro.m_otherDefs.constEnd()) {
1135 appendAtom(Atom(Atom::FormatEndif));
1136 } else {
1137 appendAtom(Atom(Atom::FormatElse));
1138 ++numPendingFi;
1139 }
1140 }
1141 }
1142 while (numPendingFi-- > 0)
1143 appendAtom(Atom(Atom::FormatEndif));
1144
1145 if (!macro.m_defaultDef.isEmpty()) {
1146 if (numFormatDefs > 0) {
1147 macro.m_defaultDefLocation.warning(
1148 QStringLiteral("Macro cannot have both "
1149 "format-specific and qdoc-"
1150 "syntax definitions"));
1151 } else {
1152 QString expanded = expandMacroToString(cmdStr, macro);
1153 m_input.replace(m_backslashPosition,
1154 m_endPosition - m_backslashPosition, expanded);
1155 m_inputLength = m_input.size();
1156 m_position = m_backslashPosition;
1157 }
1158 }
1159 } else if (isAutoLinkString(cmdStr)) {
1160 appendWord(cmdStr);
1161 } else {
1162 if (!cmdStr.endsWith("propertygroup")) {
1163 // The QML property group commands are no longer required
1164 // for grouping QML properties. They are allowed but ignored.
1165 location().warning(QStringLiteral("Unknown command '\\%1'").arg(cmdStr),
1166 detailsUnknownCommand(metaCommandSet, cmdStr));
1167 }
1168 enterPara();
1169 appendAtom(Atom(Atom::UnknownCommand, cmdStr));
1170 }
1171 }
1172 } // case '\\' (qdoc markup command)
1173 break;
1174 }
1175 case '-': { // Catch en-dash (--) and em-dash (---) markup here.
1176 enterPara();
1177 qsizetype dashCount = 1;
1178 ++m_position;
1179
1180 // Figure out how many hyphens in a row.
1181 while ((m_position < m_inputLength) && (m_input.at(m_position) == '-')) {
1182 ++dashCount;
1183 ++m_position;
1184 }
1185
1186 if (dashCount == 3) {
1187 // 3 hyphens, append an em-dash character.
1188 const QChar emDash(8212);
1189 appendChar(emDash);
1190 } else if (dashCount == 2) {
1191 // 2 hyphens; append an en-dash character.
1192 const QChar enDash(8211);
1193 appendChar(enDash);
1194 } else {
1195 // dashCount is either one or more than three. Append a hyphen
1196 // the appropriate number of times. This ensures '----' doesn't
1197 // end up as an em-dash followed by a hyphen in the output.
1198 for (qsizetype i = 0; i < dashCount; ++i)
1199 appendChar('-');
1200 }
1201 break;
1202 }
1203 case '{':
1204 enterPara();
1205 ++m_braceDepth;
1206 ++m_position;
1207 if (m_paragraphState != InBraceDelimitedParagraph)
1208 appendChar('{');
1209 else
1210 skipSpacesOnLine();
1211 break;
1212 case '}': {
1213 --m_braceDepth;
1214 ++m_position;
1215
1216 auto format = m_pendingFormats.find(m_braceDepth);
1217 if (format == m_pendingFormats.end()) {
1218 if (m_paragraphState == InBraceDelimitedParagraph) {
1219 leavePara();
1220 } else {
1221 enterPara();
1222 appendChar('}');
1223 }
1224 } else {
1225 const auto &last{m_private->m_text.lastAtom()->string()};
1226 appendAtom(Atom(Atom::FormattingRight, *format));
1227 if (*format == ATOM_FORMATTING_INDEX) {
1228 if (m_indexStartedParagraph)
1229 skipAllSpaces();
1230 } else if (*format == ATOM_FORMATTING_LINK) {
1231 // Support links like \l{QString::}{count()} for C++
1232 // and \l{Item::}{children} for QML.
1233 if (currentLinkAtom && currentLinkAtom->string().endsWith("::")) {
1234 QString suffix =
1235 Text::subText(currentLinkAtom, m_private->m_text.lastAtom())
1236 .toString();
1237 currentLinkAtom->concatenateString(suffix);
1238 }
1239 currentLinkAtom = nullptr;
1240 } else if (*format == ATOM_FORMATTING_TRADEMARK) {
1241 m_private->m_text.lastAtom()->append(last);
1242 }
1243 m_pendingFormats.erase(format);
1244 }
1245 break;
1246 }
1247 // Do not parse content after '//!' comments
1248 case '/': {
1249 if (m_position + 2 < m_inputLength)
1250 if (m_input.at(m_position + 1) == '/')
1251 if (m_input.at(m_position + 2) == '!') {
1252 m_position += 2;
1253 getRestOfLine();
1254 if (m_input.at(m_position - 1) == '\n')
1255 --m_position;
1256 break;
1257 }
1258 Q_FALLTHROUGH(); // fall through
1259 }
1260 default: {
1261 bool newWord;
1262 switch (m_private->m_text.lastAtom()->type()) {
1263 case Atom::ParaLeft:
1264 newWord = true;
1265 break;
1266 default:
1267 newWord = false;
1268 }
1269
1270 if (m_paragraphState == OutsideParagraph) {
1271 if (ch.isSpace()) {
1272 ++m_position;
1273 newWord = false;
1274 } else {
1275 enterPara();
1276 newWord = true;
1277 }
1278 } else {
1279 if (ch.isSpace()) {
1280 ++m_position;
1281 if ((ch == '\n')
1282 && (m_paragraphState == InSingleLineParagraph || isBlankLine())) {
1283 leavePara();
1284 newWord = false;
1285 } else {
1286 appendChar(' ');
1287 newWord = true;
1288 }
1289 } else {
1290 newWord = true;
1291 }
1292 }
1293
1294 if (newWord) {
1295 qsizetype startPos = m_position;
1296 // No auto-linking inside links or (section) titles
1297 bool autolink = (!m_pendingFormats.isEmpty() &&
1298 m_pendingFormats.last() == ATOM_FORMATTING_LINK)
1299 || m_paragraphState == InSingleLineParagraph ?
1300 false : isAutoLinkString(m_input, m_position);
1301 if (m_position == startPos) {
1302 if (!ch.isSpace()) {
1303 appendChar(ch);
1304 ++m_position;
1305 }
1306 } else {
1307 QString word = m_input.mid(startPos, m_position - startPos);
1308 if (autolink) {
1309 if (s_ignoreWords.contains(word) || word.startsWith(QString("__")))
1310 appendWord(word);
1311 else
1312 appendAtom(LinkAtom(Atom::AutoLink, word, {}, location()));
1313 } else {
1314 appendWord(word);
1315 }
1316 }
1317 }
1318 } // default:
1319 } // switch (ch.unicode())
1320 }
1321 leaveValueList();
1322
1323 // for compatibility
1324 if (m_openedCommands.top() == CMD_LEGALESE) {
1325 appendAtom(Atom(Atom::LegaleseRight));
1326 m_openedCommands.pop();
1327 }
1328
1329 if (m_openedCommands.top() != CMD_OMIT) {
1330 location().warning(
1331 QStringLiteral("Missing '\\%1'").arg(endCmdName(m_openedCommands.top())));
1332 } else if (preprocessorSkipping.size() > 0) {
1333 location().warning(QStringLiteral("Missing '\\%1'").arg(cmdName(CMD_ENDIF)));
1334 }
1335
1336 if (m_currentSection > Doc::NoSection) {
1337 appendAtom(Atom(Atom::SectionRight, QString::number(m_currentSection)));
1338 m_currentSection = Doc::NoSection;
1339 }
1340
1342}
1343
1344/*!
1345 Returns the current location.
1346 */
1347Location &DocParser::location()
1348{
1349 while (!m_openedInputs.isEmpty() && m_openedInputs.top() <= m_position) {
1350 m_cachedLocation.pop();
1351 m_cachedPosition = m_openedInputs.pop();
1352 }
1353 while (m_cachedPosition < m_position)
1354 m_cachedLocation.advance(m_input.at(m_cachedPosition++));
1355 return m_cachedLocation;
1356}
1357
1358QString DocParser::detailsUnknownCommand(const QSet<QString> &metaCommandSet, const QString &str)
1359{
1360 QSet<QString> commandSet = metaCommandSet;
1361 int i = 0;
1362 while (cmds[i].name != nullptr) {
1363 commandSet.insert(cmds[i].name);
1364 ++i;
1365 }
1366
1367 return "Maybe you meant '\\%1'?"_L1.arg(suggestName(str, commandSet));
1368}
1369
1370/*!
1371 \internal
1372
1373 Issues a warning about an empty or duplicate definition of either a
1374 \\target or \\keyword command (determined by \a cmdString) at
1375 \a location. \a duplicateDefinition is the target being processed;
1376 the already registered definition is \a previousDefinition.
1377 */
1378static void warnAboutEmptyOrPreexistingTarget(const Location &location, const QString &duplicateDefinition,
1379 const QString &cmdString, const QString &previousDefinition)
1380{
1381 if (duplicateDefinition.isEmpty()) {
1382 location.warning("Expected an argument for \\%1"_L1.arg(cmdString));
1383 } else {
1384 location.warning(
1385 "Duplicate %3 name '%1'. The previous occurrence is here: %2"_L1
1386 .arg(duplicateDefinition, previousDefinition, cmdString));
1387 }
1388}
1389
1390/*!
1391 \internal
1392
1393 \brief Registers \a target as a linkable entity.
1394
1395 The main purpose of this method is to register a target as defined
1396 along with its location, so that becomes a valid link target from other
1397 parts of the documentation.
1398
1399 If the \a target name is already registered, a warning is issued,
1400 as multiple definitions are problematic.
1401
1402 \sa insertKeyword, target-command
1403 */
1404void DocParser::insertTarget(const QString &target)
1405{
1406 if (target.isEmpty() || m_targetMap.contains(target))
1407 return warnAboutEmptyOrPreexistingTarget(location(), target,
1408 s_utilities.cmdHash.key(CMD_TARGET), m_targetMap[target].toString());
1409
1410 m_targetMap.insert(target, location());
1411 m_private->constructExtra();
1412
1413 appendAtom(Atom(Atom::Target, target));
1414 m_private->extra->m_targets.append(m_private->m_text.lastAtom());
1415}
1416
1417/*!
1418 \internal
1419
1420 \brief Registers \a keyword as a linkable entity.
1421
1422 The main purpose of this method is to register a keyword as defined
1423 along with its location, so that becomes a valid link target from other
1424 parts of the documentation.
1425
1426 If the \a keyword name is already registered, a warning is issued,
1427 as multiple definitions are problematic.
1428
1429 \sa insertTarget, keyword-command
1430 */
1431void DocParser::insertKeyword(const QString &keyword)
1432{
1433 if (keyword.isEmpty() || m_targetMap.contains(keyword))
1434 return warnAboutEmptyOrPreexistingTarget(location(), keyword,
1435 s_utilities.cmdHash.key(CMD_KEYWORD), m_targetMap[keyword].toString());
1436
1437 m_targetMap.insert(keyword, location());
1438 m_private->constructExtra();
1439
1440 appendAtom(Atom(Atom::Keyword, keyword));
1441 m_private->extra->m_keywords.append(m_private->m_text.lastAtom());
1442}
1443
1444void DocParser::include(const QString &fileName, const QString &identifier, const QStringList &parameters)
1445{
1446 if (location().depth() > 16)
1447 location().fatal(QStringLiteral("Too many nested '\\%1's").arg(cmdName(CMD_INCLUDE)));
1448 QString filePath = Config::instance().getIncludeFilePath(fileName);
1449 if (filePath.isEmpty()) {
1450 location().warning(QStringLiteral("Cannot find qdoc include file '%1'").arg(fileName));
1451 } else {
1452 QFile inFile(filePath);
1453 if (!inFile.open(QFile::ReadOnly)) {
1454 location().warning(
1455 QStringLiteral("Cannot open qdoc include file '%1'").arg(filePath));
1456 } else {
1457 location().push(fileName);
1458 QTextStream inStream(&inFile);
1459 QString includedContent = inStream.readAll();
1460 inFile.close();
1461
1462 if (identifier.isEmpty()) {
1463 expandArgumentsInString(includedContent, parameters);
1464 m_input.insert(m_position, includedContent);
1465 m_inputLength = m_input.size();
1466 m_openedInputs.push(m_position + includedContent.size());
1467 } else {
1468 auto isSnippetMarker = [&identifier](QStringView trimmedLine) -> bool {
1469 if (!trimmedLine.startsWith(QLatin1String("//!")))
1470 return false;
1471 auto bracketStart = trimmedLine.indexOf(QLatin1Char('['));
1472 auto bracketEnd = trimmedLine.indexOf(QLatin1Char(']'));
1473 if (bracketStart < 0 || bracketEnd <= bracketStart)
1474 return false;
1475 auto name = trimmedLine.mid(bracketStart + 1, bracketEnd - bracketStart - 1)
1476 .trimmed();
1477 return name == identifier;
1478 };
1479
1480 QStringList lineBuffer = includedContent.split(QLatin1Char('\n'));
1481 qsizetype bufLen{lineBuffer.size()};
1482 qsizetype i;
1483 QStringView trimmedLine;
1484 for (i = 0; i < bufLen; ++i) {
1485 trimmedLine = QStringView{lineBuffer[i]}.trimmed();
1486 if (isSnippetMarker(trimmedLine))
1487 break;
1488 }
1489 if (i < bufLen - 1) {
1490 ++i;
1491 } else {
1492 location().warning(
1493 QStringLiteral("Cannot find '%1' in '%2'").arg(identifier, filePath));
1494 return;
1495 }
1496 QString result;
1497 do {
1498 trimmedLine = QStringView{lineBuffer[i]}.trimmed();
1499 if (isSnippetMarker(trimmedLine))
1500 break;
1501 else
1502 result += lineBuffer[i] + QLatin1Char('\n');
1503 ++i;
1504 } while (i < bufLen);
1505
1506 expandArgumentsInString(result, parameters);
1507 if (result.isEmpty()) {
1508 location().warning(QStringLiteral("Empty qdoc snippet '%1' in '%2'")
1509 .arg(identifier, filePath));
1510 } else {
1511 m_input.insert(m_position, result);
1512 m_inputLength = m_input.size();
1513 m_openedInputs.push(m_position + result.size());
1514 }
1515 }
1516 }
1517 }
1518}
1519
1520void DocParser::startFormat(const QString &format, int cmd)
1521{
1522 enterPara();
1523
1524 for (const auto &item : std::as_const(m_pendingFormats)) {
1525 if (item == format) {
1526 location().warning(QStringLiteral("Cannot nest '\\%1' commands").arg(cmdName(cmd)));
1527 return;
1528 }
1529 }
1530
1531 appendAtom(Atom(Atom::FormattingLeft, format));
1532
1533 if (isLeftBraceAhead()) {
1534 skipSpacesOrOneEndl();
1535 m_pendingFormats.insert(m_braceDepth, format);
1536 ++m_braceDepth;
1537 ++m_position;
1538 } else {
1539 const auto &arg{getArgument()};
1540 appendAtom(Atom(Atom::String, arg));
1541 appendAtom(Atom(Atom::FormattingRight, format));
1542 if (format == ATOM_FORMATTING_INDEX && m_indexStartedParagraph) {
1543 skipAllSpaces();
1544 m_indexStartedParagraph = false;
1545 } else if (format == ATOM_FORMATTING_TRADEMARK) {
1546 m_private->m_text.lastAtom()->append(arg);
1547 }
1548 }
1549}
1550
1551bool DocParser::openCommand(int cmd)
1552{
1553 int outer = m_openedCommands.top();
1554 bool ok = true;
1555
1556 if ((cmd == CMD_COMPARESWITH || cmd == CMD_TOC)
1557 && m_openedCommands.contains(cmd)) {
1558 location().warning(u"Cannot nest '\\%1' commands"_s.arg(cmdName(cmd)));
1559 return false;
1560 } else if (cmd != CMD_LINK) {
1561 if (outer == CMD_LIST) {
1562 ok = (cmd == CMD_FOOTNOTE || cmd == CMD_LIST);
1563 } else if (outer == CMD_SIDEBAR) {
1564 ok = (cmd == CMD_LIST || cmd == CMD_QUOTATION || cmd == CMD_SIDEBAR);
1565 } else if (outer == CMD_QUOTATION) {
1566 ok = (cmd == CMD_LIST);
1567 } else if (outer == CMD_TABLE) {
1568 ok = (cmd == CMD_LIST || cmd == CMD_FOOTNOTE || cmd == CMD_QUOTATION);
1569 } else if (outer == CMD_FOOTNOTE || outer == CMD_LINK) {
1570 ok = false;
1571 }
1572 }
1573
1574 if (ok) {
1575 m_openedCommands.push(cmd);
1576 } else {
1577 location().warning(
1578 QStringLiteral("Can't use '\\%1' in '\\%2'").arg(cmdName(cmd), cmdName(outer)));
1579 }
1580 return ok;
1581}
1582
1583/*!
1584 Returns \c true if \a word qualifies for auto-linking.
1585
1586 A word qualifies for auto-linking if either:
1587
1588 \list
1589 \li It is composed of only upper and lowercase characters
1590 \li AND It contains at least one uppercase character that is not
1591 the first character of word
1592 \li AND it contains at least two lowercase characters
1593 \endlist
1594
1595 Or
1596
1597 \list
1598 \li It is composed only of uppercase characters, lowercase
1599 characters, characters in [_@] and the \c {"::"} sequence.
1600 \li It contains at least one uppercase character that is not
1601 the first character of word or it contains at least one
1602 lowercase character
1603 \li AND it contains at least one character in [_@] or it
1604 contains at least one \c {"::"} sequence.
1605 \endlist
1606
1607 Inserting or suffixing, but not prefixing, any sequence in [0-9]+
1608 in a word that qualifies for auto-linking by the above rules
1609 preserves the auto-linkability of the word.
1610
1611 Suffixing the sequence \c {"()"} to a word that qualifies for
1612 auto-linking by the above rules preserves the auto-linkability of
1613 a word.
1614
1615 FInally, a word qualifies for auto-linking if:
1616
1617 \list
1618 \li It is composed of only uppercase characters, lowercase
1619 characters and the sequence \c {"()"}
1620 \li AND it contains one lowercase character and a sequence of zero, one
1621 or two upper or lowercase characters
1622 \li AND it contains exactly one sequence \c {"()"}
1623 \li AND it contains one sequence \c {"()"} as the last two
1624 characters of word
1625 \endlist
1626
1627 For example, \c {"fOo"}, \c {"FooBar"} and \c {"foobaR"} qualify
1628 for auto-linking by the first rule.
1629
1630 \c {"QT_DEBUG"}, \c {"::Qt"} and \c {"std::move"} qualifies for
1631 auto-linking by the second rule.
1632
1633 \c {"SIMDVector256"} qualifies by suffixing \c {"SIMDVector"},
1634 which qualifies by the first rule, with the sequence \c {"256"}
1635
1636 \c {"FooBar::Bar()"} qualifies by suffixing \c {"FooBar::Bar"},
1637 which qualifies by the first and second rule, with the sequence \c
1638 {"()"}.
1639
1640 \c {"Foo()"} and \c {"a()"} qualifies by the last rule.
1641
1642 Instead, \c {"Q"}, \c {"flower"}, \c {"_"} and \c {"()"} do not
1643 qualify for auto-linking.
1644
1645 The rules are intended as a heuristic to catch common cases in the
1646 Qt documentation where a word might represent an important
1647 documented element such as a class or a method that could be
1648 linked to while at the same time avoiding catching common words
1649 such as \c {"A"} or \c {"Nonetheless"}.
1650
1651 The heuristic assumes that Qt's codebase respects a style where
1652 camelCasing is the standard for most of the elements, a function
1653 call is identified by the use of parenthesis and certain elements,
1654 such as macros, might be fully uppercase.
1655
1656 Furthemore, it assumes that the Qt codebase is written in a
1657 language that has an identifier grammar similar to the one for
1658 C++.
1659*/
1660inline bool DocParser::isAutoLinkString(const QString &word)
1661{
1662 qsizetype start = 0;
1663 return isAutoLinkString(word, start) && (start == word.size());
1664}
1665
1666/*!
1667 Returns \c true if a prefix of a substring of \a word qualifies
1668 for auto-linking.
1669
1670 Respects the same parsing rules as the unary overload.
1671
1672 \a curPos defines the offset, from the first character of \ word,
1673 at which the parsed substring starts.
1674
1675 When the call completes, \a curPos represents the offset, from the
1676 first character of word, that is the successor of the offset of
1677 the last parsed character.
1678
1679 If the return value of the call is \c true, it is guaranteed that
1680 the prefix of the substring of \word that contains the characters
1681 from the initial value of \a curPos and up to but not including \a
1682 curPos qualifies for auto-linking.
1683
1684 If \a curPos is initially zero, the considered substring is the
1685 entirety of \a word.
1686*/
1687bool DocParser::isAutoLinkString(const QString &word, qsizetype &curPos)
1688{
1689 qsizetype len = word.size();
1690 qsizetype startPos = curPos;
1691 int numUppercase = 0;
1692 int numLowercase = 0;
1693 int numStrangeSymbols = 0;
1694
1695 while (curPos < len) {
1696 unsigned char latin1Ch = word.at(curPos).toLatin1();
1697 if (islower(latin1Ch)) {
1698 ++numLowercase;
1699 ++curPos;
1700 } else if (isupper(latin1Ch)) {
1701 if (curPos > startPos)
1702 ++numUppercase;
1703 ++curPos;
1704 } else if (isdigit(latin1Ch)) {
1705 if (curPos > startPos)
1706 ++curPos;
1707 else
1708 break;
1709 } else if (latin1Ch == '_' || latin1Ch == '@') {
1710 ++numStrangeSymbols;
1711 ++curPos;
1712 } else if ((latin1Ch == ':') && (curPos < len - 1)
1713 && (word.at(curPos + 1) == QLatin1Char(':'))) {
1714 ++numStrangeSymbols;
1715 curPos += 2;
1716 } else if (latin1Ch == '(') {
1717 if ((curPos < len - 1) && (word.at(curPos + 1) == QLatin1Char(')'))) {
1718 ++numStrangeSymbols;
1719 curPos += 2;
1720 }
1721
1722 break;
1723 } else {
1724 break;
1725 }
1726 }
1727
1728 return ((numUppercase >= 1 && numLowercase >= 2) || (numStrangeSymbols > 0 && (numUppercase + numLowercase >= 1)));
1729}
1730
1731bool DocParser::closeCommand(int endCmd)
1732{
1733 if (endCmdFor(m_openedCommands.top()) == endCmd && m_openedCommands.size() > 1) {
1734 m_openedCommands.pop();
1735 return true;
1736 } else {
1737 bool contains = false;
1738 QStack<int> opened2 = m_openedCommands;
1739 while (opened2.size() > 1) {
1740 if (endCmdFor(opened2.top()) == endCmd) {
1741 contains = true;
1742 break;
1743 }
1744 opened2.pop();
1745 }
1746
1747 if (contains) {
1748 while (endCmdFor(m_openedCommands.top()) != endCmd && m_openedCommands.size() > 1) {
1749 location().warning(
1750 QStringLiteral("Missing '\\%1' before '\\%2'")
1751 .arg(endCmdName(m_openedCommands.top()), cmdName(endCmd)));
1752 m_openedCommands.pop();
1753 }
1754 } else {
1755 location().warning(QStringLiteral("Unexpected '\\%1'").arg(cmdName(endCmd)));
1756 }
1757 return false;
1758 }
1759}
1760
1761void DocParser::startSection(Doc::Sections unit, int cmd)
1762{
1763 leaveValueList();
1764
1765 if (m_currentSection == Doc::NoSection) {
1766 m_currentSection = static_cast<Doc::Sections>(unit);
1767 m_private->constructExtra();
1768 } else {
1769 endSection(unit, cmd);
1770 }
1771
1772 appendAtom(Atom(Atom::SectionLeft, QString::number(unit)));
1773 m_private->constructExtra();
1774 m_private->extra->m_tableOfContents.append(m_private->m_text.lastAtom());
1775 m_private->extra->m_tableOfContentsLevels.append(unit);
1776 enterPara(Atom::SectionHeadingLeft, Atom::SectionHeadingRight, QString::number(unit));
1777 m_currentSection = unit;
1778}
1779
1780void DocParser::endSection(int, int) // (int unit, int endCmd)
1781{
1782 leavePara();
1783 appendAtom(Atom(Atom::SectionRight, QString::number(m_currentSection)));
1784 m_currentSection = (Doc::NoSection);
1785}
1786
1787/*!
1788 \internal
1789
1790 \brief Processes CMD_IMAGE and CMD_INLINEIMAGE, as specified by \a cmd.
1791
1792 The first argument to the command is the image file name. The rest of the
1793 line is an optional string that's used as the text description of the image
1794 (e.g. the HTML <img> alt attribute). The optional argument can be wrapped in
1795 curly braces, in which case it can span multiple lines.
1796
1797 This function may modify the optional argument by removing one pair of
1798 double quotes, if they wrap the string.
1799 */
1800void DocParser::cmd_image(int cmd) {
1801 const Location imageLocation = location(); // Setup before any consuming parser operation
1802
1803 Atom::AtomType imageAtom{};
1804 switch (cmd) {
1805 case CMD_IMAGE: {
1806 leaveValueList();
1807 imageAtom = Atom::AtomType::Image;
1808 break;
1809 }
1810 case CMD_INLINEIMAGE: {
1811 enterPara();
1812 imageAtom = Atom::AtomType::InlineImage;
1813 break;
1814 }
1815 default:
1816 break;
1817 }
1818
1819 const QString imageFileName = getArgument();
1820 QString imageText;
1821 bool hasAltTextArgument{false};
1822 if (isLeftBraceAhead()) {
1823 hasAltTextArgument = true;
1824 imageText = getArgument();
1825 } else if (cmd == CMD_IMAGE) {
1826 imageText = getRestOfLine();
1827 }
1828
1829 if (imageText.length() > 1) {
1830 if (imageText.front() == '"' && imageText.back() == '"') {
1831 imageText.removeFirst();
1832 imageText.removeLast();
1833 }
1834 }
1835
1836 if (!hasAltTextArgument && imageText.isEmpty()
1837 && Config::instance().reportMissingAltTextForImages()) {
1838 imageLocation.report(
1839 "\\%1 %2 is without a textual description, "
1840 "QDoc will not generate an alt text for the image."_L1.arg(cmdName(cmd))
1841 .arg(imageFileName));
1842 }
1843 appendAtom(Atom(imageAtom, imageFileName));
1844 appendAtom(Atom(Atom::ImageText, imageText));
1845}
1846
1847/*!
1848 \brief Processes the \\overload command in documentation comments.
1849
1850 This function registers metadata when the \\overload command is used in a
1851 documentation comment. It records the use of the command and stores any
1852 arguments to the command. Arguments are optional and can be passed with or
1853 without curly braces. This allows the user to use either of:
1854
1855 \badcode
1856 \overload someFunction
1857 \overload {someFunction}
1858 \endcode
1859 */
1860void DocParser::cmd_overload()
1861{
1862 const QString cmd{"overload"};
1863
1864 leavePara();
1865 m_private->m_metacommandsUsed.insert(cmd);
1866 QString overloadArgument = isBlankLine() ? getMetaCommandArgument(cmd) : getRestOfLine();
1867
1868 // Handle special case: \overload primary
1869 // Keep the "primary" flag for the code parser, but mark it specially
1870 // so generators know not to treat it as a target function name
1871 if (overloadArgument.trimmed() == "primary")
1872 overloadArgument = "__qdoc_primary_overload__"_L1;
1873
1874 m_private->m_metaCommandMap[cmd].append(ArgPair(overloadArgument, QString()));
1875}
1876
1877/*!
1878 \internal
1879 \brief Parses arguments to QDoc's see also command.
1880
1881 Parses space or comma separated arguments passed to the \\sa command.
1882 Multi-line input requires that the arguments are comma separated. Wrap
1883 arguments in curly braces for multi-word targets, and for scope resolution
1884 (for example, {QString::}{count()}).
1885
1886 This method updates the list of links for the See also section.
1887
1888 \sa {DocPrivate::}{addAlso()}, getArgument()
1889 */
1890void DocParser::parseAlso()
1891{
1892 auto line_comment = [this]() -> bool {
1893 skipSpacesOnLine();
1894 if (m_position + 2 > m_inputLength)
1895 return false;
1896 if (m_input[m_position].unicode() == '/') {
1897 if (m_input[m_position + 1].unicode() == '/') {
1898 if (m_input[m_position + 2].unicode() == '!') {
1899 return true;
1900 }
1901 }
1902 }
1903 return false;
1904 };
1905
1906 auto skip_everything_until_newline = [this]() -> void {
1907 while (m_position < m_inputLength && m_input[m_position] != '\n')
1908 ++m_position;
1909 };
1910
1911 leavePara();
1912 skipSpacesOnLine();
1913 while (m_position < m_inputLength && m_input[m_position] != '\n') {
1914 QString target;
1915 QString str;
1916 bool skipMe = false;
1917
1918 if (m_input[m_position] == '{') {
1919 target = getArgument();
1920 if (isLeftBraceAhead()) {
1921 str = getArgument();
1922
1923 // Support links like \l{QString::}{count()} for C++
1924 // and \l{Item::}{children} for QML.
1925 if (target.endsWith("::"))
1926 target += str;
1927 } else {
1928 str = target;
1929 }
1930 } else {
1931 target = getArgument();
1932 str = cleanLink(target);
1933 if (target == QLatin1String("and") || target == QLatin1String("."))
1934 skipMe = true;
1935 }
1936
1937 if (!skipMe) {
1938 Text also;
1939 also << LinkAtom(target, {}, location())
1942 m_private->addAlso(also);
1943 }
1944
1945 skipSpacesOnLine();
1946
1947 if (line_comment())
1948 skip_everything_until_newline();
1949
1950 if (m_position < m_inputLength && m_input[m_position] == ',') {
1951 m_position++;
1952 if (line_comment())
1953 skip_everything_until_newline();
1954 skipSpacesOrOneEndl();
1955 } else if (m_position >= m_inputLength || m_input[m_position] != '\n') {
1956 location().warning(QStringLiteral("Missing comma in '\\%1'").arg(cmdName(CMD_SA)));
1957 }
1958 }
1959}
1960
1961void DocParser::appendAtom(const Atom& atom) {
1962 m_private->m_text << atom;
1963}
1964
1965void DocParser::appendChar(QChar ch)
1966{
1968 appendAtom(Atom(Atom::String));
1969 Atom *atom = m_private->m_text.lastAtom();
1970 if (ch == QLatin1Char(' ')) {
1971 if (!atom->string().endsWith(QLatin1Char(' ')))
1972 atom->appendChar(QLatin1Char(' '));
1973 } else
1974 atom->appendChar(ch);
1975}
1976
1977void DocParser::appendWord(const QString &word)
1978{
1979 if (m_private->m_text.lastAtom()->type() != Atom::String) {
1980 appendAtom(Atom(Atom::String, word));
1981 } else
1982 m_private->m_text.lastAtom()->concatenateString(word);
1983}
1984
1985/*!
1986 Handles escaped backslash sequences (\\‍) that may be followed by an identifier.
1987
1988 When a double backslash is followed by alphanumeric characters (such as \\section1),
1989 the backslash and identifier are wrapped in notranslate formatting to preserve
1990 them verbatim in the output.
1991
1992 When a double backslash is not followed by an identifier, a literal backslash
1993 is appended.
1994
1995 \note Skips \\r in CRLF sequences to prevent spurious whitespace in the output.
1996*/
1997void DocParser::appendEscapedIdentifier()
1998{
1999 Q_ASSERT(m_position < m_inputLength);
2000 Q_ASSERT(m_input.at(m_position) == '\\');
2001
2002 ++m_position;
2003
2004 QString identifier;
2005 while (m_position < m_inputLength && m_input.at(m_position).isLetterOrNumber()) {
2006 identifier += m_input.at(m_position);
2007 ++m_position;
2008 }
2009
2010 enterPara();
2011 if (!identifier.isEmpty()) {
2013 appendAtom(Atom(Atom::String, '\\' + identifier));
2015
2016 if (m_position + 1 < m_inputLength && m_input.at(m_position) == '\r' && m_input.at(m_position + 1) == '\n')
2017 ++m_position;
2018 } else {
2019 appendChar(QLatin1Char('\\'));
2020 }
2021}
2022
2023void DocParser::appendToCode(const QString &markedCode)
2024{
2025 if (!isCode(m_lastAtom)) {
2026 appendAtom(Atom(Atom::Code));
2027 m_lastAtom = m_private->m_text.lastAtom();
2028 }
2029 m_lastAtom->concatenateString(markedCode);
2030}
2031
2032/*!
2033 Appends \a markedCode to the current documentation as an atom with the
2034 \a defaultType. The \a language specifies the programming language that
2035 the code is written in so that generators can include it as part of the
2036 meta-data they produce.
2037*/
2038void DocParser::appendToCode(const QString &markedCode, Atom::AtomType defaultType, const QString &language)
2039{
2040 if (!isCode(m_lastAtom)) {
2041 appendAtom(Atom(defaultType, markedCode, language));
2042 m_lastAtom = m_private->m_text.lastAtom();
2043 } else {
2044 m_lastAtom->concatenateString(markedCode);
2045 }
2046}
2047
2048void DocParser::enterPara(Atom::AtomType leftType, Atom::AtomType rightType, const QString &string)
2049{
2050 if (m_paragraphState != OutsideParagraph)
2051 return;
2052
2056 // Admonition commands (\note, \warning, \important) can appear
2057 // inside enum \value descriptions without closing the value list.
2058 // Structural commands (sections, tables, images) that should close
2059 // the value list already call leaveValueList() explicitly before
2060 // reaching enterPara(). See QTBUG-145755.
2061 const bool inValueList = !m_openedLists.isEmpty()
2062 && m_openedLists.top().style() == OpenedList::Value;
2063 const bool isAdmonition = leftType == Atom::NoteLeft
2064 || leftType == Atom::WarningLeft
2065 || leftType == Atom::ImportantLeft;
2066 if (!inValueList || !isAdmonition)
2067 leaveValueList();
2068 }
2069
2070 appendAtom(Atom(leftType, string));
2071 m_indexStartedParagraph = false;
2072 m_pendingParagraphLeftType = leftType;
2073 m_pendingParagraphRightType = rightType;
2074 m_pendingParagraphString = string;
2075 if (leftType == Atom::SectionHeadingLeft || leftType == Atom::TitleLeft) {
2076 m_paragraphState = InSingleLineParagraph;
2077 } else if (leftType == Atom::DetailsSummaryLeft) {
2078 m_paragraphState = InBraceDelimitedParagraph;
2079 } else {
2080 m_paragraphState = InMultiLineParagraph;
2081 }
2082 skipSpacesOrOneEndl();
2083}
2084
2085void DocParser::leavePara()
2086{
2087 if (m_paragraphState == OutsideParagraph)
2088 return;
2089 if (!m_pendingFormats.isEmpty() || (m_paragraphState == InBraceDelimitedParagraph && m_braceDepth > 0)) {
2090 location().warning(u"Missing '}'"_s);
2091 m_pendingFormats.clear();
2092 m_braceDepth = 0;
2093 }
2094
2095 if (m_private->m_text.lastAtom()->type() == m_pendingParagraphLeftType) {
2096 m_private->m_text.stripLastAtom();
2097 } else {
2099 && m_private->m_text.lastAtom()->string().endsWith(QLatin1Char(' '))) {
2101 }
2102 if (m_pendingParagraphRightType == Atom::TitleRight) {
2103 // Extract title
2106 } else {
2107 appendAtom(Atom(m_pendingParagraphRightType, m_pendingParagraphString));
2108 }
2109 }
2110 m_paragraphState = OutsideParagraph;
2111 m_indexStartedParagraph = false;
2112 m_pendingParagraphRightType = Atom::Nop;
2113 m_pendingParagraphString.clear();
2114}
2115
2116void DocParser::leaveValue()
2117{
2118 leavePara();
2119 if (m_openedLists.isEmpty()) {
2120 m_openedLists.push(OpenedList(OpenedList::Value));
2121 appendAtom(Atom(Atom::ListLeft, ATOM_LIST_VALUE));
2122 } else {
2123 if (m_private->m_text.lastAtom()->type() == Atom::Nop)
2124 m_private->m_text.stripLastAtom();
2125 appendAtom(Atom(Atom::ListItemRight, ATOM_LIST_VALUE));
2126 }
2127}
2128
2129void DocParser::leaveValueList()
2130{
2131 leavePara();
2132 if (!m_openedLists.isEmpty() && (m_openedLists.top().style() == OpenedList::Value)) {
2133 if (m_private->m_text.lastAtom()->type() == Atom::Nop)
2134 m_private->m_text.stripLastAtom();
2135 appendAtom(Atom(Atom::ListItemRight, ATOM_LIST_VALUE));
2136 appendAtom(Atom(Atom::ListRight, ATOM_LIST_VALUE));
2137 m_openedLists.pop();
2138 }
2139}
2140
2141void DocParser::leaveTableRow()
2142{
2143 if (m_inTableItem) {
2144 leavePara();
2145 appendAtom(Atom(Atom::TableItemRight));
2146 m_inTableItem = false;
2147 }
2148 if (m_inTableHeader) {
2149 appendAtom(Atom(Atom::TableHeaderRight));
2150 m_inTableHeader = false;
2151 }
2152 if (m_inTableRow) {
2153 appendAtom(Atom(Atom::TableRowRight));
2154 m_inTableRow = false;
2155 }
2156}
2157
2158/*!
2159 Quotes from the file with the given \a filename using an optional \a marker
2160 to mark up the quoted text. If no marker is provided, a marker is selected
2161 based on the file name.
2162*/
2163void DocParser::quoteFromFile(const QString &filename, CodeMarker *marker)
2164{
2165 // KLUDGE: We dereference file_resolver as it is temporarily a pointer.
2166 // See the comment for file_resolver in the header files for more context.
2167 //
2168 // We spefically dereference it, instead of using the arrow
2169 // operator, to better represent that we do not consider this as
2170 // an actual pointer, as it should not be.
2171 //
2172 // Do note that we are considering it informally safe to
2173 // dereference the pointer, as we expect it to always hold a value
2174 // at this point, but actual enforcement of this appears nowhere
2175 // in the codebase.
2176 auto maybe_resolved_file{(*file_resolver).resolve(filename)};
2177 if (!maybe_resolved_file) {
2178 // TODO: [uncentralized-admonition][failed-resolve-file]
2179 // This warning is required in multiple places.
2180 // To ensure the consistency of the warning and avoid
2181 // duplicating code everywhere, provide a centralized effort
2182 // where the warning message can be generated (but not
2183 // issued).
2184 // The current format is based on what was used before, review
2185 // it when it is moved out.
2186 QString details = std::transform_reduce(
2187 (*file_resolver).get_search_directories().cbegin(),
2188 (*file_resolver).get_search_directories().cend(),
2189 u"Searched directories:"_s,
2190 std::plus(),
2191 [](const DirectoryPath &directory_path) -> QString { return u' ' + directory_path.value(); }
2192 );
2193
2194 location().warning(u"Cannot find file to quote from: %1"_s.arg(filename), details);
2195
2196 // REMARK: The following is duplicated from
2197 // Doc::quoteFromFile. If, for some reason (such as a file
2198 // that is inaccessible), the quoting fails but, previously,
2199 // the logic duplicated here was still run.
2200 // This is not true anymore as quoteFromFile does require a
2201 // resolved file to be run now.
2202 // It is not entirely clear if this is required for the
2203 // semantics of DocParser to be preserved, but for the sake of
2204 // avoiding premature breakages this was retained.
2205 // Do note that this should be considered temporary as the
2206 // quoter state, if any will be preserved, should not be
2207 // managed in such a spread and unlocal way.
2208 m_quoter.reset();
2209
2210 if (!marker)
2211 marker = CodeMarker::markerForFileName(QString{});
2212 m_quoter.quoteFromFile(filename, QString{}, marker->markedUpCode(QString{}, nullptr, location()));
2213 } else
2214 Doc::quoteFromFile(location(), m_quoter, *maybe_resolved_file, marker);
2215}
2216
2217/*!
2218 Expands a macro in-place in input.
2219
2220 Expects the current \e pos in the input to point to a backslash, and the macro to have a
2221 default definition. Format-specific macros are not expanded.
2222
2223 Behavior depends on \a options:
2224
2225 \value ArgumentParsingOptions::Default
2226 Default macro expansion; the string following the backslash
2227 must be a macro with a default definition.
2228 \value ArgumentParsingOptions::Verbatim
2229 The string following the backslash is rendered verbatim;
2230 No macro expansion is performed.
2231 \value ArgumentParsingOptions::MacroArguments
2232 Used for parsing argument(s) for a macro. Allows expanding
2233 macros, and also preserves a subset of commands (formatting
2234 commands) within the macro argument.
2235
2236 \note In addition to macros, a valid use for a backslash in an argument include
2237 escaping non-alnum characters, and splitting a single argument across multiple
2238 lines by escaping newlines. Escaping is also handled here.
2239
2240 Returns \c true on successful macro expansion.
2241 */
2242bool DocParser::expandMacro(ArgumentParsingOptions options)
2243{
2244 Q_ASSERT(m_input[m_position].unicode() == '\\');
2245
2246 if (options == ArgumentParsingOptions::Verbatim)
2247 return false;
2248
2249 QString cmdStr;
2250 qsizetype backslashPos = m_position++;
2251 while (m_position < m_input.size() && m_input[m_position].isLetterOrNumber())
2252 cmdStr += m_input[m_position++];
2253
2254 m_endPosition = m_position;
2255 if (!cmdStr.isEmpty()) {
2256 if (s_utilities.macroHash.contains(cmdStr)) {
2257 const Macro &macro = s_utilities.macroHash.value(cmdStr);
2258 if (!macro.m_defaultDef.isEmpty()) {
2259 QString expanded = expandMacroToString(cmdStr, macro);
2260 m_input.replace(backslashPos, m_position - backslashPos, expanded);
2261 m_inputLength = m_input.size();
2262 m_position = backslashPos;
2263 return true;
2264 } else {
2265 location().warning("Macro '%1' does not have a default definition"_L1.arg(cmdStr));
2266 }
2267 } else {
2268 int cmd = s_utilities.cmdHash.value(cmdStr, NOT_A_CMD);
2269 m_position = backslashPos;
2270 if (options != ArgumentParsingOptions::MacroArguments
2271 || cmd == NOT_A_CMD || !cmds[cmd].is_formatting_command) {
2272 location().warning("Unknown macro '%1'"_L1.arg(cmdStr));
2273 ++m_position;
2274 }
2275 }
2276 } else if (m_input[m_position].isSpace()) {
2277 skipAllSpaces();
2278 } else if (m_input[m_position].unicode() == '\\') {
2279 // allow escaping a backslash
2280 m_input.remove(m_position--, 1);
2281 --m_inputLength;
2282 }
2283 return false;
2284}
2285
2286void DocParser::expandMacro(const QString &def, const QStringList &args)
2287{
2288 if (args.isEmpty()) {
2289 appendAtom(Atom(Atom::RawString, def));
2290 } else {
2291 QString rawString;
2292
2293 for (int j = 0; j < def.size(); ++j) {
2294 if (int paramNo = def[j].unicode(); paramNo >= 1 && paramNo <= args.length()) {
2295 if (!rawString.isEmpty()) {
2296 appendAtom(Atom(Atom::RawString, rawString));
2297 rawString.clear();
2298 }
2299 appendAtom(Atom(Atom::String, args[paramNo - 1]));
2300 } else {
2301 rawString += def[j];
2302 }
2303 }
2304 if (!rawString.isEmpty())
2305 appendAtom(Atom(Atom::RawString, rawString));
2306 }
2307}
2308
2309QString DocParser::expandMacroToString(const QString &name, const Macro &macro)
2310{
2311 const QString &def{macro.m_defaultDef};
2312 QString rawString;
2313
2314 if (macro.numParams == 0) {
2315 rawString = macro.m_defaultDef;
2316 } else {
2317 QStringList args{getMacroArguments(name, macro)};
2318
2319 for (int j = 0; j < def.size(); ++j) {
2320 int paramNo = def[j].unicode();
2321 rawString += (paramNo >= 1 && paramNo <= args.length()) ? args[paramNo - 1] : def[j];
2322 }
2323 }
2324 QString matchExpr{macro.m_otherDefs.value("match")};
2325 if (matchExpr.isEmpty())
2326 return rawString;
2327
2328 QString result;
2329 QRegularExpression re(matchExpr);
2330 int capStart = (re.captureCount() > 0) ? 1 : 0;
2331 qsizetype i = 0;
2332 QRegularExpressionMatch match;
2333 while ((match = re.match(rawString, i)).hasMatch()) {
2334 for (int c = capStart; c <= re.captureCount(); ++c)
2335 result += match.captured(c);
2336 i = match.capturedEnd();
2337 }
2338
2339 return result;
2340}
2341
2342Doc::Sections DocParser::getSectioningUnit()
2343{
2344 QString name = getOptionalArgument();
2345
2346 if (name == "section1") {
2347 return Doc::Section1;
2348 } else if (name == "section2") {
2349 return Doc::Section2;
2350 } else if (name == "section3") {
2351 return Doc::Section3;
2352 } else if (name == "section4") {
2353 return Doc::Section4;
2354 } else if (name.isEmpty()) {
2355 return Doc::NoSection;
2356 } else {
2357 location().warning(QStringLiteral("Invalid section '%1'").arg(name));
2358 return Doc::NoSection;
2359 }
2360}
2361
2362/*!
2363 Gets an argument that is enclosed in braces and returns it
2364 without the enclosing braces. On entry, the current character
2365 is the left brace. On exit, the current character is the one
2366 that comes after the right brace.
2367
2368 If \a options is ArgumentParsingOptions::Verbatim, no macro
2369 expansion is performed, nor is the returned string stripped
2370 of extra whitespace.
2371 */
2372QString DocParser::getBracedArgument(ArgumentParsingOptions options)
2373{
2374 QString arg;
2375 int delimDepth = 0;
2376 if (m_position < m_input.size() && m_input[m_position] == '{') {
2377 ++m_position;
2378 while (m_position < m_input.size() && delimDepth >= 0) {
2379 switch (m_input[m_position].unicode()) {
2380 case '{':
2381 ++delimDepth;
2382 arg += QLatin1Char('{');
2383 ++m_position;
2384 break;
2385 case '}':
2386 --delimDepth;
2387 if (delimDepth >= 0)
2388 arg += QLatin1Char('}');
2389 ++m_position;
2390 break;
2391 case '\\':
2392 if (!expandMacro(options))
2393 arg += m_input[m_position++];
2394 break;
2395 default:
2396 if (m_input[m_position].isSpace() && options != ArgumentParsingOptions::Verbatim)
2397 arg += QChar(' ');
2398 else
2399 arg += m_input[m_position];
2400 ++m_position;
2401 }
2402 }
2403 if (delimDepth > 0)
2404 location().warning(QStringLiteral("Missing '}'"));
2405 }
2406 m_endPosition = m_position;
2407 return arg;
2408}
2409
2410/*!
2411 Parses and returns an argument for a command, using
2412 specific parsing \a options.
2413
2414 Typically, an argument ends at the next white-space. However,
2415 braces can be used to group words:
2416
2417 {a few words}
2418
2419 Also, opening and closing parentheses have to match. Thus,
2420
2421 printf("%d\n", x)
2422
2423 is an argument too, although it contains spaces. Finally,
2424 trailing punctuation is not included in an argument, nor is 's.
2425*/
2426QString DocParser::getArgument(ArgumentParsingOptions options)
2427{
2428 skipSpacesOrOneEndl();
2429
2430 int delimDepth = 0;
2431 qsizetype startPos = m_position;
2432 QString arg = getBracedArgument(options);
2433 if (arg.isEmpty()) {
2434 while ((m_position < m_input.size())
2435 && ((delimDepth > 0) || ((delimDepth == 0) && !m_input[m_position].isSpace()))) {
2436 switch (m_input[m_position].unicode()) {
2437 case '(':
2438 case '[':
2439 case '{':
2440 ++delimDepth;
2441 arg += m_input[m_position];
2442 ++m_position;
2443 break;
2444 case ')':
2445 case ']':
2446 case '}':
2447 --delimDepth;
2448 if (m_position == startPos || delimDepth >= 0) {
2449 arg += m_input[m_position];
2450 ++m_position;
2451 }
2452 break;
2453 case '\\':
2454 if (!expandMacro(options))
2455 arg += m_input[m_position++];
2456 break;
2457 default:
2458 arg += m_input[m_position];
2459 ++m_position;
2460 }
2461 }
2462 m_endPosition = m_position;
2463 if ((arg.size() > 1) && (QString(".,:;!?").indexOf(m_input[m_position - 1]) != -1)
2464 && !arg.endsWith("...")) {
2465 arg.truncate(arg.size() - 1);
2466 --m_position;
2467 }
2468 if (arg.size() > 2 && m_input.mid(m_position - 2, 2) == "'s") {
2469 arg.truncate(arg.size() - 2);
2470 m_position -= 2;
2471 }
2472 }
2473 return arg.simplified();
2474}
2475
2476/*!
2477 Gets an argument that is enclosed in brackets and returns it
2478 without the enclosing brackets. On entry, the current character
2479 is the left bracket. On exit, the current character is the one
2480 that comes after the right bracket.
2481 */
2482QString DocParser::getBracketedArgument()
2483{
2484 QString arg;
2485 int delimDepth = 0;
2486 skipSpacesOrOneEndl();
2487 if (m_position < m_input.size() && m_input[m_position] == '[') {
2488 ++m_position;
2489 while (m_position < m_input.size() && delimDepth >= 0) {
2490 switch (m_input[m_position].unicode()) {
2491 case '[':
2492 ++delimDepth;
2493 arg += QLatin1Char('[');
2494 ++m_position;
2495 break;
2496 case ']':
2497 --delimDepth;
2498 if (delimDepth >= 0)
2499 arg += QLatin1Char(']');
2500 ++m_position;
2501 break;
2502 case '\\':
2503 arg += m_input[m_position];
2504 ++m_position;
2505 break;
2506 default:
2507 arg += m_input[m_position];
2508 ++m_position;
2509 }
2510 }
2511 if (delimDepth > 0)
2512 location().warning(QStringLiteral("Missing ']'"));
2513 }
2514 return arg;
2515}
2516
2517/*!
2518 Reads an optional bracketed language argument, updates the supplied
2519 \a marker to refer to an appropriate code marker for the language and
2520 returns a lower case representation of the language.
2521
2522 If no suitable marker is found, sets the marker to null and returns
2523 an empty string.
2524*/
2525QString DocParser::getLanguageArgument(CodeMarker **marker)
2526{
2527 QString value{};
2528 if (isLeftBracketAhead(0)) {
2529 value = getBracketedArgument();
2530 *marker = markerForLanguage(value);
2531 } else {
2532 value = ""_L1;
2533 *marker = nullptr;
2534 }
2535 return value.toLower();
2536}
2537
2538/*!
2539 Returns the list of arguments passed to a \a macro with name \a name.
2540
2541 If a macro takes more than a single argument, they are expected to be
2542 wrapped in braces.
2543*/
2544QStringList DocParser::getMacroArguments(const QString &name, const Macro &macro)
2545{
2546 QStringList args;
2547 for (int i = 0; i < macro.numParams; ++i) {
2548 if (macro.numParams == 1 || isLeftBraceAhead()) {
2549 args << getArgument(ArgumentParsingOptions::MacroArguments);
2550 } else {
2551 location().warning(QStringLiteral("Macro '\\%1' invoked with too few"
2552 " arguments (expected %2, got %3)")
2553 .arg(name)
2554 .arg(macro.numParams)
2555 .arg(i));
2556 break;
2557 }
2558 }
2559 return args;
2560}
2561
2562/*!
2563 Returns the next token as an optional argument unless the token is
2564 another command. The next token can be preceded by spaces and an optional
2565 newline.
2566*/
2567QString DocParser::getOptionalArgument()
2568{
2569 skipSpacesOrOneEndl();
2570 const bool nextIsCommand = m_position + 1 < m_input.size() && m_input[m_position] == '\\'
2571 && m_input[m_position + 1].isLetterOrNumber();
2572 const bool nextIsComment = m_position + 2 < m_input.size() && m_input[m_position] == '/'
2573 && m_input[m_position + 1] == '/' && m_input[m_position + 2] == '!';
2574 if (nextIsCommand || nextIsComment) {
2575 return QString();
2576 } else {
2577 return getArgument();
2578 }
2579}
2580
2581/*!
2582 \brief Create a string that may optionally span multiple lines as one line.
2583
2584 Process a block of text that may span multiple lines using trailing
2585 backslashes (`\`) as line continuation character. Trailing backslashes and
2586 any newline character that follow them are removed.
2587
2588 Returns a string as if it was one continuous line of text. If trailing
2589 backslashes are removed, the method returns a "simplified" QString, which
2590 means any sequence of internal whitespace is replaced with a single space.
2591
2592 Whitespace at the start and end is always removed from the returned string.
2593
2594 \sa QString::simplified(), QString::trimmed().
2595 */
2596QString DocParser::getRestOfLine()
2597{
2598 auto atLineEnd = [this]() -> bool {
2599 return m_position >= m_inputLength || m_input[m_position] == '\n'
2600 || m_input[m_position] == '\r';
2601 };
2602
2603 auto lineHasTrailingBackslash = [this, &atLineEnd](bool trailingBackslash) -> bool {
2604 while (!atLineEnd()) {
2605 if (m_input[m_position] == '\\' && !trailingBackslash) {
2606 trailingBackslash = true;
2607 ++m_position;
2608 skipSpacesOnLine();
2609 } else {
2610 trailingBackslash = false;
2611 ++m_position;
2612 }
2613 }
2614 return trailingBackslash;
2615 };
2616
2617 QString rest_of_line;
2618 skipSpacesOnLine();
2619 bool trailing_backslash{ false };
2620 bool return_simplified_string{ false };
2621
2622 for (qsizetype start_position = m_position; m_position < m_inputLength; ++m_position) {
2623 trailing_backslash = lineHasTrailingBackslash(trailing_backslash);
2624
2625 if (!rest_of_line.isEmpty())
2626 rest_of_line += QLatin1Char(' ');
2627 rest_of_line += m_input.sliced(start_position, m_position - start_position);
2628
2629 if (trailing_backslash) {
2630 rest_of_line.truncate(rest_of_line.lastIndexOf('\\'));
2631 return_simplified_string = true;
2632 }
2633
2634 if (m_position < m_inputLength && m_input[m_position] == '\r')
2635 ++m_position;
2636 if (m_position < m_inputLength && m_input[m_position] == '\n')
2637 ++m_position;
2638
2639 if (!trailing_backslash)
2640 break;
2641
2642 while (m_position < m_inputLength
2643 && (m_input[m_position] == '\r' || m_input[m_position] == '\n'))
2644 ++m_position;
2645
2646 start_position = m_position;
2647 }
2648
2649 if (return_simplified_string)
2650 return rest_of_line.simplified();
2651
2652 return rest_of_line.trimmed();
2653}
2654
2655/*!
2656 The metacommand argument is normally the remaining text to
2657 the right of the metacommand itself. The extra blanks are
2658 stripped and the argument string is returned.
2659 */
2660QString DocParser::getMetaCommandArgument(const QString &cmdStr)
2661{
2662 skipSpacesOnLine();
2663
2664 qsizetype begin = m_position;
2665 int parenDepth = 0;
2666
2667 while (m_position < m_input.size() && (m_input[m_position] != '\n' || parenDepth > 0)) {
2668 if (m_input.at(m_position) == '(')
2669 ++parenDepth;
2670 else if (m_input.at(m_position) == ')')
2671 --parenDepth;
2672 else if (m_input.at(m_position) == '\\' && expandMacro(ArgumentParsingOptions::Default))
2673 continue;
2674 ++m_position;
2675 }
2676 if (m_position == m_input.size() && parenDepth > 0) {
2677 m_position = begin;
2678 location().warning(QStringLiteral("Unbalanced parentheses in '%1'").arg(cmdStr));
2679 }
2680
2681 QString t = m_input.mid(begin, m_position - begin).simplified();
2682 skipSpacesOnLine();
2683 return t;
2684}
2685
2686QString DocParser::getUntilEnd(int cmd)
2687{
2688 int endCmd = endCmdFor(cmd);
2689 QRegularExpression rx("\\\\" + cmdName(endCmd) + "\\b");
2690 QString t;
2691 auto match = rx.match(m_input, m_position);
2692
2693 if (!match.hasMatch()) {
2694 location().warning(QStringLiteral("Missing '\\%1'").arg(cmdName(endCmd)));
2695 m_position = m_input.size();
2696 } else {
2697 qsizetype end = match.capturedStart();
2698 t = m_input.mid(m_position, end - m_position);
2699 m_position = match.capturedEnd();
2700 }
2701 return t;
2702}
2703
2704void DocParser::expandArgumentsInString(QString &str, const QStringList &args)
2705{
2706 if (args.isEmpty())
2707 return;
2708
2709 qsizetype paramNo;
2710 qsizetype j = 0;
2711 while (j < str.size()) {
2712 if (str[j] == '\\' && j < str.size() - 1 && (paramNo = str[j + 1].digitValue()) >= 1
2713 && paramNo <= args.size()) {
2714 const QString &r = args[paramNo - 1];
2715 str.replace(j, 2, r);
2716 j += qMin(1, r.size());
2717 } else {
2718 ++j;
2719 }
2720 }
2721}
2722
2723/*!
2724 Returns the marked-up code following the code-quoting command \a cmd, expanding
2725 any arguments passed in \a argStr.
2726
2727 Uses the \a marker to mark up the code. If it's \c nullptr, resolve the marker
2728 based on the topic and the quoted code itself.
2729*/
2730QString DocParser::getCode(int cmd, CodeMarker *marker, const QString &argStr)
2731{
2732 QString code = untabifyEtc(getUntilEnd(cmd));
2733 expandArgumentsInString(code, argStr.split(" ", Qt::SkipEmptyParts));
2734
2735 int indent = indentLevel(code);
2736 code = dedent(indent, code);
2737
2738 // If we're in a QML topic, check if the QML marker recognizes the code
2739 if (!marker && !m_private->m_topics.isEmpty()
2740 && m_private->m_topics[0].m_topic.startsWith("qml")) {
2741 auto qmlMarker = CodeMarker::markerForLanguage("QML");
2742 marker = (qmlMarker && qmlMarker->recognizeCode(code)) ? qmlMarker : nullptr;
2743 }
2744 if (marker == nullptr)
2745 marker = CodeMarker::markerForCode(code);
2746 return marker->markedUpCode(code, nullptr, location());
2747}
2748
2749bool DocParser::isBlankLine()
2750{
2751 qsizetype i = m_position;
2752
2753 while (i < m_inputLength && m_input[i].isSpace()) {
2754 if (m_input[i] == '\n')
2755 return true;
2756 ++i;
2757 }
2758 return false;
2759}
2760
2761bool DocParser::isLeftBraceAhead()
2762{
2763 int numEndl = 0;
2764 qsizetype i = m_position;
2765
2766 while (i < m_inputLength && m_input[i].isSpace() && numEndl < 2) {
2767 // ### bug with '\\'
2768 if (m_input[i] == '\n')
2769 numEndl++;
2770 ++i;
2771 }
2772 return numEndl < 2 && i < m_inputLength && m_input[i] == '{';
2773}
2774
2775bool DocParser::isLeftBracketAhead(int maxNewlines)
2776{
2777 int numEndl = 0;
2778 qsizetype i = m_position;
2779
2780 while (i < m_inputLength && m_input[i].isSpace() && numEndl < 2) {
2781 // ### bug with '\\'
2782 if (m_input[i] == '\n')
2783 numEndl++;
2784 ++i;
2785 }
2786 return numEndl <= maxNewlines && i < m_inputLength && m_input[i] == '[';
2787}
2788
2789/*!
2790 Skips to the next non-space character or EOL.
2791 */
2792void DocParser::skipSpacesOnLine()
2793{
2794 while ((m_position < m_input.size()) && m_input[m_position].isSpace()
2795 && (m_input[m_position].unicode() != '\n'))
2796 ++m_position;
2797}
2798
2799/*!
2800 Skips spaces and one EOL.
2801 */
2802void DocParser::skipSpacesOrOneEndl()
2803{
2804 qsizetype firstEndl = -1;
2805 while (m_position < m_input.size() && m_input[m_position].isSpace()) {
2806 QChar ch = m_input[m_position];
2807 if (ch == '\n') {
2808 if (firstEndl == -1) {
2809 firstEndl = m_position;
2810 } else {
2811 m_position = firstEndl;
2812 break;
2813 }
2814 }
2815 ++m_position;
2816 }
2817}
2818
2819void DocParser::skipAllSpaces()
2820{
2821 while (m_position < m_inputLength && m_input[m_position].isSpace())
2822 ++m_position;
2823}
2824
2825void DocParser::skipToNextPreprocessorCommand()
2826{
2827 QRegularExpression rx("\\\\‍(?:" + cmdName(CMD_IF) + QLatin1Char('|') + cmdName(CMD_ELSE)
2828 + QLatin1Char('|') + cmdName(CMD_ENDIF) + ")\\b");
2829 auto match = rx.match(m_input, m_position + 1); // ### + 1 necessary?
2830
2831 if (!match.hasMatch())
2832 m_position = m_input.size();
2833 else
2834 m_position = match.capturedStart();
2835}
2836
2838{
2839 switch (cmd) {
2840 case CMD_BADCODE:
2841 return CMD_ENDCODE;
2842 case CMD_CODE:
2843 return CMD_ENDCODE;
2844 case CMD_COMPARESWITH:
2845 return CMD_ENDCOMPARESWITH;
2846 case CMD_DETAILS:
2847 return CMD_ENDDETAILS;
2848 case CMD_DIV:
2849 return CMD_ENDDIV;
2850 case CMD_QML:
2851 return CMD_ENDQML;
2852 case CMD_FOOTNOTE:
2853 return CMD_ENDFOOTNOTE;
2854 case CMD_LEGALESE:
2855 return CMD_ENDLEGALESE;
2856 case CMD_LINK:
2857 return CMD_ENDLINK;
2858 case CMD_LIST:
2859 return CMD_ENDLIST;
2860 case CMD_OMIT:
2861 return CMD_ENDOMIT;
2862 case CMD_QUOTATION:
2863 return CMD_ENDQUOTATION;
2864 case CMD_RAW:
2865 return CMD_ENDRAW;
2866 case CMD_SECTION1:
2867 return CMD_ENDSECTION1;
2868 case CMD_SECTION2:
2869 return CMD_ENDSECTION2;
2870 case CMD_SECTION3:
2871 return CMD_ENDSECTION3;
2872 case CMD_SECTION4:
2873 return CMD_ENDSECTION4;
2874 case CMD_SIDEBAR:
2875 return CMD_ENDSIDEBAR;
2876 case CMD_TABLE:
2877 return CMD_ENDTABLE;
2878 case CMD_TOC:
2879 return CMD_ENDTOC;
2880 default:
2881 return cmd;
2882 }
2883}
2884
2885QString DocParser::cmdName(int cmd)
2886{
2887 return cmds[cmd].name;
2888}
2889
2890QString DocParser::endCmdName(int cmd)
2891{
2892 return cmdName(endCmdFor(cmd));
2893}
2894
2895QString DocParser::untabifyEtc(const QString &str)
2896{
2897 QString result;
2898 result.reserve(str.size());
2899 int column = 0;
2900
2901 for (const auto &character : str) {
2902 if (character == QLatin1Char('\r'))
2903 continue;
2904 if (character == QLatin1Char('\t')) {
2905 result += &" "[column % s_tabSize];
2906 column = ((column / s_tabSize) + 1) * s_tabSize;
2907 continue;
2908 }
2909 if (character == QLatin1Char('\n')) {
2910 while (result.endsWith(QLatin1Char(' ')))
2911 result.chop(1);
2912 result += character;
2913 column = 0;
2914 continue;
2915 }
2916 result += character;
2917 ++column;
2918 }
2919
2920 while (result.endsWith("\n\n"))
2921 result.truncate(result.size() - 1);
2922 while (result.startsWith(QLatin1Char('\n')))
2923 result = result.mid(1);
2924
2925 return result;
2926}
2927
2928int DocParser::indentLevel(const QString &str)
2929{
2930 int minIndent = INT_MAX;
2931 int column = 0;
2932
2933 for (const auto &character : str) {
2934 if (character == '\n') {
2935 column = 0;
2936 } else {
2937 if (character != ' ' && column < minIndent)
2938 minIndent = column;
2939 ++column;
2940 }
2941 }
2942 return minIndent;
2943}
2944
2945QString DocParser::dedent(int level, const QString &str)
2946{
2947 if (level == 0)
2948 return str;
2949
2950 QString result;
2951 int column = 0;
2952
2953 for (const auto &character : str) {
2954 if (character == QLatin1Char('\n')) {
2955 result += '\n';
2956 column = 0;
2957 } else {
2958 if (column >= level)
2959 result += character;
2960 ++column;
2961 }
2962 }
2963 return result;
2964}
2965
2966/*!
2967 Returns \c true if \a atom represents a code snippet.
2968 */
2969bool DocParser::isCode(const Atom *atom)
2970{
2971 Atom::AtomType type = atom->type();
2972 return (type == Atom::Code || type == Atom::Qml);
2973}
2974
2975/*!
2976 Returns \c true if \a atom represents quoting information.
2977 */
2978bool DocParser::isQuote(const Atom *atom)
2979{
2980 Atom::AtomType type = atom->type();
2981 return (type == Atom::CodeQuoteArgument || type == Atom::CodeQuoteCommand
2982 || type == Atom::SnippetCommand || type == Atom::SnippetIdentifier
2983 || type == Atom::SnippetLocation);
2984}
2985
2986/*!
2987 \internal
2988 Returns a marker for the given \a language.
2989 Returns \nullptr and warns if no suitable marker is found.
2990*/
2991CodeMarker *DocParser::markerForLanguage(const QString &language)
2992{
2993 CodeMarker *marker = CodeMarker::markerForLanguage(language.toLower());
2994 // Suppress warning for explicitly allowed languages.
2995 if (!marker && !s_allowedLanguages.contains(language, Qt::CaseInsensitive))
2996 location().warning(QStringLiteral("Unrecognized markup language '%1'").arg(language));
2997
2998 return marker;
2999}
3000
3001/*!
3002 \internal
3003 Processes the arguments passed to the \\compareswith block command.
3004 The arguments are stored as text within the first atom of the block
3005 (Atom::ComparesLeft).
3006
3007 Extracts the comparison category and the list of types, and stores
3008 the information into a map accessed via \a priv.
3009*/
3010static void processComparesWithCommand(DocPrivate *priv, const Location &location)
3011{
3012 static auto take_while = [](QStringView input, auto predicate) {
3013 QStringView::size_type end{0};
3014
3015 while (end < input.size() && std::invoke(predicate, input[end]))
3016 ++end;
3017
3018 return std::make_tuple(input.sliced(0, end), input.sliced(end));
3019 };
3020
3021 static auto peek = [](QStringView input, QChar c) {
3022 return !input.empty() && input.first() == c;
3023 };
3024
3025 static auto skip_one = [](QStringView input) {
3026 if (input.empty()) return std::make_tuple(QStringView{}, input);
3027 else return std::make_tuple(input.sliced(0, 1), input.sliced(1));
3028 };
3029
3030 static auto enclosed = [](QStringView input, QChar open, QChar close) {
3031 if (!peek(input, open)) return std::make_tuple(QStringView{}, input);
3032
3033 auto [opened, without_open] = skip_one(input);
3034 auto [parsed, remaining] = take_while(without_open, [close](QChar c){ return c != close; });
3035
3036 if (remaining.empty()) return std::make_tuple(QStringView{}, input);
3037
3038 auto [closed, without_close] = skip_one(remaining);
3039
3040 return std::make_tuple(parsed.trimmed(), without_close);
3041 };
3042
3043 static auto one_of = [](auto first, auto second) {
3044 return [first, second](QStringView input) {
3045 auto [parsed, remaining] = std::invoke(first, input);
3046
3047 if (parsed.empty()) return std::invoke(second, input);
3048 else return std::make_tuple(parsed, remaining);
3049 };
3050 };
3051
3052 static auto collect = [](QStringView input, auto parser) {
3053 QStringList collected{};
3054
3055 while (true) {
3056 auto [parsed, remaining] = std::invoke(parser, input);
3057
3058 if (parsed.empty()) break;
3059 collected.append(parsed.toString());
3060
3061 input = remaining;
3062 };
3063
3064 return collected;
3065 };
3066
3067 static auto spaces = [](QStringView input) {
3068 return take_while(input, [](QChar c){ return c.isSpace(); });
3069 };
3070
3071 static auto word = [](QStringView input) {
3072 return take_while(input, [](QChar c){ return !c.isSpace(); });
3073 };
3074
3075 static auto parse_argument = [](QStringView input) {
3076 auto [_, without_spaces] = spaces(input);
3077
3078 return one_of(
3079 [](QStringView input){ return enclosed(input, '{', '}'); },
3080 word
3081 )(without_spaces);
3082 };
3083
3084 const QString cmd{DocParser::cmdName(CMD_COMPARESWITH)};
3086
3087 auto *atom = text.firstAtom();
3088 QStringList segments = collect(atom->string(), parse_argument);
3089
3090 QString categoryString;
3091 if (!segments.isEmpty())
3092 categoryString = segments.takeFirst();
3093 auto category = comparisonCategoryFromString(categoryString.toStdString());
3094
3095 if (category == ComparisonCategory::None) {
3096 location.warning(u"Invalid argument to \\%1 command: `%2`"_s.arg(cmd, categoryString),
3097 u"Valid arguments are `strong`, `weak`, `partial`, or `equality`."_s);
3098 return;
3099 }
3100
3101 if (segments.isEmpty()) {
3102 location.warning(u"Missing argument to \\%1 command."_s.arg(cmd),
3103 u"Provide at least one type name, or a list of types separated by spaces."_s);
3104 return;
3105 }
3106
3107 // Store cleaned-up type names back into the atom
3108 segments.removeDuplicates();
3109 atom->setString(segments.join(QLatin1Char(';')));
3110
3111 // Add an entry to meta-command map for error handling in CppCodeParser
3112 priv->m_metaCommandMap[cmd].append(ArgPair(categoryString, atom->string()));
3113 priv->m_metacommandsUsed.insert(cmd);
3114
3116 const auto end{priv->extra->m_comparesWithMap.cend()};
3117 priv->extra->m_comparesWithMap.insert(end, category, text);
3118}
3119
3120QT_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_FORMATTING_SPAN
Definition atom.h:203
#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
AtomType
\value AnnotatedList \value AutoLink \value BaseName \value BriefLeft \value BriefRight \value C \val...
Definition atom.h:21
@ ListTagLeft
Definition atom.h:69
@ TableRight
Definition atom.h:99
@ DivRight
Definition atom.h:44
@ CodeQuoteArgument
Definition atom.h:33
@ WarningLeft
Definition atom.h:112
@ TableOfContentsLeft
Definition atom.h:106
@ SidebarLeft
Definition atom.h:89
@ TableOfContentsRight
Definition atom.h:107
@ Keyword
Definition atom.h:61
@ TableHeaderRight
Definition atom.h:101
@ FormatElse
Definition atom.h:49
@ InlineImage
Definition atom.h:60
@ TableRowRight
Definition atom.h:103
@ FootnoteRight
Definition atom.h:48
@ SnippetCommand
Definition atom.h:94
@ TableRowLeft
Definition atom.h:102
@ Nop
Definition atom.h:76
@ LegaleseRight
Definition atom.h:63
@ ListTagRight
Definition atom.h:70
@ SinceTagRight
Definition atom.h:93
@ DetailsLeft
Definition atom.h:39
@ RawString
Definition atom.h:84
@ Target
Definition atom.h:108
@ SectionHeadingLeft
Definition atom.h:87
@ ListItemRight
Definition atom.h:72
@ DeprecatedLeft
Definition atom.h:37
@ TitleLeft
Definition atom.h:109
@ Image
Definition atom.h:56
@ TableItemRight
Definition atom.h:105
@ ListItemLeft
Definition atom.h:71
@ Code
Definition atom.h:31
@ String
Definition atom.h:97
@ ListLeft
Definition atom.h:67
@ CodeQuoteCommand
Definition atom.h:34
@ ImageText
Definition atom.h:57
@ LegaleseLeft
Definition atom.h:62
@ ListRight
Definition atom.h:73
@ C
Definition atom.h:28
@ Qml
Definition atom.h:81
@ FormattingLeft
Definition atom.h:52
@ FormattingRight
Definition atom.h:53
@ ImportantLeft
Definition atom.h:58
@ FormatEndif
Definition atom.h:50
@ SinceTagLeft
Definition atom.h:92
@ BR
Definition atom.h:25
@ DetailsRight
Definition atom.h:40
@ FootnoteLeft
Definition atom.h:47
@ AutoLink
Definition atom.h:23
@ SnippetLocation
Definition atom.h:96
@ TableHeaderLeft
Definition atom.h:100
@ ComparesRight
Definition atom.h:36
@ QuotationLeft
Definition atom.h:82
@ HR
Definition atom.h:55
@ DivLeft
Definition atom.h:43
@ QuotationRight
Definition atom.h:83
@ ParaLeft
Definition atom.h:79
@ ComparesLeft
Definition atom.h:35
@ FormatIf
Definition atom.h:51
@ TitleRight
Definition atom.h:110
@ SnippetIdentifier
Definition atom.h:95
@ NoteLeft
Definition atom.h:77
@ SidebarRight
Definition atom.h:90
@ UnknownCommand
Definition atom.h:114
@ DetailsSummaryLeft
Definition atom.h:41
void chopString()
\also string()
Definition atom.h:136
virtual Atom::AtomType atomType() const
Definition codemarker.h:24
The Config class contains the configuration variables for controlling how qdoc produces documentation...
Definition config.h:95
static QStringList s_allowedLanguages
Definition docparser.h:43
static QStringList s_ignoreWords
Definition docparser.h:44
void parse(const QString &source, DocPrivate *docPrivate, const QSet< QString > &metaCommandSet, const QSet< QString > &possibleTopics)
Parse the source string to build a Text data structure in docPrivate.
static bool s_quoting
Definition docparser.h:45
static int endCmdFor(int cmd)
static void initialize(const Config &config, FileResolver &file_resolver)
static int s_tabSize
Definition docparser.h:42
Text m_title
Definition docprivate.h:61
DocPrivateExtra * extra
Definition docprivate.h:68
void constructExtra()
Text m_text
Definition docprivate.h:60
bool m_hasLegalese
Definition docprivate.h:71
void addAlso(const Text &also)
TopicList m_topics
Definition docprivate.h:69
CommandMap m_metaCommandMap
Definition docprivate.h:67
Definition doc.h:32
static void quoteFromFile(const Location &location, Quoter &quoter, ResolvedFile resolved_file, CodeMarker *marker=nullptr)
Definition doc.cpp:468
Sections
Definition doc.h:35
@ NoSection
Definition doc.h:36
@ Section3
Definition doc.h:39
@ Section1
Definition doc.h:37
@ Section2
Definition doc.h:38
@ Section4
Definition doc.h:40
Encapsulate the logic that QDoc uses to find files whose path is provided by the user and that are re...
The Location class provides a way to mark a location in a file.
Definition location.h:20
int depth() const
Definition location.h:46
Definition text.h:12
static Text subText(const Atom *begin, const Atom *end=nullptr)
Definition text.cpp:238
Text splitAtFirst(Atom::AtomType start)
Splits the current Text from start to end into a new Text object.
Definition text.cpp:290
void stripFirstAtom()
Definition text.cpp:72
Atom * firstAtom()
Definition text.h:21
Text & operator=(const Text &text)
Definition text.cpp:29
void stripLastAtom()
Definition text.cpp:83
Atom * lastAtom()
Definition text.h:22
#define CONFIG_TABSIZE
Definition config.h:462
#define CONFIG_IGNOREWORDS
Definition config.h:415
#define CONFIG_CODELANGUAGES
Definition config.h:387
#define CONFIG_QUOTINGINFORMATION
Definition config.h:450
std::pair< QString, QString > ArgPair
Definition doc.h:27
static void warnAboutEmptyOrPreexistingTarget(const Location &location, const QString &duplicateDefinition, const QString &cmdString, const QString &previousDefinition)
static void processComparesWithCommand(DocPrivate *priv, const Location &location)
@ CMD_OVERLOAD
Definition docparser.cpp:88
@ CMD_UICONTROL
@ CMD_HEADER
Definition docparser.cpp:66
@ CMD_QUOTATION
Definition docparser.cpp:92
@ CMD_LEGALESE
Definition docparser.cpp:78
@ CMD_DOTS
Definition docparser.cpp:42
@ CMD_OMITVALUE
Definition docparser.cpp:87
@ CMD_ENDSECTION2
Definition docparser.cpp:59
@ CMD_INDEX
Definition docparser.cpp:74
@ CMD_INCLUDE
Definition docparser.cpp:72
@ CMD_PRINTUNTIL
Definition docparser.cpp:91
@ CMD_QUOTEFILE
Definition docparser.cpp:93
@ CMD_FOOTNOTE
Definition docparser.cpp:64
@ CMD_ENDDETAILS
Definition docparser.cpp:47
@ CMD_SNIPPET
@ CMD_TABLEOFCONTENTS
@ CMD_GENERATELIST
Definition docparser.cpp:65
@ CMD_SECTION2
Definition docparser.cpp:99
@ CMD_UNDERLINE
@ CMD_UNICODE
@ CMD_ENDLEGALESE
Definition docparser.cpp:51
@ CMD_TOCENTRY
@ CMD_TT
@ CMD_NOTRANSLATE
Definition docparser.cpp:84
@ CMD_DIV
Definition docparser.cpp:41
@ CMD_I
Definition docparser.cpp:68
@ CMD_META
Definition docparser.cpp:82
@ CMD_SKIPLINE
@ CMD_BADCODE
Definition docparser.cpp:31
@ CMD_ENDOMIT
Definition docparser.cpp:55
@ CMD_CPP
@ CMD_TARGET
@ CMD_TOC
@ CMD_A
Definition docparser.cpp:28
@ CMD_SIDEBAR
@ CMD_HR
Definition docparser.cpp:67
@ CMD_INPUT
Definition docparser.cpp:75
@ CMD_ENDMAPREF
Definition docparser.cpp:54
@ CMD_SKIPUNTIL
@ CMD_TM
@ CMD_CODE
Definition docparser.cpp:37
@ CMD_COMPARESWITH
Definition docparser.cpp:39
@ CMD_SUP
@ CMD_SKIPTO
@ CMD_ENDQML
@ CMD_ENDLINK
Definition docparser.cpp:52
@ CMD_ENDCPPTEXT
@ CMD_LIST
Definition docparser.cpp:81
@ CMD_ENDSECTION3
Definition docparser.cpp:60
@ CMD_SECTION4
@ CMD_ENDCPP
@ CMD_QML
@ CMD_SINCELIST
@ CMD_ENDIF
Definition docparser.cpp:50
@ CMD_LINK
Definition docparser.cpp:80
@ CMD_CPPTEXT
@ CMD_PRINTLINE
Definition docparser.cpp:89
@ CMD_RAW
Definition docparser.cpp:95
@ CMD_ROW
Definition docparser.cpp:96
@ CMD_ENDTABLE
Definition docparser.cpp:63
@ CMD_SUB
@ CMD_NOTE
Definition docparser.cpp:83
@ CMD_DETAILS
Definition docparser.cpp:40
@ CMD_CAPTION
Definition docparser.cpp:36
@ CMD_ENDCODE
Definition docparser.cpp:45
@ CMD_KEYWORD
Definition docparser.cpp:76
@ CMD_B
Definition docparser.cpp:30
@ CMD_ELSE
Definition docparser.cpp:44
@ CMD_ENDRAW
Definition docparser.cpp:57
@ CMD_ENDDIV
Definition docparser.cpp:48
@ CMD_ANNOTATEDLIST
Definition docparser.cpp:29
@ CMD_E
Definition docparser.cpp:43
@ CMD_SECTION3
@ CMD_WARNING
@ CMD_C
Definition docparser.cpp:35
@ NOT_A_CMD
@ CMD_ENDTOC
@ CMD_SECTION1
Definition docparser.cpp:98
@ CMD_IMAGE
Definition docparser.cpp:70
@ CMD_ENDSECTION4
Definition docparser.cpp:61
@ CMD_BR
Definition docparser.cpp:33
@ CMD_INLINEIMAGE
Definition docparser.cpp:73
@ CMD_SA
Definition docparser.cpp:97
@ CMD_CODELINE
Definition docparser.cpp:38
@ CMD_ENDCOMPARESWITH
Definition docparser.cpp:46
@ CMD_BOLD
Definition docparser.cpp:32
@ CMD_ENDQUOTATION
Definition docparser.cpp:56
@ CMD_L
Definition docparser.cpp:77
@ CMD_IMPORTANT
Definition docparser.cpp:71
@ CMD_ENDSECTION1
Definition docparser.cpp:58
@ CMD_TITLE
@ CMD_ENDFOOTNOTE
Definition docparser.cpp:49
@ CMD_ENDLIST
Definition docparser.cpp:53
@ CMD_QUOTEFROMFILE
Definition docparser.cpp:94
@ CMD_LI
Definition docparser.cpp:79
@ CMD_IF
Definition docparser.cpp:69
@ CMD_ENDSIDEBAR
Definition docparser.cpp:62
@ CMD_PRINTTO
Definition docparser.cpp:90
@ CMD_O
Definition docparser.cpp:85
@ CMD_BRIEF
Definition docparser.cpp:34
@ CMD_OMIT
Definition docparser.cpp:86
@ CMD_VALUE
@ CMD_SPAN
@ CMD_TABLE
static QString cleanLink(const QString &link)
Returns a cleaned version of the given link text.
Combined button and popup list for selecting options.
QStringMultiMap m_metaMap
Definition docprivate.h:38
QHash_QString_Macro macroHash
QHash_QString_int cmdHash
Simple structure used by the Doc and DocParser classes.
int numParams
Definition macro.h:22
Definition topic.h:9