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