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
generator.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// Copyright (C) 2019 Olivier Goffart <ogoffart@woboq.com>
3// Copyright (C) 2018 Intel Corporation.
4// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
5
6#include "generator.h"
7#include "cbordevice.h"
9#include "utils.h"
10#include <QtCore/qmetatype.h>
11#include <QtCore/qjsondocument.h>
12#include <QtCore/qjsonobject.h>
13#include <QtCore/qjsonvalue.h>
14#include <QtCore/qjsonarray.h>
15#include <QtCore/qplugin.h>
16#include <QtCore/qstringview.h>
17#include <QtCore/qtmocconstants.h>
18
19#include <math.h>
20#include <stdio.h>
21
22#include <private/qmetaobject_p.h> //for the flags.
23#include <private/qplugin_p.h> //for the flags.
24
25QT_BEGIN_NAMESPACE
26
27using namespace QtMiscUtils;
28
29uint nameToBuiltinType(const QByteArray &name)
30{
31 if (name.isEmpty())
32 return 0;
33
34 uint tp = qMetaTypeTypeInternal(name.constData());
35 return tp < uint(QMetaType::User) ? tp : uint(QMetaType::UnknownType);
36}
37
38/*
39 Returns \c true if the type is a built-in type.
40*/
41bool isBuiltinType(const QByteArray &type)
42 {
43 int id = qMetaTypeTypeInternal(type.constData());
44 if (id == QMetaType::UnknownType)
45 return false;
46 return (id < QMetaType::User);
47}
48
49static const char *metaTypeEnumValueString(int type)
50 {
51#define RETURN_METATYPENAME_STRING(MetaTypeName, MetaTypeId, RealType)
52 case QMetaType::MetaTypeName: return #MetaTypeName;
53
54 switch (type) {
55QT_FOR_EACH_STATIC_TYPE(RETURN_METATYPENAME_STRING)
56 }
57#undef RETURN_METATYPENAME_STRING
58 return nullptr;
59 }
60
61 Generator::Generator(Moc *moc, ClassDef *classDef, const QList<QByteArray> &metaTypes,
62 const QHash<QByteArray, QByteArray> &knownQObjectClasses,
63 const QHash<QByteArray, QByteArray> &knownGadgets, FILE *outfile,
64 bool requireCompleteTypes)
65 : parser(moc),
66 out(outfile),
67 cdef(classDef),
71 requireCompleteTypes(requireCompleteTypes)
72 {
73 if (cdef->superclassList.size())
74 purestSuperClass = cdef->superclassList.constFirst().classname;
75}
76
77static inline qsizetype lengthOfEscapeSequence(const QByteArray &s, qsizetype i)
78{
79 if (s.at(i) != '\\' || i >= s.size() - 1)
80 return 1;
81 const qsizetype startPos = i;
82 ++i;
83 char ch = s.at(i);
84 if (ch == 'x') {
85 ++i;
86 while (i < s.size() && isHexDigit(s.at(i)))
87 ++i;
88 } else if (isOctalDigit(ch)) {
89 while (i < startPos + 4
90 && i < s.size()
91 && isOctalDigit(s.at(i))) {
92 ++i;
93 }
94 } else { // single character escape sequence
95 i = qMin(i + 1, s.size());
96 }
97 return i - startPos;
98}
99
100// Prints \a s to \a out, breaking it into lines of at most ColumnWidth. The
101// opening and closing quotes are NOT included (it's up to the caller).
102static void printStringWithIndentation(FILE *out, const QByteArray &s)
103{
104 static constexpr int ColumnWidth = 72;
105 const qsizetype len = s.size();
106 qsizetype idx = 0;
107
108 do {
109 qsizetype spanLen = qMin(ColumnWidth - 2, len - idx);
110 // don't cut escape sequences at the end of a line
111 const qsizetype backSlashPos = s.lastIndexOf('\\', idx + spanLen - 1);
112 if (backSlashPos >= idx) {
113 const qsizetype escapeLen = lengthOfEscapeSequence(s, backSlashPos);
114 spanLen = qBound(spanLen, backSlashPos + escapeLen - idx, len - idx);
115 }
116 fprintf(out, "\n \"%.*s\"", int(spanLen), s.constData() + idx);
117 idx += spanLen;
118 } while (idx < len);
119}
120
121void Generator::strreg(const QByteArray &s)
122{
123 if (!strings.contains(s))
124 strings.append(s);
125}
126
127int Generator::stridx(const QByteArray &s)
128{
129 int i = int(strings.indexOf(s));
130 Q_ASSERT_X(i != -1, Q_FUNC_INFO, "We forgot to register some strings");
131 return i;
132}
133
134bool Generator::registerableMetaType(const QByteArray &propertyType)
135{
136 if (metaTypes.contains(propertyType))
137 return true;
138
139 if (propertyType.endsWith('*')) {
140 QByteArray objectPointerType = propertyType;
141 // The objects container stores class names, such as 'QState', 'QLabel' etc,
142 // not 'QState*', 'QLabel*'. The propertyType does contain the '*', so we need
143 // to chop it to find the class type in the known QObjects list.
144 objectPointerType.chop(1);
145 if (knownQObjectClasses.contains(objectPointerType))
146 return true;
147 }
148
149 static const QList<QByteArray> smartPointers = QList<QByteArray>()
150#define STREAM_SMART_POINTER(SMART_POINTER) << #SMART_POINTER
151 QT_FOR_EACH_AUTOMATIC_TEMPLATE_SMART_POINTER(STREAM_SMART_POINTER)
152#undef STREAM_SMART_POINTER
153 ;
154
155 for (const QByteArray &smartPointer : smartPointers) {
156 QByteArray ba = smartPointer + "<";
157 if (propertyType.startsWith(ba) && !propertyType.endsWith("&"))
158 return knownQObjectClasses.contains(propertyType.mid(smartPointer.size() + 1, propertyType.size() - smartPointer.size() - 1 - 1));
159 }
160
161 static const QList<QByteArray> oneArgTemplates = QList<QByteArray>()
162#define STREAM_1ARG_TEMPLATE(TEMPLATENAME) << #TEMPLATENAME
163 QT_FOR_EACH_AUTOMATIC_TEMPLATE_1ARG(STREAM_1ARG_TEMPLATE)
164#undef STREAM_1ARG_TEMPLATE
165 ;
166 for (const QByteArray &oneArgTemplateType : oneArgTemplates) {
167 const QByteArray ba = oneArgTemplateType + "<";
168 if (propertyType.startsWith(ba) && propertyType.endsWith(">")) {
169 const qsizetype argumentSize = propertyType.size() - ba.size()
170 // The closing '>'
171 - 1
172 // templates inside templates have an extra whitespace char to strip.
173 - (propertyType.at(propertyType.size() - 2) == ' ' ? 1 : 0 );
174 const QByteArray templateArg = propertyType.sliced(ba.size(), argumentSize);
175 return isBuiltinType(templateArg) || registerableMetaType(templateArg);
176 }
177 }
178 return false;
179}
180
181/* returns \c true if name and qualifiedName refers to the same name.
182 * If qualified name is "A::B::C", it returns \c true for "C", "B::C" or "A::B::C" */
183static bool qualifiedNameEquals(const QByteArray &qualifiedName, const QByteArray &name)
184{
185 if (qualifiedName == name)
186 return true;
187 const qsizetype index = qualifiedName.indexOf("::");
188 if (index == -1)
189 return false;
190 return qualifiedNameEquals(qualifiedName.mid(index+2), name);
191}
192
193static QByteArray generateQualifiedClassNameIdentifier(const QByteArray &identifier)
194{
195 // This is similar to the IA-64 C++ ABI mangling scheme.
196 QByteArray qualifiedClassNameIdentifier = "ZN";
197 for (const auto scope : qTokenize(QLatin1StringView(identifier), QLatin1Char(':'),
198 Qt::SkipEmptyParts)) {
199 qualifiedClassNameIdentifier += QByteArray::number(scope.size());
200 qualifiedClassNameIdentifier += scope;
201 }
202 qualifiedClassNameIdentifier += 'E';
203 return qualifiedClassNameIdentifier;
204}
205
207{
208 bool isQObject = (cdef->classname == "QObject");
209 bool isConstructible = !cdef->constructorList.isEmpty();
210
211 // filter out undeclared enumerators and sets
212 {
213 QList<EnumDef> enumList;
214 for (EnumDef def : std::as_const(cdef->enumList)) {
215 if (cdef->enumDeclarations.contains(def.name)) {
216 enumList += def;
217 }
218 def.enumName = def.name;
219 QByteArray alias = cdef->flagAliases.value(def.name);
220 if (cdef->enumDeclarations.contains(alias)) {
221 def.name = alias;
222 enumList += def;
223 }
224 }
225 cdef->enumList = enumList;
226 }
227
228//
229// Register all strings used in data section
230//
231 strreg(cdef->qualified);
232 registerClassInfoStrings();
233 registerFunctionStrings(cdef->signalList);
234 registerFunctionStrings(cdef->slotList);
235 registerFunctionStrings(cdef->methodList);
236 registerFunctionStrings(cdef->constructorList);
237 registerByteArrayVector(cdef->nonClassSignalList);
238 registerPropertyStrings();
239 registerEnumStrings();
240
241 const bool requireCompleteness = requireCompleteTypes || cdef->requireCompleteMethodTypes;
242 bool hasStaticMetaCall =
243 (cdef->hasQObject || !cdef->methodList.isEmpty()
244 || !cdef->propertyList.isEmpty() || !cdef->constructorList.isEmpty());
245 if (parser->activeQtMode)
246 hasStaticMetaCall = false;
247
248 const QByteArray qualifiedClassNameIdentifier = generateQualifiedClassNameIdentifier(cdef->qualified);
249
250 // type name for the Q_OJBECT/GADGET itself, void for namespaces
251 const char *ownType = !cdef->hasQNamespace ? cdef->classname.data() : "void";
252
253 // ensure the qt_meta_tag_XXXX_t type is local
254 fprintf(out, "namespace {\n"
255 "struct qt_meta_tag_%s_t {};\n"
256 "} // unnamed namespace\n\n",
257 qualifiedClassNameIdentifier.constData());
258
259//
260// Build the strings using QtMocHelpers::stringData
261//
262
263 fprintf(out, "static constexpr auto qt_meta_stringdata_%s = QtMocHelpers::stringData(",
264 qualifiedClassNameIdentifier.constData());
265 {
266 char comma = 0;
267 for (const QByteArray &str : strings) {
268 if (comma)
269 fputc(comma, out);
270 printStringWithIndentation(out, str);
271 comma = ',';
272 }
273 }
274 fprintf(out, "\n);\n\n");
275
276//
277// build the data array
278//
279
280 // We define a method inside the context of the class or namespace we're
281 // creating the meta object for, so we get access to everything it has
282 // access to and with the same contexts (for example, member enums and
283 // types).
284 fprintf(out, "template <> constexpr inline auto %s::qt_create_metaobjectdata<qt_meta_tag_%s_t>()\n"
285 "{\n"
286 " namespace QMC = QtMocConstants;\n"
287 " QtMocHelpers::UintData qt_methods {\n",
288 cdef->qualified.constData(), qualifiedClassNameIdentifier.constData());
289
290 // Build signals array first, otherwise the signal indices would be wrong
291 addFunctions(cdef->signalList, "Signal");
292 addFunctions(cdef->slotList, "Slot");
293 addFunctions(cdef->methodList, "Method");
294 fprintf(out, " };\n"
295 " QtMocHelpers::UintData qt_properties {\n");
296 addProperties();
297 fprintf(out, " };\n"
298 " QtMocHelpers::UintData qt_enums {\n");
299 addEnums();
300 fprintf(out, " };\n");
301
302 const char *uintDataParams = "";
303 if (isConstructible || !cdef->classInfoList.isEmpty()) {
304 if (isConstructible) {
305 fprintf(out, " using Constructor = QtMocHelpers::NoType;\n"
306 " QtMocHelpers::UintData qt_constructors {\n");
307 addFunctions(cdef->constructorList, "Constructor");
308 fprintf(out, " };\n");
309 } else {
310 fputs(" QtMocHelpers::UintData qt_constructors {};\n", out);
311 }
312
313 uintDataParams = ", qt_constructors";
314 if (!cdef->classInfoList.isEmpty()) {
315 fprintf(out, " QtMocHelpers::ClassInfos qt_classinfo({\n");
316 addClassInfos();
317 fprintf(out, " });\n");
318 uintDataParams = ", qt_constructors, qt_classinfo";
319 }
320 }
321
322 const char *metaObjectFlags = "QMC::MetaObjectFlag{}";
323 if (cdef->hasQGadget || cdef->hasQNamespace) {
324 // Ideally, all the classes could have that flag. But this broke
325 // classes generated by qdbusxml2cpp which generate code that require
326 // that we call qt_metacall for properties.
327 metaObjectFlags = "QMC::PropertyAccessInStaticMetaCall";
328 }
329 {
330 QByteArray tagType = "qt_meta_tag_" + qualifiedClassNameIdentifier + "_t";
331 if (requireCompleteness)
332 tagType = "QtMocHelpers::ForceCompleteMetaTypes<" + tagType + '>';
333 fprintf(out, " return QtMocHelpers::metaObjectData<%s, %s>(%s,\n"
334 " qt_methods, qt_properties, qt_enums%s);\n"
335 "}\n",
336 ownType, tagType.constData(), metaObjectFlags, uintDataParams);
337 }
338
339 QByteArray metaVarNameSuffix;
340 if (cdef->hasQNamespace) {
341 // Q_NAMESPACE does not define the variables, so we have to. Declare as
342 // plain, file-scope static variables (not templates).
343 metaVarNameSuffix = '_' + qualifiedClassNameIdentifier;
344 const char *n = metaVarNameSuffix.constData();
345 fprintf(out, R"(
346static constexpr auto qt_staticMetaObjectContent%s =
347 %s::qt_create_metaobjectdata<qt_meta_tag%s_t>();
348static constexpr auto qt_staticMetaObjectStaticContent%s =
349 qt_staticMetaObjectContent%s.data;
350static constexpr auto qt_staticMetaObjectRelocatingContent%s =
351 qt_staticMetaObjectContent%s.metaTypes;
352
353)",
354 n, cdef->qualified.constData(), n,
355 n, n,
356 n, n);
357 } else {
358 // Q_OBJECT and Q_GADGET do declare them, so we just use the templates.
359 metaVarNameSuffix = "<qt_meta_tag_" + qualifiedClassNameIdentifier + "_t>";
360 }
361
362//
363// Build extra array
364//
365 QList<QByteArray> extraList;
366 QMultiHash<QByteArray, QByteArray> knownExtraMetaObject(knownGadgets);
367 knownExtraMetaObject.unite(knownQObjectClasses);
368
369 for (const PropertyDef &p : std::as_const(cdef->propertyList)) {
370 if (isBuiltinType(p.type))
371 continue;
372
373 if (p.type.contains('*') || p.type.contains('<') || p.type.contains('>'))
374 continue;
375
376 const qsizetype s = p.type.lastIndexOf("::");
377 if (s <= 0)
378 continue;
379
380 QByteArray unqualifiedScope = p.type.left(s);
381
382 // The scope may be a namespace for example, so it's only safe to include scopes that are known QObjects (QTBUG-2151)
383 QMultiHash<QByteArray, QByteArray>::ConstIterator scopeIt;
384
385 QByteArray thisScope = cdef->qualified;
386 do {
387 const qsizetype s = thisScope.lastIndexOf("::");
388 thisScope = thisScope.left(s);
389 QByteArray currentScope = thisScope.isEmpty() ? unqualifiedScope : thisScope + "::" + unqualifiedScope;
390 scopeIt = knownExtraMetaObject.constFind(currentScope);
391 } while (!thisScope.isEmpty() && scopeIt == knownExtraMetaObject.constEnd());
392
393 if (scopeIt == knownExtraMetaObject.constEnd())
394 continue;
395
396 const QByteArray &scope = *scopeIt;
397
398 if (scope == "Qt")
399 continue;
400 if (qualifiedNameEquals(cdef->qualified, scope))
401 continue;
402
403 if (!extraList.contains(scope))
404 extraList += scope;
405 }
406
407 // QTBUG-20639 - Accept non-local enums for QML signal/slot parameters.
408 // Look for any scoped enum declarations, and add those to the list
409 // of extra/related metaobjects for this object.
410 for (auto it = cdef->enumDeclarations.keyBegin(),
411 end = cdef->enumDeclarations.keyEnd(); it != end; ++it) {
412 const QByteArray &enumKey = *it;
413 const qsizetype s = enumKey.lastIndexOf("::");
414 if (s > 0) {
415 QByteArray scope = enumKey.left(s);
416 if (scope != "Qt" && !qualifiedNameEquals(cdef->qualified, scope) && !extraList.contains(scope))
417 extraList += scope;
418 }
419 }
420
421//
422// Generate meta object link to parent meta objects
423//
424
425 if (!extraList.isEmpty()) {
426 fprintf(out, "Q_CONSTINIT static const QMetaObject::SuperData qt_meta_extradata_%s[] = {\n",
427 qualifiedClassNameIdentifier.constData());
428 for (const QByteArray &ba : std::as_const(extraList))
429 fprintf(out, " QMetaObject::SuperData::link<%s::staticMetaObject>(),\n", ba.constData());
430
431 fprintf(out, " nullptr\n};\n\n");
432 }
433
434//
435// Finally create and initialize the static meta object
436//
437 fprintf(out, "Q_CONSTINIT const QMetaObject %s::staticMetaObject = { {\n",
438 cdef->qualified.constData());
439
440 if (isQObject)
441 fprintf(out, " nullptr,\n");
442 else if (cdef->superclassList.size() && !cdef->hasQGadget && !cdef->hasQNamespace) // for qobject, we know the super class must have a static metaobject
443 fprintf(out, " QMetaObject::SuperData::link<%s::staticMetaObject>(),\n", purestSuperClass.constData());
444 else if (cdef->superclassList.size()) // for gadgets we need to query at compile time for it
445 fprintf(out, " QtPrivate::MetaObjectForType<%s>::value,\n", purestSuperClass.constData());
446 else
447 fprintf(out, " nullptr,\n");
448 fprintf(out, " qt_meta_stringdata_%s.offsetsAndSizes,\n"
449 " qt_staticMetaObjectStaticContent%s.data(),\n",
450 qualifiedClassNameIdentifier.constData(),
451 metaVarNameSuffix.constData());
452 if (hasStaticMetaCall)
453 fprintf(out, " qt_static_metacall,\n");
454 else
455 fprintf(out, " nullptr,\n");
456
457 if (extraList.isEmpty())
458 fprintf(out, " nullptr,\n");
459 else
460 fprintf(out, " qt_meta_extradata_%s,\n", qualifiedClassNameIdentifier.constData());
461
462 fprintf(out, " qt_staticMetaObjectRelocatingContent%s.data(),\n",
463 metaVarNameSuffix.constData());
464
465 fprintf(out, " nullptr\n} };\n\n");
466
467//
468// Generate internal qt_static_metacall() function
469//
470 if (hasStaticMetaCall)
471 generateStaticMetacall();
472
473 if (!cdef->hasQObject)
474 return;
475
476 fprintf(out, "\nconst QMetaObject *%s::metaObject() const\n{\n"
477 " return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;\n"
478 "}\n",
479 cdef->qualified.constData());
480
481//
482// Generate smart cast function
483//
484 fprintf(out, "\nvoid *%s::qt_metacast(const char *_clname)\n{\n", cdef->qualified.constData());
485 fprintf(out, " if (!_clname) return nullptr;\n");
486 fprintf(out, " if (!strcmp(_clname, qt_meta_stringdata_%s.stringdata0))\n"
487 " return static_cast<void*>(this);\n",
488 qualifiedClassNameIdentifier.constData());
489
490 // for all superclasses but the first one
491 if (cdef->superclassList.size() > 1) {
492 auto it = cdef->superclassList.cbegin() + 1;
493 const auto end = cdef->superclassList.cend();
494 for (; it != end; ++it) {
495 if (it->access == FunctionDef::Private)
496 continue;
497 const char *cname = it->classname.constData();
498 fprintf(out, " if (!strcmp(_clname, \"%s\"))\n return static_cast< %s*>(this);\n",
499 cname, cname);
500 }
501 }
502
503 for (const QList<ClassDef::Interface> &iface : std::as_const(cdef->interfaceList)) {
504 for (qsizetype j = 0; j < iface.size(); ++j) {
505 fprintf(out, " if (!strcmp(_clname, %s))\n return ", iface.at(j).interfaceId.constData());
506 for (qsizetype k = j; k >= 0; --k)
507 fprintf(out, "static_cast< %s*>(", iface.at(k).className.constData());
508 fprintf(out, "this%s;\n", QByteArray(j + 1, ')').constData());
509 }
510 }
511 if (!purestSuperClass.isEmpty() && !isQObject) {
512 QByteArray superClass = purestSuperClass;
513 fprintf(out, " return %s::qt_metacast(_clname);\n", superClass.constData());
514 } else {
515 fprintf(out, " return nullptr;\n");
516 }
517 fprintf(out, "}\n");
518
519 if (parser->activeQtMode)
520 return;
521
522//
523// Generate internal qt_metacall() function
524//
525 generateMetacall();
526
527//
528// Generate internal signal functions
529//
530 for (int signalindex = 0; signalindex < int(cdef->signalList.size()); ++signalindex)
531 generateSignal(&cdef->signalList.at(signalindex), signalindex);
532
533//
534// Generate plugin meta data
535//
536 generatePluginMetaData();
537
538//
539// Generate function to make sure the non-class signals exist in the parent classes
540//
541 if (!cdef->nonClassSignalList.isEmpty()) {
542 fprintf(out, "namespace CheckNotifySignalValidity_%s {\n", qualifiedClassNameIdentifier.constData());
543 for (const QByteArray &nonClassSignal : std::as_const(cdef->nonClassSignalList)) {
544 const auto propertyIt = std::find_if(cdef->propertyList.constBegin(),
545 cdef->propertyList.constEnd(),
546 [&nonClassSignal](const PropertyDef &p) {
547 return nonClassSignal == p.notify;
548 });
549 // must find something, otherwise checkProperties wouldn't have inserted an entry into nonClassSignalList
550 Q_ASSERT(propertyIt != cdef->propertyList.constEnd());
551 fprintf(out, "template<typename T> using has_nullary_%s = decltype(std::declval<T>().%s());\n",
552 nonClassSignal.constData(),
553 nonClassSignal.constData());
554 const auto &propertyType = propertyIt->type;
555 fprintf(out, "template<typename T> using has_unary_%s = decltype(std::declval<T>().%s(std::declval<%s>()));\n",
556 nonClassSignal.constData(),
557 nonClassSignal.constData(),
558 propertyType.constData());
559 fprintf(out, "static_assert(qxp::is_detected_v<has_nullary_%s, %s> || qxp::is_detected_v<has_unary_%s, %s>,\n"
560 " \"NOTIFY signal %s does not exist in class (or is private in its parent)\");\n",
561 nonClassSignal.constData(), cdef->qualified.constData(),
562 nonClassSignal.constData(), cdef->qualified.constData(),
563 nonClassSignal.constData());
564 }
565 fprintf(out, "}\n");
566 }
567}
568
569
570void Generator::registerClassInfoStrings()
571{
572 for (const ClassInfoDef &c : std::as_const(cdef->classInfoList)) {
573 strreg(c.name);
574 strreg(c.value);
575 }
576}
577
578void Generator::addClassInfos()
579{
580 for (const ClassInfoDef &c : std::as_const(cdef->classInfoList))
581 fprintf(out, " { %4d, %4d },\n", stridx(c.name), stridx(c.value));
582}
583
584void Generator::registerFunctionStrings(const QList<FunctionDef> &list)
585{
586 for (const FunctionDef &f : list) {
587 strreg(f.name);
588 if (!isBuiltinType(f.normalizedType))
589 strreg(f.normalizedType);
590 strreg(f.tag);
591
592 for (const ArgumentDef &a : f.arguments) {
593 if (!isBuiltinType(a.normalizedType))
594 strreg(a.normalizedType);
595 strreg(a.name);
596 }
597 }
598}
599
600void Generator::registerByteArrayVector(const QList<QByteArray> &list)
601{
602 for (const QByteArray &ba : list)
603 strreg(ba);
604}
605
606void Generator::addFunctions(const QList<FunctionDef> &list, const char *functype)
607{
608 for (const FunctionDef &f : list) {
609 if (!f.isConstructor)
610 fprintf(out, " // %s '%s'\n", functype, f.name.constData());
611 fprintf(out, " QtMocHelpers::%s%sData<",
612 f.revision > 0 ? "Revisioned" : "", functype);
613
614 if (f.isConstructor)
615 fprintf(out, "Constructor(");
616 else
617 fprintf(out, "%s(", f.type.name.constData()); // return type
618
619 const char *comma = "";
620 for (const auto &argument : f.arguments) {
621 fprintf(out, "%s%s", comma, argument.type.name.constData());
622 comma = ", ";
623 }
624
625 if (f.isConstructor)
626 fprintf(out, ")>(%d, ", stridx(f.tag));
627 else
628 fprintf(out, ")%s>(%d, %d, ", f.isConst ? " const" : "", stridx(f.name), stridx(f.tag));
629
630 // flags
631 // access right is always present
632 if (f.access == FunctionDef::Private)
633 fprintf(out, "QMC::AccessPrivate");
634 else if (f.access == FunctionDef::Public)
635 fprintf(out, "QMC::AccessPublic");
636 else if (f.access == FunctionDef::Protected)
637 fprintf(out, "QMC::AccessProtected");
638 if (f.isCompat)
639 fprintf(out, " | QMC::MethodCompatibility");
640 if (f.wasCloned)
641 fprintf(out, " | QMC::MethodCloned");
642 if (f.isScriptable)
643 fprintf(out, " | QMC::MethodScriptable");
644
645 // QtMocConstants::MethodRevisioned is implied by the call we're making
646 if (f.revision > 0)
647 fprintf(out, ", %#x", f.revision);
648
649 // return type (if not a constructor)
650 if (!f.isConstructor) {
651 fprintf(out, ", ");
652 generateTypeInfo(f.normalizedType);
653 }
654
655 if (f.arguments.isEmpty()) {
656 fprintf(out, "),\n");
657 } else {
658 // array of parameter types (or type names) and names
659 fprintf(out, ", {{");
660 for (qsizetype i = 0; i < f.arguments.size(); ++i) {
661 if ((i % 4) == 0)
662 fprintf(out, "\n ");
663 const ArgumentDef &arg = f.arguments.at(i);
664 fprintf(out, " { ");
665 generateTypeInfo(arg.normalizedType);
666 fprintf(out, ", %d },", stridx(arg.name));
667 }
668
669 fprintf(out, "\n }}),\n");
670 }
671 }
672}
673
674
675void Generator::generateTypeInfo(const QByteArray &typeName, bool allowEmptyName)
676{
677 Q_UNUSED(allowEmptyName);
678 if (isBuiltinType(typeName)) {
679 int type;
680 const char *valueString;
681 if (typeName == "qreal") {
682 type = QMetaType::UnknownType;
683 valueString = "QReal";
684 } else {
685 type = nameToBuiltinType(typeName);
686 valueString = metaTypeEnumValueString(type);
687 }
688 if (valueString) {
689 fprintf(out, "QMetaType::%s", valueString);
690 } else {
691 Q_ASSERT(type != QMetaType::UnknownType);
692 fprintf(out, "%4d", type);
693 }
694 } else {
695 Q_ASSERT(!typeName.isEmpty() || allowEmptyName);
696 fprintf(out, "0x%.8x | %d", IsUnresolvedType, stridx(typeName));
697 }
698}
699
700void Generator::registerPropertyStrings()
701{
702 for (const PropertyDef &p : std::as_const(cdef->propertyList)) {
703 strreg(p.name);
704 if (!isBuiltinType(p.type))
705 strreg(p.type);
706 }
707}
708
709void Generator::addProperties()
710{
711 for (const PropertyDef &p : std::as_const(cdef->propertyList)) {
712 fprintf(out, " // property '%s'\n"
713 " QtMocHelpers::PropertyData<%s>(%d, ",
714 p.name.constData(), p.type.constData(), stridx(p.name));
715 generateTypeInfo(p.type);
716 fputc(',', out);
717
718 const char *separator = "";
719 auto addFlag = [this, &separator](const char *text) {
720 fprintf(out, "%s QMC::%s", separator, text);
721 separator = " |";
722 };
723 bool readable = !p.read.isEmpty() || !p.member.isEmpty();
724 bool designable = p.designable != "false";
725 bool scriptable = p.scriptable != "false";
726 bool stored = p.stored != "false";
727 if (readable && designable && scriptable && stored) {
728 addFlag("DefaultPropertyFlags");
729 if ((!p.member.isEmpty() && !p.constant) || !p.write.isEmpty())
730 addFlag("Writable");
731 } else {
732 if (readable)
733 addFlag("Readable");
734 if ((!p.member.isEmpty() && !p.constant) || !p.write.isEmpty())
735 addFlag("Writable");
736 if (designable)
737 addFlag("Designable");
738 if (scriptable)
739 addFlag("Scriptable");
740 if (stored)
741 addFlag("Stored");
742 }
743 if (!p.reset.isEmpty())
744 addFlag("Resettable");
745 if (!isBuiltinType(p.type))
746 addFlag("EnumOrFlag");
747 if (p.stdCppSet())
748 addFlag("StdCppSet");
749 if (p.constant)
750 addFlag("Constant");
751 if (p.final)
752 addFlag("Final");
753 if (p.user != "false")
754 addFlag("User");
755 if (p.required)
756 addFlag("Required");
757 if (!p.bind.isEmpty())
758 addFlag("Bindable");
759
760 if (*separator == '\0')
761 addFlag("Invalid");
762
763 int notifyId = p.notifyId;
764 if (notifyId != -1 || p.revision > 0) {
765 fprintf(out, ", ");
766 if (p.notifyId < -1) {
767 // signal is in parent class
768 const int indexInStrings = int(strings.indexOf(p.notify));
769 notifyId = indexInStrings;
770 fprintf(out, "%#x | ", IsUnresolvedSignal);
771 }
772 fprintf(out, "%d", notifyId);
773 if (p.revision > 0)
774 fprintf(out, ", %#x", p.revision);
775 }
776
777 fprintf(out, "),\n");
778 }
779}
780
781void Generator::registerEnumStrings()
782{
783 for (const EnumDef &e : std::as_const(cdef->enumList)) {
784 strreg(e.name);
785 if (!e.enumName.isNull())
786 strreg(e.enumName);
787 for (const QByteArray &val : e.values)
788 strreg(val);
789 }
790}
791
792void Generator::addEnums()
793{
794 for (const EnumDef &e : std::as_const(cdef->enumList)) {
795 const QByteArray &typeName = e.enumName.isNull() ? e.name : e.enumName;
796 fprintf(out, " // %s '%s'\n"
797 " QtMocHelpers::EnumData<%s>(%d, %d,",
798 e.flags & EnumIsFlag ? "flag" : "enum", e.name.constData(),
799 e.name.constData(), stridx(e.name), stridx(typeName));
800
801 if (e.flags) {
802 const char *separator = "";
803 auto addFlag = [this, &separator](const char *text) {
804 fprintf(out, "%s QMC::%s", separator, text);
805 separator = " |";
806 };
807 if (e.flags & EnumIsFlag)
808 addFlag("EnumIsFlag");
809 if (e.flags & EnumIsScoped)
810 addFlag("EnumIsScoped");
811 } else {
812 fprintf(out, " QMC::EnumFlags{}");
813 }
814
815 if (e.values.isEmpty()) {
816 fprintf(out, "),\n");
817 continue;
818 }
819
820 // add the enumerations
821 fprintf(out, ").add({\n");
822 QByteArray prefix = (e.enumName.isNull() ? e.name : e.enumName);
823 for (const QByteArray &val : e.values) {
824 fprintf(out, " { %4d, %s::%s },\n", stridx(val),
825 prefix.constData(), val.constData());
826 }
827
828 fprintf(out, " }),\n");
829 }
830}
831
832void Generator::generateMetacall()
833{
834 bool isQObject = (cdef->classname == "QObject");
835
836 fprintf(out, "\nint %s::qt_metacall(QMetaObject::Call _c, int _id, void **_a)\n{\n",
837 cdef->qualified.constData());
838
839 if (!purestSuperClass.isEmpty() && !isQObject) {
840 QByteArray superClass = purestSuperClass;
841 fprintf(out, " _id = %s::qt_metacall(_c, _id, _a);\n", superClass.constData());
842 }
843
844
845 QList<FunctionDef> methodList;
846 methodList += cdef->signalList;
847 methodList += cdef->slotList;
848 methodList += cdef->methodList;
849
850 // If there are no methods or properties, we will return _id anyway, so
851 // don't emit this comparison -- it is unnecessary, and it makes coverity
852 // unhappy.
853 if (methodList.size() || cdef->propertyList.size()) {
854 fprintf(out, " if (_id < 0)\n return _id;\n");
855 }
856
857 if (methodList.size()) {
858 fprintf(out, " if (_c == QMetaObject::InvokeMetaMethod) {\n");
859 fprintf(out, " if (_id < %d)\n", int(methodList.size()));
860 fprintf(out, " qt_static_metacall(this, _c, _id, _a);\n");
861 fprintf(out, " _id -= %d;\n }\n", int(methodList.size()));
862
863 fprintf(out, " if (_c == QMetaObject::RegisterMethodArgumentMetaType) {\n");
864 fprintf(out, " if (_id < %d)\n", int(methodList.size()));
865
866 if (methodsWithAutomaticTypesHelper(methodList).isEmpty())
867 fprintf(out, " *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType();\n");
868 else
869 fprintf(out, " qt_static_metacall(this, _c, _id, _a);\n");
870 fprintf(out, " _id -= %d;\n }\n", int(methodList.size()));
871
872 }
873
874 if (cdef->propertyList.size()) {
875 fprintf(out,
876 " if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty\n"
877 " || _c == QMetaObject::ResetProperty || _c == QMetaObject::BindableProperty\n"
878 " || _c == QMetaObject::RegisterPropertyMetaType) {\n"
879 " qt_static_metacall(this, _c, _id, _a);\n"
880 " _id -= %d;\n }\n", int(cdef->propertyList.size()));
881 }
882 fprintf(out," return _id;\n}\n");
883}
884
885
886// ### Qt 7 (6.x?): remove
887QMultiMap<QByteArray, int> Generator::automaticPropertyMetaTypesHelper()
888{
889 QMultiMap<QByteArray, int> automaticPropertyMetaTypes;
890 for (int i = 0; i < int(cdef->propertyList.size()); ++i) {
891 const QByteArray propertyType = cdef->propertyList.at(i).type;
892 if (registerableMetaType(propertyType) && !isBuiltinType(propertyType))
893 automaticPropertyMetaTypes.insert(propertyType, i);
894 }
895 return automaticPropertyMetaTypes;
896}
897
898QMap<int, QMultiMap<QByteArray, int>>
899Generator::methodsWithAutomaticTypesHelper(const QList<FunctionDef> &methodList)
900{
901 QMap<int, QMultiMap<QByteArray, int> > methodsWithAutomaticTypes;
902 for (int i = 0; i < methodList.size(); ++i) {
903 const FunctionDef &f = methodList.at(i);
904 for (int j = 0; j < f.arguments.size(); ++j) {
905 const QByteArray argType = f.arguments.at(j).normalizedType;
906 if (registerableMetaType(argType) && !isBuiltinType(argType))
907 methodsWithAutomaticTypes[i].insert(argType, j);
908 }
909 }
910 return methodsWithAutomaticTypes;
911}
912
913void Generator::generateStaticMetacall()
914{
915 fprintf(out, "void %s::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)\n{\n",
916 cdef->qualified.constData());
917
918 enum UsedArgs {
919 UsedT = 1,
920 UsedC = 2,
921 UsedId = 4,
922 UsedA = 8,
923 };
924 uint usedArgs = 0;
925
926 if (cdef->hasQObject) {
927#ifndef QT_NO_DEBUG
928 fprintf(out, " Q_ASSERT(_o == nullptr || staticMetaObject.cast(_o));\n");
929#endif
930 fprintf(out, " auto *_t = static_cast<%s *>(_o);\n", cdef->classname.constData());
931 } else {
932 fprintf(out, " auto *_t = reinterpret_cast<%s *>(_o);\n", cdef->classname.constData());
933 }
934
935 const auto generateCtorArguments = [&](int ctorindex) {
936 const FunctionDef &f = cdef->constructorList.at(ctorindex);
937 Q_ASSERT(!f.isPrivateSignal); // That would be a strange ctor indeed
938 int offset = 1;
939
940 const auto begin = f.arguments.cbegin();
941 const auto end = f.arguments.cend();
942 for (auto it = begin; it != end; ++it) {
943 const ArgumentDef &a = *it;
944 if (it != begin)
945 fprintf(out, ",");
946 fprintf(out, "(*reinterpret_cast<%s>(_a[%d]))",
947 a.typeNameForCast.constData(), offset++);
948 }
949 };
950
951 if (!cdef->constructorList.isEmpty()) {
952 fprintf(out, " if (_c == QMetaObject::CreateInstance) {\n");
953 fprintf(out, " switch (_id) {\n");
954 const int ctorend = int(cdef->constructorList.size());
955 for (int ctorindex = 0; ctorindex < ctorend; ++ctorindex) {
956 fprintf(out, " case %d: { %s *_r = new %s(", ctorindex,
957 cdef->classname.constData(), cdef->classname.constData());
958 generateCtorArguments(ctorindex);
959 fprintf(out, ");\n");
960 fprintf(out, " if (_a[0]) *reinterpret_cast<%s**>(_a[0]) = _r; } break;\n",
961 (cdef->hasQGadget || cdef->hasQNamespace) ? "void" : "QObject");
962 }
963 fprintf(out, " default: break;\n");
964 fprintf(out, " }\n");
965 fprintf(out, " }\n");
966 fprintf(out, " if (_c == QMetaObject::ConstructInPlace) {\n");
967 fprintf(out, " switch (_id) {\n");
968 for (int ctorindex = 0; ctorindex < ctorend; ++ctorindex) {
969 fprintf(out, " case %d: { new (_a[0]) %s(",
970 ctorindex, cdef->classname.constData());
971 generateCtorArguments(ctorindex);
972 fprintf(out, "); } break;\n");
973 }
974 fprintf(out, " default: break;\n");
975 fprintf(out, " }\n");
976 fprintf(out, " }\n");
977 usedArgs |= UsedC | UsedId | UsedA;
978 }
979
980 QList<FunctionDef> methodList;
981 methodList += cdef->signalList;
982 methodList += cdef->slotList;
983 methodList += cdef->methodList;
984
985 if (!methodList.isEmpty()) {
986 usedArgs |= UsedT | UsedC | UsedId;
987 fprintf(out, " if (_c == QMetaObject::InvokeMetaMethod) {\n");
988 fprintf(out, " switch (_id) {\n");
989 for (int methodindex = 0; methodindex < methodList.size(); ++methodindex) {
990 const FunctionDef &f = methodList.at(methodindex);
991 Q_ASSERT(!f.normalizedType.isEmpty());
992 fprintf(out, " case %d: ", methodindex);
993 if (f.normalizedType != "void")
994 fprintf(out, "{ %s _r = ", noRef(f.normalizedType).constData());
995 fprintf(out, "_t->");
996 if (f.inPrivateClass.size())
997 fprintf(out, "%s->", f.inPrivateClass.constData());
998 fprintf(out, "%s(", f.name.constData());
999 int offset = 1;
1000
1001 if (f.isRawSlot) {
1002 fprintf(out, "QMethodRawArguments{ _a }");
1003 usedArgs |= UsedA;
1004 } else {
1005 const auto begin = f.arguments.cbegin();
1006 const auto end = f.arguments.cend();
1007 for (auto it = begin; it != end; ++it) {
1008 const ArgumentDef &a = *it;
1009 if (it != begin)
1010 fprintf(out, ",");
1011 fprintf(out, "(*reinterpret_cast< %s>(_a[%d]))",a.typeNameForCast.constData(), offset++);
1012 usedArgs |= UsedA;
1013 }
1014 if (f.isPrivateSignal) {
1015 if (!f.arguments.isEmpty())
1016 fprintf(out, ", ");
1017 fprintf(out, "%s", "QPrivateSignal()");
1018 }
1019 }
1020 fprintf(out, ");");
1021 if (f.normalizedType != "void") {
1022 fprintf(out, "\n if (_a[0]) *reinterpret_cast< %s*>(_a[0]) = std::move(_r); } ",
1023 noRef(f.normalizedType).constData());
1024 usedArgs |= UsedA;
1025 }
1026 fprintf(out, " break;\n");
1027 }
1028 fprintf(out, " default: ;\n");
1029 fprintf(out, " }\n");
1030 fprintf(out, " }\n");
1031
1032 QMap<int, QMultiMap<QByteArray, int> > methodsWithAutomaticTypes = methodsWithAutomaticTypesHelper(methodList);
1033
1034 if (!methodsWithAutomaticTypes.isEmpty()) {
1035 fprintf(out, " if (_c == QMetaObject::RegisterMethodArgumentMetaType) {\n");
1036 fprintf(out, " switch (_id) {\n");
1037 fprintf(out, " default: *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType(); break;\n");
1038 QMap<int, QMultiMap<QByteArray, int> >::const_iterator it = methodsWithAutomaticTypes.constBegin();
1039 const QMap<int, QMultiMap<QByteArray, int> >::const_iterator end = methodsWithAutomaticTypes.constEnd();
1040 for ( ; it != end; ++it) {
1041 fprintf(out, " case %d:\n", it.key());
1042 fprintf(out, " switch (*reinterpret_cast<int*>(_a[1])) {\n");
1043 fprintf(out, " default: *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType(); break;\n");
1044 auto jt = it->begin();
1045 const auto jend = it->end();
1046 while (jt != jend) {
1047 fprintf(out, " case %d:\n", jt.value());
1048 const QByteArray &lastKey = jt.key();
1049 ++jt;
1050 if (jt == jend || jt.key() != lastKey)
1051 fprintf(out, " *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType::fromType< %s >(); break;\n", lastKey.constData());
1052 }
1053 fprintf(out, " }\n");
1054 fprintf(out, " break;\n");
1055 }
1056 fprintf(out, " }\n");
1057 fprintf(out, " }\n");
1058 usedArgs |= UsedC | UsedId | UsedA;
1059 }
1060
1061 }
1062 if (!cdef->signalList.isEmpty()) {
1063 usedArgs |= UsedC | UsedA;
1064 fprintf(out, " if (_c == QMetaObject::IndexOfMethod) {\n");
1065 for (int methodindex = 0; methodindex < int(cdef->signalList.size()); ++methodindex) {
1066 const FunctionDef &f = cdef->signalList.at(methodindex);
1067 if (f.wasCloned || !f.inPrivateClass.isEmpty() || f.isStatic)
1068 continue;
1069 fprintf(out, " if (QtMocHelpers::indexOfMethod<%s (%s::*)(",
1070 f.type.rawName.constData() , cdef->classname.constData());
1071
1072 const auto begin = f.arguments.cbegin();
1073 const auto end = f.arguments.cend();
1074 for (auto it = begin; it != end; ++it) {
1075 const ArgumentDef &a = *it;
1076 if (it != begin)
1077 fprintf(out, ", ");
1078 fprintf(out, "%s", QByteArray(a.type.name + ' ' + a.rightType).constData());
1079 }
1080 if (f.isPrivateSignal) {
1081 if (!f.arguments.isEmpty())
1082 fprintf(out, ", ");
1083 fprintf(out, "%s", "QPrivateSignal");
1084 }
1085 fprintf(out, ")%s>(_a, &%s::%s, %d))\n",
1086 f.isConst ? " const" : "",
1087 cdef->classname.constData(), f.name.constData(), methodindex);
1088 fprintf(out, " return;\n");
1089 }
1090 fprintf(out, " }\n");
1091 }
1092
1093 const QMultiMap<QByteArray, int> automaticPropertyMetaTypes = automaticPropertyMetaTypesHelper();
1094
1095 if (!automaticPropertyMetaTypes.isEmpty()) {
1096 fprintf(out, " if (_c == QMetaObject::RegisterPropertyMetaType) {\n");
1097 fprintf(out, " switch (_id) {\n");
1098 fprintf(out, " default: *reinterpret_cast<int*>(_a[0]) = -1; break;\n");
1099 auto it = automaticPropertyMetaTypes.begin();
1100 const auto end = automaticPropertyMetaTypes.end();
1101 while (it != end) {
1102 fprintf(out, " case %d:\n", it.value());
1103 const QByteArray &lastKey = it.key();
1104 ++it;
1105 if (it == end || it.key() != lastKey)
1106 fprintf(out, " *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< %s >(); break;\n", lastKey.constData());
1107 }
1108 fprintf(out, " }\n");
1109 fprintf(out, " }\n");
1110 usedArgs |= UsedC | UsedId | UsedA;
1111 }
1112
1113 if (!cdef->propertyList.empty()) {
1114 bool needGet = false;
1115 bool needTempVarForGet = false;
1116 bool needSet = false;
1117 bool needReset = false;
1118 bool hasBindableProperties = false;
1119 for (const PropertyDef &p : std::as_const(cdef->propertyList)) {
1120 needGet |= !p.read.isEmpty() || !p.member.isEmpty();
1121 if (!p.read.isEmpty() || !p.member.isEmpty())
1122 needTempVarForGet |= (p.gspec != PropertyDef::PointerSpec
1123 && p.gspec != PropertyDef::ReferenceSpec);
1124
1125 needSet |= !p.write.isEmpty() || (!p.member.isEmpty() && !p.constant);
1126 needReset |= !p.reset.isEmpty();
1127 hasBindableProperties |= !p.bind.isEmpty();
1128 }
1129 if (needGet || needSet || hasBindableProperties || needReset)
1130 usedArgs |= UsedT | UsedC | UsedId;
1131 if (needGet || needSet || hasBindableProperties)
1132 usedArgs |= UsedA; // resetting doesn't need arguments
1133
1134 if (needGet) {
1135 fprintf(out, " if (_c == QMetaObject::ReadProperty) {\n");
1136 if (needTempVarForGet)
1137 fprintf(out, " void *_v = _a[0];\n");
1138 fprintf(out, " switch (_id) {\n");
1139 for (int propindex = 0; propindex < int(cdef->propertyList.size()); ++propindex) {
1140 const PropertyDef &p = cdef->propertyList.at(propindex);
1141 if (p.read.isEmpty() && p.member.isEmpty())
1142 continue;
1143 QByteArray prefix = "_t->";
1144 if (p.inPrivateClass.size()) {
1145 prefix += p.inPrivateClass + "->";
1146 }
1147
1149 fprintf(out, " case %d: _a[0] = const_cast<void*>(reinterpret_cast<const void*>(%s%s())); break;\n",
1150 propindex, prefix.constData(), p.read.constData());
1152 fprintf(out, " case %d: _a[0] = const_cast<void*>(reinterpret_cast<const void*>(&%s%s())); break;\n",
1153 propindex, prefix.constData(), p.read.constData());
1154#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0)
1155 else if (auto eflags = cdef->enumDeclarations.value(p.type); eflags & EnumIsFlag)
1156 fprintf(out, " case %d: QtMocHelpers::assignFlags<%s>(_v, %s%s()); break;\n",
1157 propindex, p.type.constData(), prefix.constData(), p.read.constData());
1158#endif
1159 else if (p.read == "default")
1160 fprintf(out, " case %d: *reinterpret_cast< %s*>(_v) = %s%s().value(); break;\n",
1161 propindex, p.type.constData(), prefix.constData(), p.bind.constData());
1162 else if (!p.read.isEmpty())
1163 fprintf(out, " case %d: *reinterpret_cast< %s*>(_v) = %s%s(); break;\n",
1164 propindex, p.type.constData(), prefix.constData(), p.read.constData());
1165 else
1166 fprintf(out, " case %d: *reinterpret_cast< %s*>(_v) = %s%s; break;\n",
1167 propindex, p.type.constData(), prefix.constData(), p.member.constData());
1168 }
1169 fprintf(out, " default: break;\n");
1170 fprintf(out, " }\n");
1171 fprintf(out, " }\n");
1172 }
1173
1174 if (needSet) {
1175 fprintf(out, " if (_c == QMetaObject::WriteProperty) {\n");
1176 fprintf(out, " void *_v = _a[0];\n");
1177 fprintf(out, " switch (_id) {\n");
1178 for (int propindex = 0; propindex < int(cdef->propertyList.size()); ++propindex) {
1179 const PropertyDef &p = cdef->propertyList.at(propindex);
1180 if (p.constant)
1181 continue;
1182 if (p.write.isEmpty() && p.member.isEmpty())
1183 continue;
1184 QByteArray prefix = "_t->";
1185 if (p.inPrivateClass.size()) {
1186 prefix += p.inPrivateClass + "->";
1187 }
1188 if (p.write == "default") {
1189 fprintf(out, " case %d: {\n", propindex);
1190 fprintf(out, " %s%s().setValue(*reinterpret_cast< %s*>(_v));\n",
1191 prefix.constData(), p.bind.constData(), p.type.constData());
1192 fprintf(out, " break;\n");
1193 fprintf(out, " }\n");
1194 } else if (!p.write.isEmpty()) {
1195 fprintf(out, " case %d: %s%s(*reinterpret_cast< %s*>(_v)); break;\n",
1196 propindex, prefix.constData(), p.write.constData(), p.type.constData());
1197 } else {
1198 fprintf(out, " case %d:\n", propindex);
1199 fprintf(out, " if (%s%s != *reinterpret_cast< %s*>(_v)) {\n",
1200 prefix.constData(), p.member.constData(), p.type.constData());
1201 fprintf(out, " %s%s = *reinterpret_cast< %s*>(_v);\n",
1202 prefix.constData(), p.member.constData(), p.type.constData());
1203 if (!p.notify.isEmpty() && p.notifyId > -1) {
1204 const FunctionDef &f = cdef->signalList.at(p.notifyId);
1205 if (f.arguments.size() == 0)
1206 fprintf(out, " Q_EMIT _t->%s();\n", p.notify.constData());
1207 else if (f.arguments.size() == 1 && f.arguments.at(0).normalizedType == p.type)
1208 fprintf(out, " Q_EMIT _t->%s(%s%s);\n",
1209 p.notify.constData(), prefix.constData(), p.member.constData());
1210 } else if (!p.notify.isEmpty() && p.notifyId < -1) {
1211 fprintf(out, " Q_EMIT _t->%s();\n", p.notify.constData());
1212 }
1213 fprintf(out, " }\n");
1214 fprintf(out, " break;\n");
1215 }
1216 }
1217 fprintf(out, " default: break;\n");
1218 fprintf(out, " }\n");
1219 fprintf(out, " }\n");
1220 }
1221
1222 if (needReset) {
1223 fprintf(out, "if (_c == QMetaObject::ResetProperty) {\n");
1224 fprintf(out, " switch (_id) {\n");
1225 for (int propindex = 0; propindex < int(cdef->propertyList.size()); ++propindex) {
1226 const PropertyDef &p = cdef->propertyList.at(propindex);
1227 if (p.reset.isEmpty())
1228 continue;
1229 QByteArray prefix = "_t->";
1230 if (p.inPrivateClass.size()) {
1231 prefix += p.inPrivateClass + "->";
1232 }
1233 fprintf(out, " case %d: %s%s(); break;\n",
1234 propindex, prefix.constData(), p.reset.constData());
1235 }
1236 fprintf(out, " default: break;\n");
1237 fprintf(out, " }\n");
1238 fprintf(out, " }\n");
1239 }
1240
1241 if (hasBindableProperties) {
1242 fprintf(out, " if (_c == QMetaObject::BindableProperty) {\n");
1243 fprintf(out, " switch (_id) {\n");
1244 for (int propindex = 0; propindex < int(cdef->propertyList.size()); ++propindex) {
1245 const PropertyDef &p = cdef->propertyList.at(propindex);
1246 if (p.bind.isEmpty())
1247 continue;
1248 QByteArray prefix = "_t->";
1249 if (p.inPrivateClass.size()) {
1250 prefix += p.inPrivateClass + "->";
1251 }
1252 fprintf(out,
1253 " case %d: *static_cast<QUntypedBindable *>(_a[0]) = %s%s(); "
1254 "break;\n",
1255 propindex, prefix.constData(), p.bind.constData());
1256 }
1257 fprintf(out, " default: break;\n");
1258 fprintf(out, " }\n");
1259 fprintf(out, " }\n");
1260 }
1261 }
1262
1263 auto printUnused = [&](UsedArgs entry, const char *name) {
1264 if ((usedArgs & entry) == 0)
1265 fprintf(out, " (void)%s;\n", name);
1266 };
1267 printUnused(UsedT, "_t");
1268 printUnused(UsedC, "_c");
1269 printUnused(UsedId, "_id");
1270 printUnused(UsedA, "_a");
1271
1272 fprintf(out, "}\n");
1273}
1274
1275void Generator::generateSignal(const FunctionDef *def, int index)
1276{
1277 if (def->wasCloned || def->isAbstract)
1278 return;
1279 fprintf(out, "\n// SIGNAL %d\n%s %s::%s(",
1280 index, def->type.name.constData(), cdef->qualified.constData(), def->name.constData());
1281
1282 QByteArray thisPtr = "this";
1283 const char *constQualifier = "";
1284
1285 if (def->isConst) {
1286 thisPtr = "const_cast< " + cdef->qualified + " *>(this)";
1287 constQualifier = "const";
1288 }
1289
1290 Q_ASSERT(!def->normalizedType.isEmpty());
1291 if (def->arguments.isEmpty() && def->normalizedType == "void" && !def->isPrivateSignal) {
1292 fprintf(out, ")%s\n{\n"
1293 " QMetaObject::activate(%s, &staticMetaObject, %d, nullptr);\n"
1294 "}\n", constQualifier, thisPtr.constData(), index);
1295 return;
1296 }
1297
1298 int offset = 1;
1299 const auto begin = def->arguments.cbegin();
1300 const auto end = def->arguments.cend();
1301 for (auto it = begin; it != end; ++it) {
1302 const ArgumentDef &a = *it;
1303 if (it != begin)
1304 fputs(", ", out);
1305 if (a.type.name.size())
1306 fputs(a.type.name.constData(), out);
1307 fprintf(out, " _t%d", offset++);
1308 if (a.rightType.size())
1309 fputs(a.rightType.constData(), out);
1310 }
1311 if (def->isPrivateSignal) {
1312 if (!def->arguments.isEmpty())
1313 fprintf(out, ", ");
1314 fprintf(out, "QPrivateSignal _t%d", offset++);
1315 }
1316
1317 fprintf(out, ")%s\n{\n", constQualifier);
1318 if (def->type.name.size() && def->normalizedType != "void") {
1319 QByteArray returnType = noRef(def->normalizedType);
1320 fprintf(out, " %s _t0{};\n", returnType.constData());
1321 }
1322
1323 fprintf(out, " QMetaObject::activate<%s>(%s, &staticMetaObject, %d, ",
1324 def->normalizedType.constData(), thisPtr.constData(), index);
1325 if (def->normalizedType == "void") {
1326 fprintf(out, "nullptr");
1327 } else {
1328 fprintf(out, "std::addressof(_t0)");
1329 }
1330 int i;
1331 for (i = 1; i < offset; ++i)
1332 fprintf(out, ", _t%d", i);
1333 fprintf(out, ");\n");
1334
1335 if (def->normalizedType != "void")
1336 fprintf(out, " return _t0;\n");
1337 fprintf(out, "}\n");
1338}
1339
1340static CborError jsonValueToCbor(CborEncoder *parent, const QJsonValue &v);
1341static CborError jsonObjectToCbor(CborEncoder *parent, const QJsonObject &o)
1342{
1343 auto it = o.constBegin();
1344 auto end = o.constEnd();
1345 CborEncoder map;
1346 cbor_encoder_create_map(parent, &map, o.size());
1347
1348 for ( ; it != end; ++it) {
1349 QByteArray key = it.key().toUtf8();
1350 cbor_encode_text_string(&map, key.constData(), key.size());
1351 jsonValueToCbor(&map, it.value());
1352 }
1353 return cbor_encoder_close_container(parent, &map);
1354}
1355
1356static CborError jsonArrayToCbor(CborEncoder *parent, const QJsonArray &a)
1357{
1358 CborEncoder array;
1359 cbor_encoder_create_array(parent, &array, a.size());
1360 for (const QJsonValue v : a)
1361 jsonValueToCbor(&array, v);
1362 return cbor_encoder_close_container(parent, &array);
1363}
1364
1365static CborError jsonValueToCbor(CborEncoder *parent, const QJsonValue &v)
1366{
1367 switch (v.type()) {
1368 case QJsonValue::Null:
1369 case QJsonValue::Undefined:
1370 return cbor_encode_null(parent);
1371 case QJsonValue::Bool:
1372 return cbor_encode_boolean(parent, v.toBool());
1373 case QJsonValue::Array:
1374 return jsonArrayToCbor(parent, v.toArray());
1375 case QJsonValue::Object:
1376 return jsonObjectToCbor(parent, v.toObject());
1377 case QJsonValue::String: {
1378 QByteArray s = v.toString().toUtf8();
1379 return cbor_encode_text_string(parent, s.constData(), s.size());
1380 }
1381 case QJsonValue::Double: {
1382 double d = v.toDouble();
1383 if (d == floor(d) && fabs(d) <= (Q_INT64_C(1) << std::numeric_limits<double>::digits))
1384 return cbor_encode_int(parent, qint64(d));
1385 return cbor_encode_double(parent, d);
1386 }
1387 }
1388 Q_UNREACHABLE_RETURN(CborUnknownError);
1389}
1390
1391void Generator::generatePluginMetaData()
1392{
1393 if (cdef->pluginData.iid.isEmpty())
1394 return;
1395
1396 auto outputCborData = [this]() {
1397 CborDevice dev(out);
1398 CborEncoder enc;
1399 cbor_encoder_init_writer(&enc, CborDevice::callback, &dev);
1400
1401 CborEncoder map;
1402 cbor_encoder_create_map(&enc, &map, CborIndefiniteLength);
1403
1404 dev.nextItem("\"IID\"");
1405 cbor_encode_int(&map, int(QtPluginMetaDataKeys::IID));
1406 cbor_encode_text_string(&map, cdef->pluginData.iid.constData(), cdef->pluginData.iid.size());
1407
1408 dev.nextItem("\"className\"");
1409 cbor_encode_int(&map, int(QtPluginMetaDataKeys::ClassName));
1410 cbor_encode_text_string(&map, cdef->classname.constData(), cdef->classname.size());
1411
1412 QJsonObject o = cdef->pluginData.metaData.object();
1413 if (!o.isEmpty()) {
1414 dev.nextItem("\"MetaData\"");
1415 cbor_encode_int(&map, int(QtPluginMetaDataKeys::MetaData));
1416 jsonObjectToCbor(&map, o);
1417 }
1418
1419 if (!cdef->pluginData.uri.isEmpty()) {
1420 dev.nextItem("\"URI\"");
1421 cbor_encode_int(&map, int(QtPluginMetaDataKeys::URI));
1422 cbor_encode_text_string(&map, cdef->pluginData.uri.constData(), cdef->pluginData.uri.size());
1423 }
1424
1425 // Add -M args from the command line:
1426 for (auto it = cdef->pluginData.metaArgs.cbegin(), end = cdef->pluginData.metaArgs.cend(); it != end; ++it) {
1427 const QJsonArray &a = it.value();
1428 QByteArray key = it.key().toUtf8();
1429 dev.nextItem(QByteArray("command-line \"" + key + "\"").constData());
1430 cbor_encode_text_string(&map, key.constData(), key.size());
1431 jsonArrayToCbor(&map, a);
1432 }
1433
1434 // Close the CBOR map manually
1435 dev.nextItem();
1436 cbor_encoder_close_container(&enc, &map);
1437 };
1438
1439 // 'Use' all namespaces.
1440 qsizetype pos = cdef->qualified.indexOf("::");
1441 for ( ; pos != -1 ; pos = cdef->qualified.indexOf("::", pos + 2) )
1442 fprintf(out, "using namespace %s;\n", cdef->qualified.left(pos).constData());
1443
1444 fputs("\n#ifdef QT_MOC_EXPORT_PLUGIN_V2", out);
1445
1446 // Qt 6.3+ output
1447 fprintf(out, "\nstatic constexpr unsigned char qt_pluginMetaDataV2_%s[] = {",
1448 cdef->classname.constData());
1449 outputCborData();
1450 fprintf(out, "\n};\nQT_MOC_EXPORT_PLUGIN_V2(%s, %s, qt_pluginMetaDataV2_%s)\n",
1451 cdef->qualified.constData(), cdef->classname.constData(), cdef->classname.constData());
1452
1453 // compatibility with Qt 6.0-6.2
1454 fprintf(out, "#else\nQT_PLUGIN_METADATA_SECTION\n"
1455 "Q_CONSTINIT static constexpr unsigned char qt_pluginMetaData_%s[] = {\n"
1456 " 'Q', 'T', 'M', 'E', 'T', 'A', 'D', 'A', 'T', 'A', ' ', '!',\n"
1457 " // metadata version, Qt version, architectural requirements\n"
1458 " 0, QT_VERSION_MAJOR, QT_VERSION_MINOR, qPluginArchRequirements(),",
1459 cdef->classname.constData());
1460 outputCborData();
1461 fprintf(out, "\n};\nQT_MOC_EXPORT_PLUGIN(%s, %s)\n"
1462 "#endif // QT_MOC_EXPORT_PLUGIN_V2\n",
1463 cdef->qualified.constData(), cdef->classname.constData());
1464
1465 fputs("\n", out);
1466}
1467
1468QT_WARNING_DISABLE_GCC("-Wunused-function")
1469QT_WARNING_DISABLE_CLANG("-Wunused-function")
1470QT_WARNING_DISABLE_CLANG("-Wundefined-internal")
1471QT_WARNING_DISABLE_MSVC(4334) // '<<': result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?)
1472
1473#define CBOR_ENCODER_WRITER_CONTROL 1
1474#define CBOR_ENCODER_WRITE_FUNCTION CborDevice::callback
1475
1476QT_END_NAMESPACE
1477
1478#include "cborencoder.c"
void nextItem(const char *comment=nullptr)
Definition cbordevice.h:22
CborDevice(FILE *out)
Definition cbordevice.h:20
Generator(Moc *moc, ClassDef *classDef, const QList< QByteArray > &metaTypes, const QHash< QByteArray, QByteArray > &knownQObjectClasses, const QHash< QByteArray, QByteArray > &knownGadgets, FILE *outfile=nullptr, bool requireCompleteTypes=false)
Definition generator.cpp:61
void generateCode()
Definition moc.h:209
\inmodule QtCore\reentrant
Definition qjsonobject.h:20
Definition qlist.h:76
static QByteArray generateQualifiedClassNameIdentifier(const QByteArray &identifier)
static CborError jsonValueToCbor(CborEncoder *parent, const QJsonValue &v)
static bool qualifiedNameEquals(const QByteArray &qualifiedName, const QByteArray &name)
uint nameToBuiltinType(const QByteArray &name)
Definition generator.cpp:29
static CborError jsonArrayToCbor(CborEncoder *parent, const QJsonArray &a)
bool isBuiltinType(const QByteArray &type)
Definition generator.cpp:41
static const char * metaTypeEnumValueString(int type)
Definition generator.cpp:49
static void printStringWithIndentation(FILE *out, const QByteArray &s)
static qsizetype lengthOfEscapeSequence(const QByteArray &s, qsizetype i)
Definition generator.cpp:77
static CborError jsonObjectToCbor(CborEncoder *parent, const QJsonObject &o)
bool hasQObject
Definition moc.h:192
bool hasQGadget
Definition moc.h:193
bool requireCompleteMethodTypes
Definition moc.h:195
bool hasQNamespace
Definition moc.h:194
Definition moc.h:43
bool wasCloned
Definition moc.h:83
bool isRawSlot
Definition moc.h:96
bool isConst
Definition moc.h:79
bool isAbstract
Definition moc.h:95
bool isPrivateSignal
Definition moc.h:92
@ Private
Definition moc.h:75
bool isStatic
Definition moc.h:81
int notifyId
Definition moc.h:115
bool constant
Definition moc.h:119
Specification gspec
Definition moc.h:117
@ ReferenceSpec
Definition moc.h:116
@ PointerSpec
Definition moc.h:116