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