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
moc.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2019 Olivier Goffart <ogoffart@woboq.com>
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
4
5#include "moc.h"
6#include "generator.h"
7#include "qdatetime.h"
8#include "utils.h"
10#include <QtCore/qfile.h>
11#include <QtCore/qfileinfo.h>
12#include <QtCore/qdir.h>
13#include <QtCore/qjsondocument.h>
14
15// for normalizeTypeInternal
16#include <private/qmetaobject_p.h>
17#include <private/qmetaobject_moc_p.h>
18#include <private/qduplicatetracker_p.h>
19
20QT_BEGIN_NAMESPACE
21
22using namespace Qt::StringLiterals;
23
24// only moc needs this function
25static QByteArray normalizeType(const QByteArray &ba)
26{
27 return ba.size() ? normalizeTypeInternal(ba.constBegin(), ba.constEnd()) : ba;
28}
29
30const QByteArray &Moc::toFullyQualified(const QByteArray &name) const noexcept
31{
32 if (auto it = knownQObjectClasses.find(name); it != knownQObjectClasses.end())
33 return it.value();
34 if (auto it = knownGadgets.find(name); it != knownGadgets.end())
35 return it.value();
36 return name;
37}
38
40{
41 // figure out whether this is a class declaration, or only a
42 // forward or variable declaration.
43 int i = 0;
44 Token token;
45 do {
46 token = lookup(i++);
47 if (token == COLON || token == LBRACE)
48 break;
49 if (token == SEMIC || token == RANGLE)
50 return false;
51 } while (token);
52
53 // support attributes like "class [[deprecated]]] name"
55
56 if (!test(IDENTIFIER)) // typedef struct { ... }
57 return false;
58 QByteArray name = lexem();
59
60 // support "class IDENT name" and "class IDENT(IDENT) name"
61 // also support "class IDENT name (final|sealed|Q_DECL_FINAL)"
62 if (test(LPAREN)) {
63 until(RPAREN);
64 if (!test(IDENTIFIER))
65 return false;
66 name = lexem();
67 } else if (test(IDENTIFIER)) {
68 const QByteArrayView lex = lexemView();
69 if (lex != "final" && lex != "sealed" && lex != "Q_DECL_FINAL")
70 name = lexem();
71 else
72 def->isFinal = true;
73 }
74
75 def->qualified += name;
76 while (test(SCOPE)) {
77 def->qualified += lexemView();
78 if (test(IDENTIFIER)) {
79 name = lexem();
80 def->qualified += name;
81 }
82 }
83 def->classname = name;
84 def->lineNumber = symbol().lineNum;
85
86 if (test(IDENTIFIER)) {
87 const QByteArrayView lex = lexemView();
88 if (lex != "final" && lex != "sealed" && lex != "Q_DECL_FINAL")
89 return false;
90 else
91 def->isFinal = true;
92 }
93
94 if (test(COLON)) {
95 do {
96 test(VIRTUAL);
98 if (test(PRIVATE))
99 access = FunctionDef::Private;
100 else if (test(PROTECTED))
101 access = FunctionDef::Protected;
102 else
103 test(PUBLIC);
104 test(VIRTUAL);
105 const Type type = parseType();
106 // ignore the 'class Foo : BAR(Baz)' case
107 if (test(LPAREN)) {
108 until(RPAREN);
109 } else {
110 def->superclassList.push_back({type.name, toFullyQualified(type.name), access});
111 }
112 } while (test(COMMA));
113
114 if (!def->superclassList.isEmpty()
115 && knownGadgets.contains(def->superclassList.constFirst().classname)) {
116 // Q_GADGET subclasses are treated as Q_GADGETs
117 knownGadgets.insert(def->classname, def->qualified);
118 knownGadgets.insert(def->qualified, def->qualified);
119 }
120 }
121 if (!test(LBRACE))
122 return false;
123 def->begin = index - 1;
124 bool foundRBrace = until(RBRACE);
125 def->end = index;
126 index = def->begin + 1;
127 return foundRBrace;
128}
129
131{
132 Type type;
133 bool hasSignedOrUnsigned = false;
134 bool isVoid = false;
135 type.firstToken = lookup();
136 for (;;) {
138 switch (next()) {
139 case SIGNED:
140 case UNSIGNED:
141 hasSignedOrUnsigned = true;
142 Q_FALLTHROUGH();
143 case CONST:
144 case VOLATILE:
145 type.name += lexemView();
146 type.name += ' ';
147 if (lookup(0) == VOLATILE)
148 type.isVolatile = true;
149 continue;
150 case Q_MOC_COMPAT_TOKEN:
151 case Q_INVOKABLE_TOKEN:
152 case Q_SCRIPTABLE_TOKEN:
153 case Q_SIGNALS_TOKEN:
154 case Q_SLOTS_TOKEN:
155 case Q_SIGNAL_TOKEN:
156 case Q_SLOT_TOKEN:
157 type.name += lexemView();
158 return type;
159 case NOTOKEN:
160 return type;
161 default:
162 prev();
163 break;
164 }
165 break;
166 }
167
169 if (test(ENUM))
170 type.typeTag = TypeTag::HasEnum;
171 if (test(CLASS))
172 type.typeTag |= TypeTag::HasClass;
173 if (test(STRUCT))
174 type.typeTag |= TypeTag::HasStruct;
175 for(;;) {
177 switch (next()) {
178 case IDENTIFIER:
179 // void mySlot(unsigned myArg)
180 if (hasSignedOrUnsigned) {
181 prev();
182 break;
183 }
184 Q_FALLTHROUGH();
185 case CHAR:
186 case SHORT:
187 case INT:
188 case LONG:
189 type.name += lexemView();
190 // preserve '[unsigned] long long', 'short int', 'long int', 'long double'
191 if (test(LONG) || test(INT) || test(DOUBLE)) {
192 type.name += ' ';
193 prev();
194 continue;
195 }
196 break;
197 case FLOAT:
198 case DOUBLE:
199 case VOID:
200 case BOOL:
201 case AUTO:
202 type.name += lexemView();
203 isVoid |= (lookup(0) == VOID);
204 break;
205 case NOTOKEN:
206 return type;
207 default:
208 prev();
209 ;
210 }
211 if (test(LANGLE)) {
212 if (type.name.isEmpty()) {
213 // '<' cannot start a type
214 return type;
215 }
216 type.name += lexemUntil(RANGLE);
217 }
218 if (test(SCOPE)) {
219 type.name += lexemView();
220 type.isScoped = true;
221 } else {
222 break;
223 }
224 }
225 while (test(CONST) || test(VOLATILE) || test(SIGNED) || test(UNSIGNED)
226 || test(STAR) || test(AND) || test(ANDAND)) {
227 type.name += ' ';
228 type.name += lexemView();
229 if (lookup(0) == AND)
230 type.referenceType = Type::Reference;
231 else if (lookup(0) == ANDAND)
232 type.referenceType = Type::RValueReference;
233 else if (lookup(0) == STAR)
234 type.referenceType = Type::Pointer;
235 }
236 type.rawName = type.name;
237 // transform stupid things like 'const void' or 'void const' into 'void'
238 if (isVoid && type.referenceType == Type::NoReference) {
239 type.name = "void";
240 }
241 return type;
242}
243
249
250bool Moc::parseEnum(EnumDef *def, ClassDef *containingClass)
251{
252 bool isTypdefEnum = false; // typedef enum { ... } Foo;
253
254 if (test(CLASS) || test(STRUCT))
255 def->flags |= EnumIsScoped;
256
257 if (test(IDENTIFIER)) {
258 def->name = lexem();
259 if (containingClass)
260 containingClass->allEnumNames.insert(def->name);
261 } else {
262 if (lookup(-1) != TYPEDEF)
263 return false; // anonymous enum
264 isTypdefEnum = true;
265 }
266 def->lineNumber = symbol().lineNum;
267 if (test(COLON)) { // C++11 strongly typed enum
268 // enum Foo : unsigned long { ... };
269 def->type = normalizeType(parseType().name);
270 }
271 if (!test(LBRACE))
272 return false;
273 auto handleInclude = [this]() -> IncludeState {
274 bool hadIncludeBegin = false;
275 if (test(MOC_INCLUDE_BEGIN)) {
276 currentFilenames.push(symbol().unquotedLexem());
277 // we do not return early to handle empty headers in one go
278 hadIncludeBegin = true;
279 }
280 if (test(NOTOKEN)) {
281 next(MOC_INCLUDE_END);
282 currentFilenames.pop();
284 }
285 if (hadIncludeBegin)
287 else
289 };
290 do {
291 handleInclude();
292 if (lookup() == RBRACE) // accept trailing comma
293 break;
294 next(IDENTIFIER);
295 def->values += lexem();
296 handleInclude();
298 } while (test(EQ) ? until(COMMA) : test(COMMA));
299 next(RBRACE);
300 if (isTypdefEnum) {
301 if (!test(IDENTIFIER))
302 return false;
303 def->name = lexem();
304 // used as the name for our enum, but we don't track it,
305 // because we only care about types that might conflict with members
306 }
307 return true;
308}
309
311{
312 Q_UNUSED(def);
313 while (hasNext()) {
314 ArgumentDef arg;
315 arg.type = parseType();
316 if (arg.type.name == "void")
317 break;
318 if (test(IDENTIFIER))
319 arg.name = lexem();
320 while (test(LBRACK)) {
321 arg.rightType += lexemUntil(RBRACK);
322 }
323 if (test(CONST) || test(VOLATILE)) {
324 arg.rightType += ' ';
325 arg.rightType += lexemView();
326 }
327 arg.normalizedType = normalizeType(QByteArray(arg.type.name + ' ' + arg.rightType));
328 if (test(EQ))
329 arg.isDefault = true;
330 def->arguments += arg;
331 if (!until(COMMA))
332 break;
333 }
334
335 if (!def->arguments.isEmpty()
336 && def->arguments.constLast().normalizedType == "QPrivateSignal") {
337 def->arguments.removeLast();
338 def->isPrivateSignal = true;
339 }
340 if (def->arguments.size() == 1
341 && def->arguments.constLast().normalizedType == "QMethodRawArguments") {
342 def->arguments.removeLast();
343 def->isRawSlot = true;
344 }
345
346 if (Q_UNLIKELY(def->arguments.size() >= std::numeric_limits<int>::max()))
347 error("number of function arguments exceeds std::numeric_limits<int>::max()");
348}
349
351{
352 if (index < symbols.size() && testFunctionAttribute(symbols.at(index).token, def)) {
353 ++index;
354 return true;
355 }
356 return false;
357}
358
360{
361 switch (tok) {
362 case Q_MOC_COMPAT_TOKEN:
363 def->isCompat = true;
364 return true;
365 case Q_INVOKABLE_TOKEN:
366 def->isInvokable = true;
367 return true;
368 case Q_SIGNAL_TOKEN:
369 def->isSignal = true;
370 return true;
371 case Q_SLOT_TOKEN:
372 def->isSlot = true;
373 return true;
374 case Q_SCRIPTABLE_TOKEN:
375 def->isInvokable = def->isScriptable = true;
376 return true;
377 default: break;
378 }
379 return false;
380}
381
383{
384 auto rewind = index;
385 if (test(LBRACK) && test(LBRACK) && until(RBRACK) && test(RBRACK))
386 return true;
387 index = rewind;
388 return false;
389}
390
392{
393 next(LPAREN);
394 QByteArray revisionString = lexemUntil(RPAREN);
395 revisionString.remove(0, 1);
396 revisionString.chop(1);
397 const QList<QByteArray> majorMinor = revisionString.split(',');
398 switch (majorMinor.size()) {
399 case 1: {
400 bool ok = false;
401 const int revision = revisionString.toInt(&ok);
402 if (!ok || !QTypeRevision::isValidSegment(revision))
403 error("Invalid revision");
404 return QTypeRevision::fromMinorVersion(revision);
405 }
406 case 2: { // major.minor
407 bool ok = false;
408 const int major = majorMinor[0].toInt(&ok);
409 if (!ok || !QTypeRevision::isValidSegment(major))
410 error("Invalid major version");
411 const int minor = majorMinor[1].toInt(&ok);
412 if (!ok || !QTypeRevision::isValidSegment(minor))
413 error("Invalid minor version");
414 return QTypeRevision::fromVersion(major, minor);
415 }
416 default:
417 error("Invalid revision");
418 return QTypeRevision();
419 }
420}
421
423{
424
425 if (test(Q_REVISION_TOKEN)) {
426 def->revision = parseRevision().toEncodedVersion<int>();
427 return true;
428 }
429
430 return false;
431}
432
433// returns false if the function should be ignored
434bool Moc::parseFunction(FunctionDef *def, bool inMacro)
435{
436 def->isVirtual = false;
437 def->isStatic = false;
438 //skip modifiers and attributes
441 bool templateFunction = (lookup() == TEMPLATE);
442 def->type = parseType();
443 if (def->type.name.isEmpty()) {
444 if (templateFunction)
445 error("Template function as signal or slot");
446 else
447 error();
448 }
449 bool scopedFunctionName = false;
450 // we might have modifiers and attributes after a tag
451 // note that testFunctionAttribute is handled further below,
452 // and revisions and attributes must come first
453 while (testForFunctionModifiers(def)) {}
454 Type tempType = parseType();
455 while (!tempType.name.isEmpty() && lookup() != LPAREN) {
456 if (testFunctionAttribute(def->type.firstToken, def))
457 ; // fine
458 else if (def->type.firstToken == Q_SIGNALS_TOKEN)
459 error();
460 else if (def->type.firstToken == Q_SLOTS_TOKEN)
461 error();
462 else {
463 if (!def->tag.isEmpty())
464 def->tag += ' ';
465 def->tag += def->type.name;
466 }
467 def->type = tempType;
468 tempType = parseType();
469 }
470 next(LPAREN, "Not a signal or slot declaration");
471 def->name = tempType.name;
472 def->lineNumber = symbol().lineNum;
473
474 scopedFunctionName = tempType.isScoped;
475
476 if (!test(RPAREN)) {
478 next(RPAREN);
479 }
480
481 // support optional macros with compiler specific options
482 while (test(IDENTIFIER))
483 ;
484
485 def->isConst = test(CONST);
486
487 while (test(IDENTIFIER))
488 ;
489
490 if (inMacro) {
491 next(RPAREN);
492 prev();
493 } else {
494 if (test(THROW)) {
495 next(LPAREN);
496 until(RPAREN);
497 }
498
499 if (def->type.name == "auto" && test(ARROW))
500 def->type = parseType(); // Parse trailing return-type
501
502 if (test(SEMIC))
503 ;
504 else if ((def->inlineCode = test(LBRACE)))
505 until(RBRACE);
506 else if ((def->isAbstract = test(EQ)))
507 until(SEMIC);
508 else if (skipCxxAttributes())
509 until(SEMIC);
510 else
511 error();
512 }
513 if (scopedFunctionName) {
514 const QByteArray msg = "Function declaration " + def->name
515 + " contains extra qualification. Ignoring as signal or slot.";
516 warning(msg.constData());
517 return false;
518 }
519
520 QList<QByteArray> typeNameParts = normalizeType(def->type.name).split(' ');
521 if (typeNameParts.contains("auto")) {
522 // We expected a trailing return type but we haven't seen one
523 error("Function declared with auto as return type but missing trailing return type. "
524 "Return type deduction is not supported.");
525 }
526
527 // we don't support references as return types, it's too dangerous
528 if (def->type.referenceType == Type::Reference) {
529 QByteArray rawName = def->type.rawName;
530 def->type = Type("void");
531 def->type.rawName = rawName;
532 }
533
534 def->normalizedType = normalizeType(def->type.name);
535 return true;
536}
537
539{
540 return test(EXPLICIT) || test(INLINE) || test(CONSTEXPR) ||
541 (test(STATIC) && (def->isStatic = true)) ||
542 (test(VIRTUAL) && (def->isVirtual = true));
543}
544
545// like parseFunction, but never aborts with an error
547{
548 def->isVirtual = false;
549 def->isStatic = false;
550 //skip modifiers and attributes
553 bool tilde = test(TILDE);
554 def->type = parseType();
555 if (def->type.name.isEmpty())
556 return false;
557 bool scopedFunctionName = false;
558 if (test(LPAREN)) {
559 def->name = def->type.name;
560 def->lineNumber = symbol().lineNum;
561 scopedFunctionName = def->type.isScoped;
562 if (def->name == cdef->classname) {
563 def->isDestructor = tilde;
564 def->isConstructor = !tilde;
565 def->type = Type();
566 } else {
567 // missing type name? => Skip
568 return false;
569 }
570 } else {
571 // ### TODO: The condition before testForFunctionModifiers shoulnd't be necessary,
572 // but otherwise we end up with misparses
573 if (def->isSlot || def->isSignal || def->isInvokable)
574 while (testForFunctionModifiers(def)) {}
575 Type tempType = parseType();
576 while (!tempType.name.isEmpty() && lookup() != LPAREN) {
577 if (testFunctionAttribute(def->type.firstToken, def))
578 ; // fine
579 else if (def->type.name == "Q_SIGNAL")
580 def->isSignal = true;
581 else if (def->type.name == "Q_SLOT")
582 def->isSlot = true;
583 else {
584 if (!def->tag.isEmpty())
585 def->tag += ' ';
586 def->tag += def->type.name;
587 }
588 def->type = tempType;
589 tempType = parseType();
590 }
591 if (!test(LPAREN))
592 return false;
593 def->name = tempType.name;
594 def->lineNumber = symbol().lineNum;
595 scopedFunctionName = tempType.isScoped;
596 }
597
598 if (!test(RPAREN)) {
600 if (!test(RPAREN))
601 return false;
602 }
603
604 def->isConst = test(CONST);
605
606 while (test(IDENTIFIER))
607 ;
608
609 if (test(THROW)) {
610 next(LPAREN);
611 until(RPAREN);
612 }
613
614 if (def->type.name == "auto" && test(ARROW))
615 def->type = parseType(); // Parse trailing return-type
616
617 if (scopedFunctionName
618 && (def->isSignal || def->isSlot || def->isInvokable)) {
619 const QByteArray msg = "parsemaybe: Function declaration " + def->name
620 + " contains extra qualification. Ignoring as signal or slot.";
621 warning(msg.constData());
622 return false;
623 }
624
625 if (def->isSlot || def->isSignal || def->isInvokable) {
626 QList<QByteArray> typeNameParts = normalizeType(def->type.name).split(' ');
627 if (typeNameParts.contains("auto")) {
628 // We expected a trailing return type but we haven't seen one
629 error("Function declared with auto as return type but missing trailing return type. "
630 "Return type deduction is not supported.");
631 }
632 }
633 // we don't support references as return types, it's too dangerous
634 if (def->type.referenceType == Type::Reference) {
635 QByteArray rawName = def->type.rawName;
636 def->type = Type("void");
637 def->type.rawName = rawName;
638 }
639
640 def->normalizedType = normalizeType(def->type.name);
641 return true;
642}
643
644inline void handleDefaultArguments(QList<FunctionDef> *functionList, FunctionDef &function)
645{
646 // support a function with a default argument by pretending there is an
647 // overload without the argument (the original function is the overload with
648 // all arguments present)
649 while (function.arguments.size() > 0 && function.arguments.constLast().isDefault) {
650 function.wasCloned = true;
651 function.arguments.removeLast();
652 *functionList += function;
653 }
654}
655
656void Moc::prependNamespaces(BaseDef &def, const QList<NamespaceDef> &namespaceList) const
657{
658 auto it = namespaceList.crbegin();
659 const auto rend = namespaceList.crend();
660 for (; it != rend; ++it) {
661 if (inNamespace(&*it))
662 def.qualified.prepend(it->classname + "::");
663 }
664}
665
666void Moc::checkListSizes(const ClassDef &def)
667{
668 if (Q_UNLIKELY(def.nonClassSignalList.size() > std::numeric_limits<int>::max()))
669 error("number of signals defined in parent class(es) exceeds "
670 "std::numeric_limits<int>::max().");
671
672 if (Q_UNLIKELY(def.propertyList.size() > std::numeric_limits<int>::max()))
673 error("number of bindable properties exceeds std::numeric_limits<int>::max().");
674
675 if (Q_UNLIKELY(def.classInfoList.size() > std::numeric_limits<int>::max()))
676 error("number of times Q_CLASSINFO macro is used exceeds "
677 "std::numeric_limits<int>::max().");
678
679 if (Q_UNLIKELY(def.enumList.size() > std::numeric_limits<int>::max()))
680 error("number of enumerations exceeds std::numeric_limits<int>::max().");
681
682 if (Q_UNLIKELY(def.superclassList.size() > std::numeric_limits<int>::max()))
683 error("number of super classes exceeds std::numeric_limits<int>::max().");
684
685 if (Q_UNLIKELY(def.constructorList.size() > std::numeric_limits<int>::max()))
686 error("number of constructor parameters exceeds std::numeric_limits<int>::max().");
687
688 if (Q_UNLIKELY(def.signalList.size() > std::numeric_limits<int>::max()))
689 error("number of signals exceeds std::numeric_limits<int>::max().");
690
691 if (Q_UNLIKELY(def.slotList.size() > std::numeric_limits<int>::max()))
692 error("number of declared slots exceeds std::numeric_limits<int>::max().");
693
694 if (Q_UNLIKELY(def.methodList.size() > std::numeric_limits<int>::max()))
695 error("number of methods exceeds std::numeric_limits<int>::max().");
696
697 if (Q_UNLIKELY(def.publicList.size() > std::numeric_limits<int>::max()))
698 error("number of public functions declared in this class exceeds "
699 "std::numeric_limits<int>::max().");
700}
701
702void Moc::parseModuleDeclaration(qsizetype rewind, bool exported)
703{
704 // If we already found a module declaration, this can't be one.
706 return;
707
708 if (test(SEMIC)) {
710 return;
711 }
712
713 if (!test(IDENTIFIER)) {
714 index = rewind;
715 return;
716 }
717
718 // Collect full module name, including dots.
719 QByteArray name = lexem();
720 while (test(DOT)) {
721 if (!test(IDENTIFIER)) {
722 index = rewind;
723 return;
724 }
725 name += '.';
726 name += lexem();
727 }
728
729 QByteArray partition;
730 if (test(COLON)) {
731 if (!test(IDENTIFIER)) {
732 index = rewind;
733 return;
734 }
735 partition = lexem();
736 }
737
738 if (!test(SEMIC)) {
739 index = rewind;
740 return;
741 }
742
743 moduleName = name;
744 modulePartitionName = partition;
745 if (exported) {
748 } else {
751 }
752}
753
754void Moc::parsePrivateModuleFragment(qsizetype rewind)
755{
756 // A private module fragment can only occur once, and only in the primary module interface.
758 index = rewind;
759 return;
760 }
761
762 if (!test(PRIVATE)) {
763 index = rewind;
764 return;
765 }
766
767 if (!test(SEMIC)) {
768 index = rewind;
769 return;
770 }
771
773}
774
775void Moc::parse()
776{
777 QList<NamespaceDef> namespaceList;
778 bool templateClass = false;
779 while (hasNext()) {
780 Token t = next();
781 switch (t) {
782 case NAMESPACE: {
783 qsizetype rewind = index;
784 if (test(IDENTIFIER)) {
785 QByteArray nsName = lexem();
786 QByteArrayList nested;
787 while (test(SCOPE)) {
788 /* treat (C++20's) namespace A::inline B {} as A::B
789 this is mostly to not break compilation when encountering such
790 a construct in a header; the interaction of Qt's meta-macros with
791 inline namespaces is still rather poor.
792 */
793 test(INLINE);
794 next(IDENTIFIER);
795 nested.append(nsName);
796 nsName = lexem();
797 }
798 if (test(EQ)) {
799 // namespace Foo = Bar::Baz;
800 until(SEMIC);
801 } else if (test(LPAREN)) {
802 // Ignore invalid code such as: 'namespace __identifier("x")' (QTBUG-56634)
803 until(RPAREN);
804 } else if (!test(SEMIC)) {
805 NamespaceDef def;
806 def.classname = nsName;
807 def.lineNumber = symbol().lineNum;
808 def.doGenerate = currentFilenames.size() <= 1;
809
810 next(LBRACE);
811 def.begin = index - 1;
812 until(RBRACE);
813 def.end = index;
814 index = def.begin + 1;
815
816 prependNamespaces(def, namespaceList);
817
818 for (const QByteArray &ns : nested) {
819 NamespaceDef parentNs;
820 parentNs.classname = ns;
821 parentNs.qualified = def.qualified;
822 def.qualified += ns + "::";
823 parentNs.begin = def.begin;
824 parentNs.end = def.end;
825 namespaceList += parentNs;
826 }
827
828 while (inNamespace(&def) && hasNext()) {
829 switch (next()) {
830 case NAMESPACE:
831 if (test(IDENTIFIER)) {
832 while (test(SCOPE)) {
833 test(INLINE); // ignore inline namespaces
834 next(IDENTIFIER);
835 }
836 if (test(EQ)) {
837 // namespace Foo = Bar::Baz;
838 until(SEMIC);
839 } else if (!test(SEMIC)) {
840 until(RBRACE);
841 }
842 }
843 break;
844 case Q_NAMESPACE_EXPORT_TOKEN:
845 next(LPAREN);
846 while (test(IDENTIFIER))
847 {}
848 next(RPAREN);
849 Q_FALLTHROUGH();
850 case Q_NAMESPACE_TOKEN:
851 def.hasQNamespace = true;
852 if (moduleUnitKind == ModuleUnitKind::ImplementationUnit)
853 error("Q_NAMESPACE is not supported in a module implementation unit");
854 if (inPrivateModuleFragment)
855 error("Q_NAMESPACE is not supported in a private module fragment");
856 break;
857 case Q_ENUMS_TOKEN:
858 case Q_ENUM_NS_TOKEN:
859 parseEnumOrFlag(&def, {});
860 break;
861 case Q_ENUM_TOKEN:
862 error("Q_ENUM can't be used in a Q_NAMESPACE, use Q_ENUM_NS instead");
863 break;
864 case Q_FLAGS_TOKEN:
865 case Q_FLAG_NS_TOKEN:
866 parseEnumOrFlag(&def, EnumIsFlag);
867 break;
868 case Q_FLAG_TOKEN:
869 error("Q_FLAG can't be used in a Q_NAMESPACE, use Q_FLAG_NS instead");
870 break;
871 case Q_DECLARE_FLAGS_TOKEN:
872 parseFlag(&def);
873 break;
874 case Q_CLASSINFO_TOKEN:
875 parseClassInfo(&def);
876 break;
877 case Q_MOC_INCLUDE_TOKEN:
878 // skip it, the namespace is parsed twice
879 next(LPAREN);
880 lexemUntil(RPAREN);
881 break;
882 case ENUM: {
883 EnumDef enumDef;
884 if (parseEnum(&enumDef, nullptr))
885 def.enumList += enumDef;
886 } break;
887 case CLASS:
888 case STRUCT: {
889 ClassDef classdef;
890 if (!parseClassHead(&classdef))
891 continue;
892 while (inClass(&classdef) && hasNext())
893 next(); // consume all Q_XXXX macros from this class
894 } break;
895 default: break;
896 }
897 }
898 namespaceList += def;
899 index = rewind;
900 if (!def.hasQNamespace && (!def.classInfoList.isEmpty() || !def.enumDeclarations.isEmpty()))
901 error("Namespace declaration lacks Q_NAMESPACE macro.");
902 }
903 }
904 break;
905 }
906 case SEMIC:
907 case RBRACE:
908 templateClass = false;
909 break;
910 case TEMPLATE:
911 templateClass = true;
912 break;
913 case MOC_INCLUDE_BEGIN:
914 // Record (top-level) includes in the global module fragment for later
915 // insertion into the generated file.
916 // As it is fiendishly difficult to find out if and how the contents of
917 // a header file are being used, we have to assume that the compiler will need
918 // all of them when building our generated file.
919 if (hasGlobalModuleFragment && moduleUnitKind == ModuleUnitKind::NotAModule
920 && currentFilenames.size() == 1) {
921 moduleFragmentIncludes += symbol().lexem();
922 }
923
924 currentFilenames.push(symbol().unquotedLexem());
925 break;
926 case MOC_INCLUDE_END:
927 currentFilenames.pop();
928 break;
929 case Q_DECLARE_INTERFACE_TOKEN:
931 break;
932 case Q_DECLARE_METATYPE_TOKEN:
934 break;
935 case Q_MOC_INCLUDE_TOKEN:
937 break;
938 case USING:
939 if (test(NAMESPACE)) {
940 while (test(SCOPE) || test(IDENTIFIER))
941 ;
942 // Ignore invalid code such as: 'using namespace __identifier("x")' (QTBUG-63772)
943 if (test(LPAREN))
944 until(RPAREN);
945 next(SEMIC);
946 }
947 break;
948 case CLASS:
949 case STRUCT: {
950 if (currentFilenames.size() <= 1)
951 break;
952
953 ClassDef def;
954 if (!parseClassHead(&def))
955 continue;
956
957 while (inClass(&def) && hasNext()) {
958 switch (next()) {
959 case Q_OBJECT_TOKEN:
960 def.hasQObject = true;
961 break;
962 case Q_GADGET_EXPORT_TOKEN:
963 next(LPAREN);
964 while (test(IDENTIFIER))
965 {}
966 next(RPAREN);
967 Q_FALLTHROUGH();
968 case Q_GADGET_TOKEN:
969 def.hasQGadget = true;
970 break;
971 default: break;
972 }
973 }
974
975 if (!def.hasQObject && !def.hasQGadget)
976 continue;
977
978 prependNamespaces(def, namespaceList);
979
980 QHash<QByteArray, QByteArray> &classHash = def.hasQObject ? knownQObjectClasses : knownGadgets;
981 classHash.insert(def.classname, def.qualified);
982 classHash.insert(def.qualified, def.qualified);
983
984 continue; }
985 case EXPORT: {
986 const qsizetype afterExport = index;
987 if (currentFilenames.size() == 1 && test(IDENTIFIER) && lexem() == "module")
988 parseModuleDeclaration(index, /*exported=*/true);
989 else
990 index = afterExport;
991 break;
992 }
993 case IDENTIFIER:
994 if (currentFilenames.size() == 1 && lexem() == "module") {
995 const qsizetype afterModule = index;
996 if (test(COLON)) {
997 // A private module fragment can follow any ordinary declaration
998 // in the primary interface.
999 parsePrivateModuleFragment(afterModule);
1000 } else {
1001 // Since "module" is a legal identifier in most contexts, we
1002 // must be careful about false positives.
1003 const bool precededByBareModuleFragment = afterModule == 3
1004 && symbols.at(afterModule - 2).token == SEMIC
1005 && symbols.at(afterModule - 3).token == IDENTIFIER
1006 && symbols.at(afterModule - 3).lexem() == "module";
1007 const bool isModuleCandidate = afterModule < 2
1008 || precededByBareModuleFragment
1009 || (hasGlobalModuleFragment
1010 && symbols.at(afterModule - 2).token == MOC_INCLUDE_END);
1011 if (isModuleCandidate)
1012 parseModuleDeclaration(afterModule, /*exported=*/false);
1013 }
1014 }
1015 break;
1016 default: break;
1017 }
1018 if ((t != CLASS && t != STRUCT)|| currentFilenames.size() > 1)
1019 continue;
1020 ClassDef def;
1021 if (parseClassHead(&def)) {
1022 Symbol qmlRegistrationMacroSymbol = {};
1023 prependNamespaces(def, namespaceList);
1024
1026 while (inClass(&def) && hasNext()) {
1027 switch ((t = next())) {
1028 case PRIVATE:
1029 access = FunctionDef::Private;
1030 if (test(Q_SIGNALS_TOKEN))
1031 error("Signals cannot have access specifier");
1032 break;
1033 case PROTECTED:
1034 access = FunctionDef::Protected;
1035 if (test(Q_SIGNALS_TOKEN))
1036 error("Signals cannot have access specifier");
1037 break;
1038 case PUBLIC:
1039 access = FunctionDef::Public;
1040 if (test(Q_SIGNALS_TOKEN))
1041 error("Signals cannot have access specifier");
1042 break;
1043 case STRUCT:
1044 case CLASS: {
1045 ClassDef nestedDef;
1046 if (parseClassHead(&nestedDef)) {
1047 while (inClass(&nestedDef) && inClass(&def)) {
1048 t = next();
1049 if (t >= Q_META_TOKEN_BEGIN && t < Q_META_TOKEN_END)
1050 error("Meta object features not supported for nested classes");
1051 }
1052 }
1053 } break;
1054 case Q_SIGNALS_TOKEN:
1055 parseSignals(&def);
1056 break;
1057 case Q_SLOTS_TOKEN:
1058 switch (lookup(-1)) {
1059 case PUBLIC:
1060 case PROTECTED:
1061 case PRIVATE:
1062 parseSlots(&def, access);
1063 break;
1064 default:
1065 error("Missing access specifier for slots");
1066 }
1067 break;
1068 case Q_OBJECT_TOKEN:
1069 def.hasQObject = true;
1070 if (templateClass)
1071 error("Template classes not supported by Q_OBJECT");
1072 if (def.classname != "Qt" && def.classname != "QObject" && def.superclassList.isEmpty())
1073 error("Class contains Q_OBJECT macro but does not inherit from QObject");
1074 if (moduleUnitKind == ModuleUnitKind::ImplementationUnit)
1075 error("Q_OBJECT is not supported in a module implementation unit");
1076 if (inPrivateModuleFragment)
1077 error("Q_OBJECT is not supported in a private module fragment");
1078 break;
1079 case Q_GADGET_EXPORT_TOKEN:
1080 next(LPAREN);
1081 while (test(IDENTIFIER))
1082 {}
1083 next(RPAREN);
1084 Q_FALLTHROUGH();
1085 case Q_GADGET_TOKEN:
1086 def.hasQGadget = true;
1087 if (templateClass)
1088 error("Template classes not supported by Q_GADGET");
1089 if (moduleUnitKind == ModuleUnitKind::ImplementationUnit)
1090 error("Q_GADGET is not supported in a module implementation unit");
1091 if (inPrivateModuleFragment)
1092 error("Q_GADGET is not supported in a private module fragment");
1093 break;
1094 case Q_PROPERTY_TOKEN:
1096 break;
1097 case QT_ANONYMOUS_PROPERTY_TOKEN:
1099 break;
1100 case Q_PLUGIN_METADATA_TOKEN:
1102 break;
1103 case Q_ENUMS_TOKEN:
1104 case Q_ENUM_TOKEN:
1105 parseEnumOrFlag(&def, {});
1106 break;
1107 case Q_ENUM_NS_TOKEN:
1108 error("Q_ENUM_NS can't be used in a Q_OBJECT/Q_GADGET, use Q_ENUM instead");
1109 break;
1110 case Q_FLAGS_TOKEN:
1111 case Q_FLAG_TOKEN:
1112 parseEnumOrFlag(&def, EnumIsFlag);
1113 break;
1114 case Q_FLAG_NS_TOKEN:
1115 error("Q_FLAG_NS can't be used in a Q_OBJECT/Q_GADGET, use Q_FLAG instead");
1116 break;
1117 case Q_DECLARE_FLAGS_TOKEN:
1118 parseFlag(&def);
1119 break;
1120 case Q_CLASSINFO_TOKEN:
1121 parseClassInfo(&def);
1122 break;
1123 case Q_MOC_INCLUDE_TOKEN:
1125 break;
1126 case Q_INTERFACES_TOKEN:
1128 break;
1129 case Q_PRIVATE_SLOT_TOKEN:
1130 parseSlotInPrivate(&def, access);
1131 break;
1132 case Q_PRIVATE_PROPERTY_TOKEN:
1134 break;
1135 case QT_ANONYMOUS_PRIVATE_PROPERTY_TOKEN:
1137 break;
1138 case ENUM: {
1139 EnumDef enumDef;
1140 if (parseEnum(&enumDef, &def))
1141 def.enumList += enumDef;
1142 } break;
1143 case SEMIC:
1144 case COLON:
1145 break;
1146 case IDENTIFIER:
1147 {
1148 const QByteArrayView lex = lexemView();
1149 if (lex.startsWith("QML_")) {
1150 if ( lex == "QML_ELEMENT" || lex == "QML_NAMED_ELEMENT"
1151 || lex == "QML_ANONYMOUS" || lex == "QML_VALUE_TYPE") {
1152 qmlRegistrationMacroSymbol = symbol();
1153 }
1154 }
1155 }
1156 Q_FALLTHROUGH();
1157 default:
1158 FunctionDef funcDef;
1159 funcDef.access = access;
1160 qsizetype rewind = index--;
1161 if (parseMaybeFunction(&def, &funcDef)) {
1162 if (funcDef.isConstructor) {
1163 if ((access == FunctionDef::Public) && funcDef.isInvokable) {
1164 def.constructorList += funcDef;
1165 handleDefaultArguments(&def.constructorList, funcDef);
1166 }
1167 } else if (funcDef.isDestructor) {
1168 // don't care about destructors
1169 } else {
1170 if (access == FunctionDef::Public)
1171 def.publicList += funcDef;
1172 if (funcDef.isSlot) {
1173 def.slotList += funcDef;
1174 handleDefaultArguments(&def.slotList, funcDef);
1175 if (funcDef.revision > 0)
1176 ++def.revisionedMethods;
1177 } else if (funcDef.isSignal) {
1178 def.signalList += funcDef;
1179 handleDefaultArguments(&def.signalList, funcDef);
1180 if (funcDef.revision > 0)
1181 ++def.revisionedMethods;
1182 } else if (funcDef.isInvokable) {
1183 def.methodList += funcDef;
1184 handleDefaultArguments(&def.methodList, funcDef);
1185 if (funcDef.revision > 0)
1186 ++def.revisionedMethods;
1187 }
1188 }
1189 } else {
1190 index = rewind;
1191 }
1192 }
1193 }
1194
1195 next(RBRACE);
1196
1197 /* if the header is available, moc will see a Q_CLASSINFO entry; the
1198 token is only visible if the header is missing
1199 To avoid false positives, we only warn when encountering the token in a QObject or gadget
1200 */
1201 if ((def.hasQObject || def.hasQGadget) && qmlRegistrationMacroSymbol.token != NOTOKEN) {
1202 QByteArray msg("Potential QML registration macro was found, but no header containing it was included.\n"
1203 "This might cause runtime errors in QML applications\n"
1204 "Include <QtQmlIntegration/qqmlintegration.h> or <QtQml/qqmlregistration.h> to fix this.");
1205 if (qmlMacroWarningIsFatal)
1206 error(qmlRegistrationMacroSymbol, msg.constData());
1207 else
1208 warning(qmlRegistrationMacroSymbol, msg.constData());
1209 }
1210
1211 if (!def.hasQObject && !def.hasQGadget && def.signalList.isEmpty() && def.slotList.isEmpty()
1212 && def.propertyList.isEmpty() && def.enumDeclarations.isEmpty())
1213 continue; // no meta object code required
1214
1215
1216 if (!def.hasQObject && !def.hasQGadget)
1217 error("Class declaration lacks Q_OBJECT macro.");
1218
1219 // Add meta tags to the plugin meta data:
1220 if (!def.pluginData.iid.isEmpty())
1221 def.pluginData.metaArgs = metaArgs;
1222
1223 if (def.hasQObject && !def.superclassList.isEmpty())
1225
1227
1229
1230 classList += def;
1231 QHash<QByteArray, QByteArray> &classHash = def.hasQObject ? knownQObjectClasses : knownGadgets;
1232 classHash.insert(def.classname, def.qualified);
1233 classHash.insert(def.qualified, def.qualified);
1234 }
1235 }
1236 for (const auto &n : std::as_const(namespaceList)) {
1237 if (!n.hasQNamespace)
1238 continue;
1239 ClassDef def;
1240 static_cast<BaseDef &>(def) = static_cast<BaseDef>(n);
1241 def.qualified += def.classname;
1242 def.hasQNamespace = true;
1243 auto it = std::find_if(classList.begin(), classList.end(), [&def](const ClassDef &val) {
1244 return def.classname == val.classname && def.qualified == val.qualified;
1245 });
1246
1247 if (it != classList.end()) {
1248 it->classInfoList += def.classInfoList;
1249 Q_ASSERT(it->classInfoList.size() <= std::numeric_limits<int>::max());
1250 it->enumDeclarations.insert(def.enumDeclarations);
1251 it->enumList += def.enumList;
1252 Q_ASSERT(it->enumList.size() <= std::numeric_limits<int>::max());
1253 it->flagAliases.insert(def.flagAliases);
1254 } else {
1255 knownGadgets.insert(def.classname, def.qualified);
1256 knownGadgets.insert(def.qualified, def.qualified);
1257 if (n.doGenerate)
1258 classList += def;
1259 }
1260 }
1261}
1262
1264{
1265 QByteArrayView fn = QByteArrayView(filename);
1266
1267 auto isSlash = [](char ch) { return ch == '/' || ch == '\\'; };
1268 auto rit = std::find_if(fn.crbegin(), fn.crend(), isSlash);
1269 if (rit != fn.crend())
1270 fn = fn.last(rit - fn.crbegin());
1271
1272 return fn;
1273}
1274
1275static bool any_type_contains(const QList<PropertyDef> &properties, const QByteArray &pattern)
1276{
1277 for (const auto &p : properties) {
1278 if (p.type.contains(pattern))
1279 return true;
1280 }
1281 return false;
1282}
1283
1284static bool any_arg_contains(const QList<FunctionDef> &functions, const QByteArray &pattern)
1285{
1286 for (const auto &f : functions) {
1287 for (const auto &arg : f.arguments) {
1288 if (arg.normalizedType.contains(pattern))
1289 return true;
1290 }
1291 }
1292 return false;
1293}
1294
1296{
1297 QByteArrayList result;
1298 result
1299#define STREAM_SMART_POINTER(SMART_POINTER) << #SMART_POINTER
1300 QT_FOR_EACH_AUTOMATIC_TEMPLATE_SMART_POINTER(STREAM_SMART_POINTER)
1301#undef STREAM_SMART_POINTER
1302#define STREAM_1ARG_TEMPLATE(TEMPLATENAME) << #TEMPLATENAME
1303 QT_FOR_EACH_AUTOMATIC_TEMPLATE_1ARG(STREAM_1ARG_TEMPLATE)
1304#undef STREAM_1ARG_TEMPLATE
1305 ;
1306 return result;
1307}
1308
1310{
1311 static const QByteArrayList candidates = make_candidates();
1312
1313 QByteArrayList required;
1314 required.reserve(candidates.size());
1315
1316 bool needsQProperty = false;
1317
1318 for (const auto &candidate : candidates) {
1319 const QByteArray pattern = candidate + '<';
1320
1321 for (const auto &c : classes) {
1322 for (const auto &p : c.propertyList)
1323 needsQProperty |= !p.bind.isEmpty();
1324 if (any_type_contains(c.propertyList, pattern) ||
1325 any_arg_contains(c.slotList, pattern) ||
1326 any_arg_contains(c.signalList, pattern) ||
1327 any_arg_contains(c.methodList, pattern)) {
1328 required.push_back(candidate);
1329 break;
1330 }
1331 }
1332 }
1333
1334 if (needsQProperty)
1335 required.push_back("QProperty");
1336
1337 return required;
1338}
1339
1340void Moc::generate(FILE *out, FILE *jsonOutput)
1341{
1342 QByteArrayView fn = strippedFileName();
1343
1344 fprintf(out, "/****************************************************************************\n"
1345 "** Meta object code from reading C++ file '%s'\n**\n" , fn.constData());
1346 fprintf(out, "** Created by: The Qt Meta Object Compiler version %d (Qt %s)\n**\n" , mocOutputRevision, QT_VERSION_STR);
1347 fprintf(out, "** WARNING! All changes made in this file will be lost!\n"
1348 "*****************************************************************************/\n\n");
1349
1350 // If the source file is part of a module, the generated code becomes an implementation unit
1351 // of the same module, so that it gains access to the module's interface and can import
1352 // internal partitions, if needed.
1353 // Includes from the source file's own global module fragment need to be copied over.
1355 fprintf(out, "module;\n\n");
1356 for (const QByteArray &inc : std::as_const(moduleFragmentIncludes))
1357 fprintf(out, "#include \"%s\"\n", inc.constData());
1358 } else if (!noInclude) {
1359 // include header(s) of user class definitions at _first_ to allow
1360 // for preprocessor definitions possibly affecting standard headers.
1361 // see https://codereview.qt-project.org/c/qt/qtbase/+/445937
1362 if (includePath.size() && !includePath.endsWith('/'))
1363 includePath += '/';
1364 for (QByteArray inc : std::as_const(includeFiles)) {
1365 if (!inc.isEmpty() && inc.at(0) != '<' && inc.at(0) != '"') {
1366 if (includePath.size() && includePath != "./")
1367 inc.prepend(includePath);
1368 inc = '\"' + inc + '\"';
1369 }
1370 fprintf(out, "#include %s\n", inc.constData());
1371 }
1372 }
1373 if (classList.size() && classList.constFirst().classname == "Qt")
1374 fprintf(out, "#include <QtCore/qobject.h>\n");
1375
1376 fprintf(out, "#include <QtCore/qmetatype.h>\n"); // For QMetaType::Type
1378 fprintf(out, "#include <QtCore/qplugin.h>\n");
1379
1380 const auto qtContainers = requiredQtContainers(classList);
1381 for (const QByteArray &qtContainer : qtContainers)
1382 fprintf(out, "#include <QtCore/%s>\n", qtContainer.constData());
1383
1384 fprintf(out, "\n#include <QtCore/qtmochelpers.h>\n");
1385
1386 fprintf(out, "\n#include <memory>\n\n"); // For std::addressof
1387 fprintf(out, "\n#include <QtCore/qxptype_traits.h>\n"); // is_detected
1388
1390 fprintf(out, "\nmodule %s;\n", moduleName.constData());
1391
1392 // Internal partitions need to be imported to get access to them.
1393 // Interface partitions should normally be available implicitly
1394 // via the re-export from the primary interface, but we import them
1395 // anyway to be on the safe side.
1398 fprintf(out, "import :%s;\n", modulePartitionName.constData());
1399 }
1400
1401 fprintf(out, "\n");
1402 }
1403
1404 fprintf(out, "#if !defined(Q_MOC_OUTPUT_REVISION)\n"
1405 "#error \"The header file '%s' doesn't include <QObject>.\"\n", fn.constData());
1406 fprintf(out, "#elif Q_MOC_OUTPUT_REVISION != %d\n", mocOutputRevision);
1407 fprintf(out, "#error \"This file was generated using the moc from %s."
1408 " It\"\n#error \"cannot be used with the include files from"
1409 " this version of Qt.\"\n#error \"(The moc has changed too"
1410 " much.)\"\n", QT_VERSION_STR);
1411 fprintf(out, "#endif\n\n");
1412
1413#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0)
1414 fprintf(out, "#ifndef Q_CONSTINIT\n"
1415 "#define Q_CONSTINIT\n"
1416 "#endif\n\n");
1417#endif
1418
1419 // filter out undeclared enumerators and sets
1420 for (ClassDef &cdef : classList) {
1421 QList<EnumDef> enumList;
1422 for (EnumDef def : std::as_const(cdef.enumList)) {
1423 if (cdef.enumDeclarations.contains(def.name)) {
1424 enumList += def;
1425 }
1426 def.enumName = def.name;
1427 QByteArray alias = cdef.flagAliases.value(def.name);
1428 if (cdef.enumDeclarations.contains(alias)) {
1429 def.name = alias;
1430 def.flags |= cdef.enumDeclarations[alias];
1431 enumList += def;
1432 }
1433 }
1434 cdef.enumList = enumList;
1435 }
1436
1437 fprintf(out, "QT_WARNING_PUSH\n");
1438 fprintf(out, "QT_WARNING_DISABLE_DEPRECATED\n");
1439 fprintf(out, "QT_WARNING_DISABLE_GCC(\"-Wuseless-cast\")\n");
1440
1441 fputs("", out);
1442 for (const ClassDef &def : std::as_const(classList)) {
1443 Generator generator(this, &def, metaTypes, knownQObjectClasses, knownGadgets, out,
1444 requireCompleteTypes);
1445 generator.generateCode();
1446
1447 // generator.generateCode() should have already registered all strings
1448 if (Q_UNLIKELY(generator.registeredStringsCount() >= std::numeric_limits<int>::max())) {
1449 error("internal limit exceeded: number of parsed strings is too big.");
1450 exit(EXIT_FAILURE);
1451 }
1452 }
1453 fputs("", out);
1454
1455 fprintf(out, "QT_WARNING_POP\n");
1456
1457 if (jsonOutput) {
1458 QJsonObject mocData;
1459 mocData["outputRevision"_L1] = mocOutputRevision;
1460 mocData["inputFile"_L1] = QLatin1StringView(fn.constData());
1461
1463 QByteArray moduleId = moduleName;
1464 if (!modulePartitionName.isEmpty())
1465 moduleId += ':' + modulePartitionName;
1466 mocData["module"_L1] = QLatin1StringView(moduleId.constData(), moduleId.size());
1467 }
1468
1469 QJsonArray classesJsonFormatted;
1470
1471 for (const ClassDef &cdef: std::as_const(classList))
1472 classesJsonFormatted.append(cdef.toJson());
1473
1474 if (!classesJsonFormatted.isEmpty())
1475 mocData["classes"_L1] = classesJsonFormatted;
1476
1477 QJsonDocument jsonDoc(mocData);
1478 fputs(jsonDoc.toJson().constData(), jsonOutput);
1479 }
1480}
1481
1483{
1484 QTypeRevision defaultRevision;
1485 if (test(Q_REVISION_TOKEN))
1486 defaultRevision = parseRevision();
1487
1488 next(COLON);
1489 while (inClass(def) && hasNext()) {
1490 switch (next()) {
1491 case PUBLIC:
1492 case PROTECTED:
1493 case PRIVATE:
1494 case Q_SIGNALS_TOKEN:
1495 case Q_SLOTS_TOKEN:
1496 prev();
1497 return;
1498 case SEMIC:
1499 continue;
1500 case FRIEND:
1501 until(SEMIC);
1502 continue;
1503 case USING:
1504 error("'using' directive not supported in 'slots' section");
1505 default:
1506 prev();
1507 }
1508
1509 FunctionDef funcDef;
1510 funcDef.access = access;
1511 if (!parseFunction(&funcDef))
1512 continue;
1513 if (funcDef.revision > 0) {
1515 } else if (defaultRevision.isValid()) {
1516 funcDef.revision = defaultRevision.toEncodedVersion<int>();
1518 }
1519 def->slotList += funcDef;
1520 handleDefaultArguments(&def->slotList, funcDef);
1521 }
1522}
1523
1525{
1526 QTypeRevision defaultRevision;
1527 if (test(Q_REVISION_TOKEN))
1528 defaultRevision = parseRevision();
1529
1530 next(COLON);
1531 while (inClass(def) && hasNext()) {
1532 switch (next()) {
1533 case PUBLIC:
1534 case PROTECTED:
1535 case PRIVATE:
1536 case Q_SIGNALS_TOKEN:
1537 case Q_SLOTS_TOKEN:
1538 prev();
1539 return;
1540 case SEMIC:
1541 continue;
1542 case FRIEND:
1543 until(SEMIC);
1544 continue;
1545 case USING:
1546 error("'using' directive not supported in 'signals' section");
1547 default:
1548 prev();
1549 }
1550 FunctionDef funcDef;
1552 parseFunction(&funcDef);
1553 if (funcDef.isVirtual)
1554 warning("Signals cannot be declared virtual");
1555 if (funcDef.inlineCode)
1556 error("Not a signal declaration");
1557 if (funcDef.revision > 0) {
1559 } else if (defaultRevision.isValid()) {
1560 funcDef.revision = defaultRevision.toEncodedVersion<int>();
1562 }
1563 def->signalList += funcDef;
1564 handleDefaultArguments(&def->signalList, funcDef);
1565 }
1566}
1567
1568void Moc::createPropertyDef(PropertyDef &propDef, int propertyIndex, Moc::PropertyMode mode)
1569{
1570 propDef.location = index;
1571 propDef.relativeIndex = propertyIndex;
1572 propDef.lineNumber = symbol().lineNum;
1573
1574 Type t = parseType();
1575 QByteArray type = t.name;
1576 if (type.isEmpty())
1577 error();
1578 propDef.typeTag = t.typeTag;
1579 propDef.designable = propDef.scriptable = propDef.stored = "true";
1580 propDef.user = "false";
1581 /*
1582 The Q_PROPERTY construct cannot contain any commas, since
1583 commas separate macro arguments. We therefore expect users
1584 to type "QMap" instead of "QMap<QString, QVariant>". For
1585 coherence, we also expect the same for
1586 QValueList<QVariant>, the other template class supported by
1587 QVariant.
1588 */
1589 type = normalizeType(type);
1590 if (type == "QMap")
1591 type = "QMap<QString,QVariant>";
1592 else if (type == "LongLong")
1593 type = "qlonglong";
1594 else if (type == "ULongLong")
1595 type = "qulonglong";
1596
1597 propDef.type = type;
1598
1599 if (mode == Moc::Named) {
1600 next();
1601 propDef.name = lexem();
1602 }
1603
1605}
1606
1608{
1609 auto checkIsFunction = [&](const QByteArray &def, const char *name) {
1610 if (def.endsWith(')')) {
1611 QByteArray msg = "Providing a function for ";
1612 msg += name;
1613 msg += " in a property declaration is not be supported in Qt 6.";
1614 error(msg.constData());
1615 }
1616 };
1617
1618 while (test(IDENTIFIER)) {
1619 const Symbol &lsym = symbol();
1620 const QByteArrayView l = lsym.lexemView();
1621 if (l[0] == 'C' && l == "CONSTANT") {
1622 propDef.constant = true;
1623 continue;
1624 } else if (l[0] == 'F' && l == "FINAL") {
1625 propDef.final = true;
1626 continue;
1627 } else if (l[0] == 'N' && l == "NAME") {
1628 next(IDENTIFIER);
1629 propDef.name = lexem();
1630 continue;
1631 } else if (l[0] == 'O' && l == "OVERRIDE") {
1632 propDef.override = true;
1633 continue;
1634 } else if (l[0] == 'R' && l == "REQUIRED") {
1635 propDef.required = true;
1636 continue;
1637 } else if (l[0] == 'R' && l == "REVISION" && test(LPAREN)) {
1638 prev();
1639 propDef.revision = parseRevision().toEncodedVersion<int>();
1640 continue;
1641 } else if (l[0] == 'V' && l == "VIRTUAL") {
1642 propDef.virtual_ = true;
1643 continue;
1644 }
1645
1646 QByteArray v, v2;
1647 if (test(LPAREN)) {
1648 v = lexemUntil(RPAREN);
1649 v = v.mid(1, v.size() - 2); // removes the '(' and ')'
1650 } else if (test(INTEGER_LITERAL)) {
1651 v = lexem();
1652 if (l != "REVISION")
1653 error(lsym);
1654 } else if (test(DEFAULT)) {
1655 v = lexem();
1656 if (l != "READ" && l != "WRITE")
1657 error(lsym);
1658 } else {
1659 next(IDENTIFIER);
1660 v = lexem();
1661 if (test(LPAREN))
1662 v2 = lexemUntil(RPAREN);
1663 else if (v != "true" && v != "false")
1664 v2 = "()";
1665 }
1666 switch (l[0]) {
1667 case 'M':
1668 if (l == "MEMBER")
1669 propDef.member = v;
1670 else
1671 error(lsym);
1672 break;
1673 case 'R':
1674 if (l == "READ")
1675 propDef.read = v;
1676 else if (l == "RESET")
1677 propDef.reset = v;
1678 else if (l == "REVISION") {
1679 bool ok = false;
1680 const int minor = v.toInt(&ok);
1681 if (!ok || !QTypeRevision::isValidSegment(minor))
1682 error(lsym);
1683 propDef.revision = QTypeRevision::fromMinorVersion(minor).toEncodedVersion<int>();
1684 } else
1685 error(lsym);
1686 break;
1687 case 'S':
1688 if (l == "SCRIPTABLE") {
1689 propDef.scriptable = v + v2;
1690 checkIsFunction(propDef.scriptable, "SCRIPTABLE");
1691 } else if (l == "STORED") {
1692 propDef.stored = v + v2;
1693 checkIsFunction(propDef.stored, "STORED");
1694 } else
1695 error(lsym);
1696 break;
1697 case 'W': if (l != "WRITE") error(lsym);
1698 propDef.write = v;
1699 break;
1700 case 'B': if (l != "BINDABLE") error(lsym);
1701 propDef.bind = v;
1702 break;
1703 case 'D': if (l != "DESIGNABLE") error(lsym);
1704 propDef.designable = v + v2;
1705 checkIsFunction(propDef.designable, "DESIGNABLE");
1706 break;
1707 case 'N': if (l != "NOTIFY") error(lsym);
1708 propDef.notify = v;
1709 break;
1710 case 'U': if (l != "USER") error(lsym);
1711 propDef.user = v + v2;
1712 checkIsFunction(propDef.user, "USER");
1713 break;
1714 default:
1715 error(lsym);
1716 }
1717 }
1718 if (propDef.constant && !propDef.write.isNull()) {
1719 const QByteArray msg = "Property declaration " + propDef.name
1720 + " is both WRITEable and CONSTANT. CONSTANT will be ignored.";
1721 propDef.constant = false;
1722 warning(msg.constData());
1723 }
1724 if (propDef.constant && !propDef.notify.isNull()) {
1725 const QByteArray msg = "Property declaration " + propDef.name
1726 + " is both NOTIFYable and CONSTANT. CONSTANT will be ignored.";
1727 propDef.constant = false;
1728 warning(msg.constData());
1729 }
1730 if (propDef.constant && !propDef.bind.isNull()) {
1731 const QByteArray msg = "Property declaration " + propDef.name
1732 + " is both BINDable and CONSTANT. CONSTANT will be ignored.";
1733 propDef.constant = false;
1734 warning(msg.constData());
1735 }
1736 if (propDef.read == "default" && propDef.bind.isNull()) {
1737 const QByteArray msg = "Property declaration " + propDef.name
1738 + " is not BINDable but default-READable. READ will be ignored.";
1739 propDef.read = "";
1740 warning(msg.constData());
1741 }
1742 if (propDef.write == "default" && propDef.bind.isNull()) {
1743 const QByteArray msg = "Property declaration " + propDef.name
1744 + " is not BINDable but default-WRITEable. WRITE will be ignored.";
1745 propDef.write = "";
1746 warning(msg.constData());
1747 }
1748 if (propDef.override && propDef.virtual_) {
1749 const QByteArray msg = "Issue with property declaration " + propDef.name
1750 + ": VIRTUAL is redundant when overriding a property. The OVERRIDE "
1751 "must only be used when actually overriding an existing property; using it on a "
1752 "new property is an error.";
1753 error(msg.constData());
1754 }
1755 if (propDef.override && propDef.final) {
1756 const QByteArray msg = "Issue with property declaration " + propDef.name
1757 + ": OVERRIDE is redundant when property is marked FINAL";
1758 error(msg.constData());
1759 }
1760 if (propDef.virtual_ && propDef.final) {
1761 const QByteArray msg = "Issue with property declaration " + propDef.name
1762 + ": The VIRTUAL cannot be combined with FINAL, as these attributes are mutually "
1763 "exclusive";
1764 error(msg.constData());
1765 }
1766}
1767
1769{
1770 next(LPAREN);
1771 PropertyDef propDef;
1772 createPropertyDef(propDef, int(def->propertyList.size()), mode);
1773 next(RPAREN);
1774
1775 def->propertyList += propDef;
1776}
1777
1779{
1780 next(LPAREN);
1781 QByteArray metaData;
1782 while (test(IDENTIFIER)) {
1783 QByteArray l = lexem();
1784 if (l == "IID") {
1785 next(STRING_LITERAL);
1786 def->pluginData.iid = unquotedLexem();
1787 } else if (l == "URI") {
1788 next(STRING_LITERAL);
1789 def->pluginData.uri = unquotedLexem();
1790 } else if (l == "FILE") {
1791 next(STRING_LITERAL);
1792 QByteArrayView metaDataFile = unquotedLexemView();
1793 QFileInfo fi(QFileInfo(QString::fromLocal8Bit(currentFilenames.top())).dir(),
1794 QString::fromLocal8Bit(metaDataFile));
1795 for (const IncludePath &p : std::as_const(includes)) {
1796 if (fi.exists())
1797 break;
1798 if (p.isFrameworkPath)
1799 continue;
1800
1801 fi.setFile(QString::fromLocal8Bit(p.path), QString::fromLocal8Bit(metaDataFile));
1802 // try again, maybe there's a file later in the include paths with the same name
1803 if (fi.isDir()) {
1804 fi = QFileInfo();
1805 continue;
1806 }
1807 }
1808 if (!fi.exists()) {
1809 const QByteArray msg = "Plugin Metadata file " + lexemView()
1810 + " does not exist. Declaration will be ignored";
1811 error(msg.constData());
1812 return;
1813 }
1814 QFile file(fi.canonicalFilePath());
1815 if (!file.open(QFile::ReadOnly)) {
1816 QByteArray msg = "Plugin Metadata file " + lexemView() + " could not be opened: "
1817 + file.errorString().toUtf8();
1818 error(msg.constData());
1819 return;
1820 }
1821 parsedPluginMetadataFiles.append(fi.canonicalFilePath());
1822 metaData = file.readAll();
1823 }
1824 }
1825
1826 if (!metaData.isEmpty()) {
1827 def->pluginData.metaData = QJsonDocument::fromJson(metaData);
1828 if (!def->pluginData.metaData.isObject()) {
1829 const QByteArray msg = "Plugin Metadata file " + lexemView()
1830 + " does not contain a valid JSON object. Declaration will be ignored";
1831 warning(msg.constData());
1832 def->pluginData.iid = QByteArray();
1833 def->pluginData.uri = QByteArray();
1834 return;
1835 }
1836 }
1837
1838 mustIncludeQPluginH = true;
1839 next(RPAREN);
1840}
1841
1843{
1844 int nesting = 0;
1845 QByteArray accessor;
1846 while (1) {
1847 Token t = peek();
1848 if (!nesting && (t == RPAREN || t == COMMA))
1849 break;
1850 t = next();
1851 if (t == LPAREN)
1852 ++nesting;
1853 if (t == RPAREN)
1854 --nesting;
1855 accessor += lexemView();
1856 }
1857 return accessor;
1858}
1859
1861{
1862 next(LPAREN);
1863 PropertyDef propDef;
1864 propDef.inPrivateClass = parsePropertyAccessor();
1865
1866 next(COMMA);
1867
1868 createPropertyDef(propDef, int(def->propertyList.size()), mode);
1869
1870 def->propertyList += propDef;
1871}
1872
1873void Moc::parseEnumOrFlag(BaseDef *def, EnumFlags flags)
1874{
1875 next(LPAREN);
1876 QByteArray identifier;
1877 while (test(IDENTIFIER)) {
1878 identifier = lexem();
1879 while (test(SCOPE) && test(IDENTIFIER)) {
1880 identifier += "::";
1881 identifier += lexemView();
1882 }
1883 def->enumDeclarations[identifier] = flags;
1884 }
1885 next(RPAREN);
1886}
1887
1889{
1890 next(LPAREN);
1891 QByteArray flagName, enumName;
1892 while (test(IDENTIFIER)) {
1893 flagName = lexem();
1894 while (test(SCOPE) && test(IDENTIFIER)) {
1895 flagName += "::";
1896 flagName += lexemView();
1897 }
1898 }
1899 next(COMMA);
1900 while (test(IDENTIFIER)) {
1901 enumName = lexem();
1902 while (test(SCOPE) && test(IDENTIFIER)) {
1903 enumName += "::";
1904 enumName += lexemView();
1905 }
1906 }
1907
1908 def->flagAliases.insert(enumName, flagName);
1909 next(RPAREN);
1910}
1911
1913{
1914 bool encounteredQmlMacro = false;
1915 next(LPAREN);
1916 ClassInfoDef infoDef;
1917 next(STRING_LITERAL);
1918 infoDef.name = symbol().unquotedLexem();
1919 if (infoDef.name.startsWith("QML."))
1920 encounteredQmlMacro = true;
1921 next(COMMA);
1922 if (test(STRING_LITERAL)) {
1923 infoDef.value = symbol().unquotedLexem();
1924 } else if (test(Q_REVISION_TOKEN)) {
1925 infoDef.value = QByteArray::number(parseRevision().toEncodedVersion<quint16>());
1926 } else {
1927 // support Q_CLASSINFO("help", QT_TR_NOOP("blah"))
1928 next(IDENTIFIER);
1929 next(LPAREN);
1930 next(STRING_LITERAL);
1931 infoDef.value = symbol().unquotedLexem();
1932 next(RPAREN);
1933 }
1934 next(RPAREN);
1935 def->classInfoList += infoDef;
1936 return encounteredQmlMacro ? EncounteredQmlMacro::Yes : EncounteredQmlMacro::No;
1937}
1938
1940{
1941 if (parseClassInfo(static_cast<BaseDef *>(def)) == EncounteredQmlMacro::Yes)
1943}
1944
1946{
1947 next(LPAREN);
1948 while (test(IDENTIFIER)) {
1949 QList<ClassDef::Interface> iface;
1950 iface += ClassDef::Interface(lexem());
1951 while (test(SCOPE)) {
1952 iface.last().className += lexemView();
1953 next(IDENTIFIER);
1954 iface.last().className += lexemView();
1955 }
1956 while (test(COLON)) {
1957 next(IDENTIFIER);
1958 iface += ClassDef::Interface(lexem());
1959 while (test(SCOPE)) {
1960 iface.last().className += lexemView();
1961 next(IDENTIFIER);
1962 iface.last().className += lexemView();
1963 }
1964 }
1965 // resolve from classnames to interface ids
1966 for (qsizetype i = 0; i < iface.size(); ++i) {
1967 const QByteArray iid = interface2IdMap.value(iface.at(i).className);
1968 if (iid.isEmpty())
1969 error("Undefined interface");
1970
1971 iface[i].interfaceId = iid;
1972 }
1973 def->interfaceList += iface;
1974 }
1975 next(RPAREN);
1976}
1977
1979{
1980 next(LPAREN);
1981 QByteArray interface;
1982 next(IDENTIFIER);
1983 interface += lexemView();
1984 while (test(SCOPE)) {
1985 interface += lexemView();
1986 next(IDENTIFIER);
1987 interface += lexemView();
1988 }
1989 next(COMMA);
1990 QByteArray iid;
1991 if (test(STRING_LITERAL)) {
1992 iid = lexem();
1993 } else {
1994 next(IDENTIFIER);
1995 iid = lexem();
1996 }
1997 interface2IdMap.insert(interface, iid);
1998 next(RPAREN);
1999}
2000
2002{
2003 next(LPAREN);
2004 QByteArray typeName = lexemUntil(RPAREN);
2005 typeName.remove(0, 1);
2006 typeName.chop(1);
2007 metaTypes.append(typeName);
2008}
2009
2011{
2012 next(LPAREN);
2013 QByteArray include = lexemUntil(RPAREN);
2014 // remove parentheses
2015 include.remove(0, 1);
2016 include.chop(1);
2017 includeFiles.append(include);
2018}
2019
2021{
2022 next(LPAREN);
2023 FunctionDef funcDef;
2024 next(IDENTIFIER);
2025 funcDef.inPrivateClass = lexem();
2026 // also allow void functions
2027 if (test(LPAREN)) {
2028 next(RPAREN);
2029 funcDef.inPrivateClass += "()";
2030 }
2031 next(COMMA);
2032 funcDef.access = access;
2033 parseFunction(&funcDef, true);
2034 def->slotList += funcDef;
2035 handleDefaultArguments(&def->slotList, funcDef);
2036 if (funcDef.revision > 0)
2038
2039}
2040
2042{
2043 qsizetype from = index;
2044 until(target);
2045 QByteArray s;
2046 while (from <= index) {
2047 QByteArray n = symbols.at(from++-1).lexem();
2048 if (s.size() && n.size()) {
2049 char prev = s.at(s.size()-1);
2050 char next = n.at(0);
2051 if ((is_ident_char(prev) && is_ident_char(next))
2052 || (prev == '<' && next == ':')
2053 || (prev == '>' && next == '>'))
2054 s += ' ';
2055 }
2056 s += n;
2057 }
2058 return s;
2059}
2060
2061bool Moc::until(Token target) {
2062 int braceCount = 0;
2063 int brackCount = 0;
2064 int parenCount = 0;
2065 int angleCount = 0;
2066 if (index) {
2067 switch(symbols.at(index-1).token) {
2068 case LBRACE: ++braceCount; break;
2069 case LBRACK: ++brackCount; break;
2070 case LPAREN: ++parenCount; break;
2071 case LANGLE: ++angleCount; break;
2072 default: break;
2073 }
2074 }
2075
2076 //when searching commas within the default argument, we should take care of template depth (anglecount)
2077 // unfortunately, we do not have enough semantic information to know if '<' is the operator< or
2078 // the beginning of a template type. so we just use heuristics.
2079 qsizetype possible = -1;
2080
2081 while (index < symbols.size()) {
2082 Token t = symbols.at(index++).token;
2083 switch (t) {
2084 case LBRACE: ++braceCount; break;
2085 case RBRACE: --braceCount; break;
2086 case LBRACK: ++brackCount; break;
2087 case RBRACK: --brackCount; break;
2088 case LPAREN: ++parenCount; break;
2089 case RPAREN: --parenCount; break;
2090 case LANGLE:
2091 if (parenCount == 0 && braceCount == 0)
2092 ++angleCount;
2093 break;
2094 case RANGLE:
2095 if (parenCount == 0 && braceCount == 0)
2096 --angleCount;
2097 break;
2098 case GTGT:
2099 if (parenCount == 0 && braceCount == 0) {
2100 angleCount -= 2;
2101 t = RANGLE;
2102 }
2103 break;
2104 default: break;
2105 }
2106 if (t == target
2107 && braceCount <= 0
2108 && brackCount <= 0
2109 && parenCount <= 0
2110 && (target != RANGLE || angleCount <= 0)) {
2111 if (target != COMMA || angleCount <= 0)
2112 return true;
2113 possible = index;
2114 }
2115
2116 if (target == COMMA && t == EQ && possible != -1) {
2117 index = possible;
2118 return true;
2119 }
2120
2121 if (braceCount < 0 || brackCount < 0 || parenCount < 0
2122 || (target == RANGLE && angleCount < 0)) {
2123 --index;
2124 break;
2125 }
2126
2127 if (braceCount <= 0 && t == SEMIC) {
2128 // Abort on semicolon. Allow recovering bad template parsing (QTBUG-31218)
2129 break;
2130 }
2131 }
2132
2133 if (target == COMMA && angleCount != 0 && possible != -1) {
2134 index = possible;
2135 return true;
2136 }
2137
2138 return false;
2139}
2140
2142{
2143 Q_ASSERT(!def->superclassList.isEmpty());
2144 const QByteArray &firstSuperclass = def->superclassList.at(0).classname;
2145
2146 if (!knownQObjectClasses.contains(firstSuperclass)) {
2147 // enable once we /require/ include paths
2148#if 0
2149 const QByteArray msg
2150 = "Class "
2151 + def->className
2152 + " contains the Q_OBJECT macro and inherits from "
2153 + def->superclassList.value(0)
2154 + " but that is not a known QObject subclass. You may get compilation errors.";
2155 warning(msg.constData());
2156#endif
2157 return;
2158 }
2159
2160 auto isRegisteredInterface = [&def](QByteArrayView super) {
2161 auto matchesSuperClass = [&super](const auto &ifaces) {
2162 return !ifaces.isEmpty() && ifaces.first().className == super;
2163 };
2164 return std::any_of(def->interfaceList.cbegin(), def->interfaceList.cend(), matchesSuperClass);
2165 };
2166
2167 const auto end = def->superclassList.cend();
2168 auto it = def->superclassList.cbegin() + 1;
2169 for (; it != end; ++it) {
2170 const QByteArray &superClass = it->classname;
2171 if (knownQObjectClasses.contains(superClass)) {
2172 const QByteArray msg
2173 = "Class "
2174 + def->classname
2175 + " inherits from two QObject subclasses "
2176 + firstSuperclass
2177 + " and "
2178 + superClass
2179 + ". This is not supported!";
2180 warning(msg.constData());
2181 }
2182
2183 if (interface2IdMap.contains(superClass)) {
2184 if (!isRegisteredInterface(superClass)) {
2185 const QByteArray msg
2186 = "Class "
2187 + def->classname
2188 + " implements the interface "
2189 + superClass
2190 + " but does not list it in Q_INTERFACES. qobject_cast to "
2191 + superClass
2192 + " will not work!";
2193 warning(msg.constData());
2194 }
2195 }
2196 }
2197}
2198
2200{
2201 //
2202 // specify get function, for compatibility we accept functions
2203 // returning pointers, or const char * for QByteArray.
2204 //
2205 QDuplicateTracker<QByteArray> definedProperties(cdef->propertyList.size());
2206 auto hasNoAttributes = [&](const PropertyDef &p) {
2207 if (definedProperties.hasSeen(p.name)) {
2208 QByteArray msg = "The property '" + p.name + "' is defined multiple times in class " + cdef->classname + ".";
2209 warning(msg.constData());
2210 }
2211
2212 if (p.read.isEmpty() && p.member.isEmpty() && p.bind.isEmpty()) {
2213 QByteArray msg = "Property declaration " + p.name + " has neither an associated QProperty<> member"
2214 ", nor a READ accessor function nor an associated MEMBER variable. The property will be invalid.";
2215 const auto &sym = p.location >= 0 ? symbolAt(p.location) : Symbol();
2216 warning(sym, msg.constData());
2217 if (p.write.isEmpty())
2218 return true;
2219 }
2220 return false;
2221 };
2222 cdef->propertyList.removeIf(hasNoAttributes);
2223
2224 for (PropertyDef &p : cdef->propertyList) {
2225 for (const FunctionDef &f : std::as_const(cdef->publicList)) {
2226 if (f.name != p.read)
2227 continue;
2228 if (!f.isConst) // get functions must be const
2229 continue;
2230 if (f.arguments.size()) // and must not take any arguments
2231 continue;
2232 PropertyDef::Specification spec = PropertyDef::ValueSpec;
2233 QByteArray tmp = f.normalizedType;
2234 if (p.type == "QByteArray" && tmp == "const char *")
2235 tmp = "QByteArray";
2236 if (tmp.left(6) == "const ")
2237 tmp = tmp.mid(6);
2238 if (p.type != tmp && tmp.endsWith('*')) {
2239 tmp.chop(1);
2240 spec = PropertyDef::PointerSpec;
2241 } else if (f.type.name.endsWith('&')) { // raw type, not normalized type
2242 spec = PropertyDef::ReferenceSpec;
2243 }
2244 if (p.type != tmp)
2245 continue;
2246 p.gspec = spec;
2247 break;
2248 }
2249 if (!p.notify.isEmpty()) {
2250 int notifyId = -1;
2251 for (int j = 0; j < int(cdef->signalList.size()); ++j) {
2252 const FunctionDef &f = cdef->signalList.at(j);
2253 if (f.name != p.notify) {
2254 continue;
2255 } else {
2256 notifyId = j /* Signal indexes start from 0 */;
2257 break;
2258 }
2259 }
2260 p.notifyId = notifyId;
2261 if (notifyId == -1) {
2262 const int index = int(cdef->nonClassSignalList.indexOf(p.notify));
2263 if (index == -1) {
2264 cdef->nonClassSignalList << p.notify;
2265 p.notifyId = int(-1 - cdef->nonClassSignalList.size());
2266 } else {
2267 p.notifyId = int(-2 - index);
2268 }
2269 }
2270 }
2271 }
2272}
2273
2274QJsonObject ClassDef::toJson() const
2275{
2276 QJsonObject cls;
2277 cls["className"_L1] = QString::fromUtf8(classname.constData());
2278 cls["qualifiedClassName"_L1] = QString::fromUtf8(qualified.constData());
2279 cls["lineNumber"_L1] = lineNumber;
2280 if (isFinal)
2281 cls["final"_L1] = true;
2282
2283 QJsonArray classInfos;
2284 for (const auto &info: std::as_const(classInfoList)) {
2285 QJsonObject infoJson;
2286 infoJson["name"_L1] = QString::fromUtf8(info.name);
2287 infoJson["value"_L1] = QString::fromUtf8(info.value);
2288 classInfos.append(infoJson);
2289 }
2290
2291 if (classInfos.size())
2292 cls["classInfos"_L1] = classInfos;
2293
2294 int methodIndex = 0;
2295 const auto appendFunctions
2296 = [&cls, &methodIndex](const QString &type, const QList<FunctionDef> &funcs) {
2297 QJsonArray jsonFuncs;
2298
2299 for (const FunctionDef &fdef: funcs)
2300 jsonFuncs.append(fdef.toJson(methodIndex++));
2301
2302 if (!jsonFuncs.isEmpty())
2303 cls[type] = jsonFuncs;
2304 };
2305
2306 // signals, slots, and methods, in this order, follow the same index
2307 appendFunctions("signals"_L1, signalList);
2308 appendFunctions("slots"_L1, slotList);
2309 appendFunctions("methods"_L1, methodList);
2310
2311 // constructors are indexed separately.
2312 methodIndex = 0;
2313 appendFunctions("constructors"_L1, constructorList);
2314
2315 QJsonArray props;
2316
2317 for (const PropertyDef &propDef: std::as_const(propertyList))
2318 props.append(propDef.toJson());
2319
2320 if (!props.isEmpty())
2321 cls["properties"_L1] = props;
2322
2323 if (hasQObject)
2324 cls["object"_L1] = true;
2325 if (hasQGadget)
2326 cls["gadget"_L1] = true;
2327 if (hasQNamespace)
2328 cls["namespace"_L1] = true;
2329
2330 QJsonArray superClasses;
2331
2332 for (const auto &super: std::as_const(superclassList)) {
2333 QJsonObject superCls;
2334 superCls["name"_L1] = QString::fromUtf8(super.classname);
2335 if (super.classname != super.qualified)
2336 superCls["fullyQualifiedName"_L1] = QString::fromUtf8(super.qualified);
2337 FunctionDef::accessToJson(&superCls, super.access);
2338 superClasses.append(superCls);
2339 }
2340
2341 if (!superClasses.isEmpty())
2342 cls["superClasses"_L1] = superClasses;
2343
2344 QJsonArray enums;
2345 for (const EnumDef &enumDef: std::as_const(enumList))
2346 enums.append(enumDef.toJson(*this));
2347 if (!enums.isEmpty())
2348 cls["enums"_L1] = enums;
2349
2350 QJsonArray ifaces;
2351 for (const QList<Interface> &ifaceList : interfaceList) {
2352 QJsonArray jsonList;
2353 for (const Interface &iface: ifaceList) {
2354 QJsonObject ifaceJson;
2355 ifaceJson["id"_L1] = QString::fromUtf8(iface.interfaceId);
2356 ifaceJson["className"_L1] = QString::fromUtf8(iface.className);
2357 jsonList.append(ifaceJson);
2358 }
2359 ifaces.append(jsonList);
2360 }
2361 if (!ifaces.isEmpty())
2362 cls["interfaces"_L1] = ifaces;
2363
2364 return cls;
2365}
2366
2367QJsonObject FunctionDef::toJson(int index) const
2368{
2369 QJsonObject fdef;
2370 fdef["name"_L1] = QString::fromUtf8(name);
2371 fdef["index"_L1] = index;
2372 if (!tag.isEmpty())
2373 fdef["tag"_L1] = QString::fromUtf8(tag);
2374 fdef["returnType"_L1] = QString::fromUtf8(normalizedType);
2375 if (isConst)
2376 fdef["isConst"_L1] = true;
2377
2378 QJsonArray args;
2379 for (const ArgumentDef &arg: arguments)
2380 args.append(arg.toJson());
2381
2382 if (!args.isEmpty())
2383 fdef["arguments"_L1] = args;
2384
2386
2387 if (revision > 0)
2388 fdef["revision"_L1] = revision;
2389 fdef["lineNumber"_L1] = lineNumber;
2390
2391 if (wasCloned)
2392 fdef["isCloned"_L1] = true;
2393
2394 return fdef;
2395}
2396
2397void FunctionDef::accessToJson(QJsonObject *obj, FunctionDef::Access acs)
2398{
2399 switch (acs) {
2400 case Private: (*obj)["access"_L1] = "private"_L1; break;
2401 case Public: (*obj)["access"_L1] = "public"_L1; break;
2402 case Protected: (*obj)["access"_L1] = "protected"_L1; break;
2403 }
2404}
2405
2406QJsonObject ArgumentDef::toJson() const
2407{
2408 QJsonObject arg;
2409 arg["type"_L1] = QString::fromUtf8(normalizedType);
2410 if (!name.isEmpty())
2411 arg["name"_L1] = QString::fromUtf8(name);
2412 return arg;
2413}
2414
2415QJsonObject PropertyDef::toJson() const
2416{
2417 QJsonObject prop;
2418 prop["name"_L1] = QString::fromUtf8(name);
2419 prop["type"_L1] = QString::fromUtf8(type);
2420
2421 const auto jsonify = [&prop](const char *str, const QByteArray &member) {
2422 if (!member.isEmpty())
2423 prop[QLatin1StringView(str)] = QString::fromUtf8(member);
2424 };
2425
2426 jsonify("member", member);
2427 jsonify("read", read);
2428 jsonify("write", write);
2429 jsonify("bindable", bind);
2430 jsonify("reset", reset);
2431 jsonify("notify", notify);
2432 jsonify("privateClass", inPrivateClass);
2433
2434 const auto jsonifyBoolOrString = [&prop](const char *str, const QByteArray &boolOrString) {
2435 QJsonValue value;
2436 if (boolOrString == "true")
2437 value = true;
2438 else if (boolOrString == "false")
2439 value = false;
2440 else
2441 value = QString::fromUtf8(boolOrString); // function name to query at run-time
2442 prop[QLatin1StringView(str)] = value;
2443 };
2444
2445 jsonifyBoolOrString("designable", designable);
2446 jsonifyBoolOrString("scriptable", scriptable);
2447 jsonifyBoolOrString("stored", stored);
2448 jsonifyBoolOrString("user", user);
2449
2450 prop["constant"_L1] = constant;
2451 prop["final"_L1] = final;
2452 prop["virtual"_L1] = virtual_;
2453 prop["override"_L1] = override;
2454 prop["required"_L1] = required;
2455 prop["index"_L1] = relativeIndex;
2456 prop["lineNumber"_L1] = lineNumber;
2457 if (revision > 0)
2458 prop["revision"_L1] = revision;
2459
2460 return prop;
2461}
2462
2463QJsonObject EnumDef::toJson(const ClassDef &cdef) const
2464{
2465 QJsonObject def;
2466 uint flags = this->flags | cdef.enumDeclarations.value(name);
2467 def["name"_L1] = QString::fromUtf8(name);
2468 def["lineNumber"_L1] = lineNumber;
2469 if (!enumName.isEmpty())
2470 def["alias"_L1] = QString::fromUtf8(enumName);
2471 if (!type.isEmpty())
2472 def["type"_L1] = QString::fromUtf8(type);
2473 def["isFlag"_L1] = (flags & EnumIsFlag) != 0;
2474 def["isClass"_L1] = (flags & EnumIsScoped) != 0;
2475
2476 QJsonArray valueArr;
2477 for (const QByteArray &value: values)
2478 valueArr.append(QString::fromUtf8(value));
2479 if (!valueArr.isEmpty())
2480 def["values"_L1] = valueArr;
2481
2482 return def;
2483}
2484
2486{
2487 if (name == cdef->classname) {
2488 // The name of the enclosing namespace is the same as the enum class name
2489 if (cdef->qualified.contains("::")) {
2490 // QTBUG-112996, fully qualify by using cdef->qualified to disambiguate enum
2491 // class name and enclosing namespace, e.g.:
2492 // namespace A { namespace B { Q_NAMESPACE; enum class B { }; Q_ENUM_NS(B) } }
2493 return cdef->qualified % "::" % name;
2494 } else {
2495 // Just "B"; otherwise the compiler complains about the type "B::B" inside
2496 // "B::staticMetaObject" in the generated code; e.g.:
2497 // namespace B { Q_NAMESPACE; enum class B { }; Q_ENUM_NS(B) }
2498 return name;
2499 }
2500 }
2501 return cdef->classname % "::" % name;
2502}
2503
2504QT_END_NAMESPACE
Definition moc.h:234
bool testFunctionAttribute(Token tok, FunctionDef *def)
Definition moc.cpp:359
void parseEnumOrFlag(BaseDef *def, QtMocConstants::EnumFlags flags)
Definition moc.cpp:1873
bool hasGlobalModuleFragment
Definition moc.h:262
void checkSuperClasses(ClassDef *def)
Definition moc.cpp:2141
void parse()
Definition moc.cpp:775
bool inPrivateModuleFragment
Definition moc.h:261
bool parseEnum(EnumDef *def, ClassDef *containingClass)
Definition moc.cpp:250
void parseProperty(ClassDef *def, PropertyMode mode)
Definition moc.cpp:1768
QByteArray lexemUntil(Token)
Definition moc.cpp:2041
EncounteredQmlMacro parseClassInfo(BaseDef *def)
Definition moc.cpp:1912
bool until(Token)
Definition moc.cpp:2061
void createPropertyDef(PropertyDef &def, int propertyIndex, PropertyMode mode)
Definition moc.cpp:1568
void parseClassInfo(ClassDef *def)
Definition moc.cpp:1939
QByteArrayView strippedFileName() const
Definition moc.cpp:1263
bool parseClassHead(ClassDef *def)
Definition moc.cpp:39
void parsePrivateProperty(ClassDef *def, PropertyMode mode)
Definition moc.cpp:1860
void parseFlag(BaseDef *def)
Definition moc.cpp:1888
void parsePrivateModuleFragment(qsizetype rewind)
Definition moc.cpp:754
void parseSignals(ClassDef *def)
Definition moc.cpp:1524
void parseDeclareMetatype()
Definition moc.cpp:2001
void parsePropertyAttributes(PropertyDef &propDef)
Definition moc.cpp:1607
void parseInterfaces(ClassDef *def)
Definition moc.cpp:1945
bool testFunctionRevision(FunctionDef *def)
Definition moc.cpp:422
bool testFunctionAttribute(FunctionDef *def)
Definition moc.cpp:350
void prependNamespaces(BaseDef &def, const QList< NamespaceDef > &namespaceList) const
Definition moc.cpp:656
bool parseFunction(FunctionDef *def, bool inMacro=false)
Definition moc.cpp:434
QByteArray parsePropertyAccessor()
Definition moc.cpp:1842
bool testForFunctionModifiers(FunctionDef *def)
Definition moc.cpp:538
const QByteArray & toFullyQualified(const QByteArray &name) const noexcept
Definition moc.cpp:30
void parseSlots(ClassDef *def, FunctionDef::Access access)
Definition moc.cpp:1482
void parseDeclareInterface()
Definition moc.cpp:1978
void checkListSizes(const ClassDef &def)
Definition moc.cpp:666
QTypeRevision parseRevision()
Definition moc.cpp:391
void parseMocInclude()
Definition moc.cpp:2010
bool skipCxxAttributes()
Definition moc.cpp:382
PropertyMode
Definition moc.h:236
@ Anonymous
Definition moc.h:236
@ Named
Definition moc.h:236
ModuleUnitKind moduleUnitKind
Definition moc.h:258
bool mustIncludeQPluginH
Definition moc.h:245
bool parseMaybeFunction(const ClassDef *cdef, FunctionDef *def)
Definition moc.cpp:546
void checkProperties(ClassDef *cdef)
Definition moc.cpp:2199
Type parseType()
Definition moc.cpp:130
void parseModuleDeclaration(qsizetype rewind, bool exported)
Definition moc.cpp:702
void parseFunctionArguments(FunctionDef *def)
Definition moc.cpp:310
void parseSlotInPrivate(ClassDef *def, FunctionDef::Access access)
Definition moc.cpp:2020
bool inClass(const ClassDef *def) const
Definition moc.h:278
void parsePluginData(ClassDef *def)
Definition moc.cpp:1778
void generate(FILE *out, FILE *jsonOutput)
Definition moc.cpp:1340
bool noInclude
Definition moc.h:244
EncounteredQmlMacro
Definition moc.h:307
bool inNamespace(const NamespaceDef *def) const
Definition moc.h:282
\inmodule QtCore\reentrant
Definition qlist.h:82
\inmodule QtCore
constexpr QTypeRevision()=default
Produces an invalid revision.
static bool any_arg_contains(const QList< FunctionDef > &functions, const QByteArray &pattern)
Definition moc.cpp:1284
static QByteArrayList requiredQtContainers(const QList< ClassDef > &classes)
Definition moc.cpp:1309
static QByteArray normalizeType(const QByteArray &ba)
Definition moc.cpp:25
IncludeState
Definition moc.cpp:244
@ IncludeBegin
Definition moc.cpp:245
static QByteArrayList make_candidates()
Definition moc.cpp:1295
static bool any_type_contains(const QList< PropertyDef > &properties, const QByteArray &pattern)
Definition moc.cpp:1275
void handleDefaultArguments(QList< FunctionDef > *functionList, FunctionDef &function)
Definition moc.cpp:644
ModuleUnitKind
Definition moc.h:225
@ InterfacePartition
Definition moc.h:228
@ InternalPartition
Definition moc.h:229
@ PrimaryInterface
Definition moc.h:227
@ ImplementationUnit
Definition moc.h:230
TypeTag
Definition moc.h:23
@ HasEnum
Definition moc.h:27
@ HasClass
Definition moc.h:26
@ HasStruct
Definition moc.h:25
bool is_ident_char(char s)
Definition utils.h:30
QJsonObject toJson() const
Definition moc.cpp:2406
bool isDefault
Definition moc.h:70
Definition moc.h:162
bool hasQObject
Definition moc.h:208
bool hasQGadget
Definition moc.h:209
bool isFinal
Definition moc.h:212
bool requireCompleteMethodTypes
Definition moc.h:211
int revisionedMethods
Definition moc.h:206
QJsonObject toJson() const
Definition moc.cpp:2274
Definition moc.h:53
QByteArray qualifiedType(const ClassDef *cdef) const
Definition moc.cpp:2485
QJsonObject toJson(const ClassDef &cdef) const
Definition moc.cpp:2463
int lineNumber
Definition moc.h:61
bool isVirtual
Definition moc.h:91
bool isScriptable
Definition moc.h:100
bool wasCloned
Definition moc.h:94
QJsonObject toJson(int index) const
Definition moc.cpp:2367
bool isCompat
Definition moc.h:98
bool inlineCode
Definition moc.h:93
bool isRawSlot
Definition moc.h:107
static void accessToJson(QJsonObject *obj, Access acs)
Definition moc.cpp:2397
Access access
Definition moc.h:86
bool isSignal
Definition moc.h:102
bool isSlot
Definition moc.h:101
bool isInvokable
Definition moc.h:99
bool isConst
Definition moc.h:90
int lineNumber
Definition moc.h:88
int revision
Definition moc.h:87
bool isAbstract
Definition moc.h:106
bool isPrivateSignal
Definition moc.h:103
bool isDestructor
Definition moc.h:105
@ Public
Definition moc.h:85
@ Protected
Definition moc.h:85
@ Private
Definition moc.h:85
bool isConstructor
Definition moc.h:104
bool isStatic
Definition moc.h:92
bool hasQNamespace
Definition moc.h:220
int lineNumber
Definition moc.h:137
bool final
Definition moc.h:132
QJsonObject toJson() const
Definition moc.cpp:2415
bool constant
Definition moc.h:131
bool override
Definition moc.h:134
bool virtual_
Definition moc.h:133
int revision
Definition moc.h:129
int relativeIndex
Definition moc.h:136
bool required
Definition moc.h:135
Token token
Definition symbols.h:58
Symbol()=default