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"
8#include "outputrevision.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(name: 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),
88 metaTypes(metaTypes),
89 knownQObjectClasses(knownQObjectClasses),
90 knownGadgets(knownGadgets),
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(c: s.at(i)))
107 ++i;
108 } else if (isOctalDigit(c: ch)) {
109 while (i < startPos + 4
110 && i < s.size()
111 && isOctalDigit(c: s.at(i))) {
112 ++i;
113 }
114 } else { // single character escape sequence
115 i = qMin(a: i + 1, b: 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(a: ColumnWidth - 2, b: len - idx);
130 // don't cut escape sequences at the end of a line
131 const qsizetype backSlashPos = s.lastIndexOf(ch: '\\', from: idx + spanLen - 1);
132 if (backSlashPos >= idx) {
133 const qsizetype escapeLen = lengthOfEscapeSequence(s, i: backSlashPos);
134 spanLen = qBound(min: spanLen, val: backSlashPos + escapeLen - idx, max: len - idx);
135 }
136 fprintf(stream: out, format: "\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(t: s))
144 strings.append(t: s);
145}
146
147int Generator::stridx(const QByteArray &s)
148{
149 int i = int(strings.indexOf(t: 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(t: propertyType))
157 return true;
158
159 if (propertyType.endsWith(c: '*')) {
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(n: 1);
165 if (knownQObjectClasses.contains(key: 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(bv: ba) && !propertyType.endsWith(bv: "&"))
178 return knownQObjectClasses.contains(key: propertyType.mid(index: smartPointer.size() + 1, len: 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(bv: ba) && propertyType.endsWith(bv: ">")) {
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(i: propertyType.size() - 2) == ' ' ? 1 : 0 );
194 const QByteArray templateArg = propertyType.sliced(pos: ba.size(), n: argumentSize);
195 return isBuiltinType(type: templateArg) || registerableMetaType(propertyType: 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(bv: "::");
208 if (index == -1)
209 return false;
210 return qualifiedNameEquals(qualifiedName: qualifiedName.mid(index: 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(h: QLatin1StringView(identifier), n: QLatin1Char(':'),
218 flags: Qt::SkipEmptyParts)) {
219 qualifiedClassNameIdentifier += QByteArray::number(scope.size());
220 qualifiedClassNameIdentifier += scope;
221 }
222 qualifiedClassNameIdentifier += 'E';
223 return qualifiedClassNameIdentifier;
224}
225
226void Generator::generateCode()
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(t&: cdef->enumList)) {
235 if (cdef->enumDeclarations.contains(key: def.name)) {
236 enumList += def;
237 }
238 def.enumName = def.name;
239 QByteArray alias = cdef->flagAliases.value(key: def.name);
240 if (cdef->enumDeclarations.contains(key: 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(s: cdef->qualified);
253 registerClassInfoStrings();
254 registerFunctionStrings(list: cdef->signalList);
255 registerFunctionStrings(list: cdef->slotList);
256 registerFunctionStrings(list: cdef->methodList);
257 registerFunctionStrings(list: cdef->constructorList);
258 registerByteArrayVector(list: 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(identifier: 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(stream: out, format: "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(stream: out, format: "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(stream: out, format: " QtMocHelpers::StringRefStorage qt_stringData {");
294 addStrings(strings);
295 fprintf(stream: out, format: "\n };\n\n");
296
297 fprintf(stream: out, format: " QtMocHelpers::UintData qt_methods {\n");
298
299 // Build signals array first, otherwise the signal indices would be wrong
300 addFunctions(list: cdef->signalList, functype: "Signal");
301 addFunctions(list: cdef->slotList, functype: "Slot");
302 addFunctions(list: cdef->methodList, functype: "Method");
303 fprintf(stream: out, format: " };\n"
304 " QtMocHelpers::UintData qt_properties {\n");
305 addProperties();
306 fprintf(stream: out, format: " };\n"
307 " QtMocHelpers::UintData qt_enums {\n");
308 addEnums();
309 fprintf(stream: out, format: " };\n");
310
311 const char *uintDataParams = "";
312 if (isConstructible || !cdef->classInfoList.isEmpty()) {
313 if (isConstructible) {
314 fprintf(stream: out, format: " using Constructor = QtMocHelpers::NoType;\n"
315 " QtMocHelpers::UintData qt_constructors {\n");
316 addFunctions(list: cdef->constructorList, functype: "Constructor");
317 fprintf(stream: out, format: " };\n");
318 } else {
319 fputs(s: " QtMocHelpers::UintData qt_constructors {};\n", stream: out);
320 }
321
322 uintDataParams = ", qt_constructors";
323 if (!cdef->classInfoList.isEmpty()) {
324 fprintf(stream: out, format: " QtMocHelpers::ClassInfos qt_classinfo({\n");
325 addClassInfos();
326 fprintf(stream: out, format: " });\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(stream: out, format: " 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(stream: out, format: 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(other: knownQObjectClasses);
377
378 for (const PropertyDef &p : std::as_const(t&: cdef->propertyList)) {
379 if (isBuiltinType(type: p.type))
380 continue;
381
382 if (p.type.contains(c: '*') || p.type.contains(c: '<') || p.type.contains(c: '>'))
383 continue;
384
385 const qsizetype s = p.type.lastIndexOf(bv: "::");
386 if (s <= 0)
387 continue;
388
389 QByteArray unqualifiedScope = p.type.left(n: 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(bv: "::");
397 thisScope = thisScope.left(n: s);
398 QByteArray currentScope = thisScope.isEmpty() ? unqualifiedScope : thisScope + "::" + unqualifiedScope;
399 scopeIt = knownExtraMetaObject.constFind(key: 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(qualifiedName: cdef->qualified, name: scope))
410 continue;
411
412 if (!extraList.contains(t: 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(bv: "::");
423 if (s > 0) {
424 QByteArray scope = enumKey.left(n: s);
425 if (scope != "Qt" && !qualifiedNameEquals(qualifiedName: cdef->qualified, name: scope) && !extraList.contains(t: 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(stream: out, format: "Q_CONSTINIT static const QMetaObject::SuperData qt_meta_extradata_%s[] = {\n",
436 qualifiedClassNameIdentifier.constData());
437 for (const QByteArray &ba : std::as_const(t&: extraList))
438 fprintf(stream: out, format: " QMetaObject::SuperData::link<%s::staticMetaObject>(),\n", ba.constData());
439
440 fprintf(stream: out, format: " nullptr\n};\n\n");
441 }
442
443//
444// Finally create and initialize the static meta object
445//
446 fprintf(stream: out, format: "Q_CONSTINIT const QMetaObject %s::staticMetaObject = { {\n",
447 cdef->qualified.constData());
448
449 if (isQObject)
450 fprintf(stream: out, format: " 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(stream: out, format: " 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(stream: out, format: " QtPrivate::MetaObjectForType<%s>::value,\n", purestSuperClass.constData());
455 else
456 fprintf(stream: out, format: " nullptr,\n");
457 fprintf(stream: out, format: " qt_staticMetaObjectStaticContent%s.stringdata,\n"
458 " qt_staticMetaObjectStaticContent%s.data,\n",
459 metaVarNameSuffix.constData(),
460 metaVarNameSuffix.constData());
461 if (hasStaticMetaCall)
462 fprintf(stream: out, format: " qt_static_metacall,\n");
463 else
464 fprintf(stream: out, format: " nullptr,\n");
465
466 if (extraList.isEmpty())
467 fprintf(stream: out, format: " nullptr,\n");
468 else
469 fprintf(stream: out, format: " qt_meta_extradata_%s,\n", qualifiedClassNameIdentifier.constData());
470
471 fprintf(stream: out, format: " qt_staticMetaObjectRelocatingContent%s.metaTypes,\n",
472 metaVarNameSuffix.constData());
473
474 fprintf(stream: out, format: " 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(stream: out, format: "\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(stream: out, format: "\nvoid *%s::qt_metacast(const char *_clname)\n{\n", cdef->qualified.constData());
494 fprintf(stream: out, format: " if (!_clname) return nullptr;\n");
495 fprintf(stream: out, format: " 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(stream: out, format: " 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(t&: cdef->interfaceList)) {
513 for (qsizetype j = 0; j < iface.size(); ++j) {
514 fprintf(stream: out, format: " if (!strcmp(_clname, %s))\n return ", iface.at(i: j).interfaceId.constData());
515 for (qsizetype k = j; k >= 0; --k)
516 fprintf(stream: out, format: "static_cast< %s*>(", iface.at(i: k).className.constData());
517 fprintf(stream: out, format: "this%s;\n", QByteArray(j + 1, ')').constData());
518 }
519 }
520 if (!purestSuperClass.isEmpty() && !isQObject) {
521 QByteArray superClass = purestSuperClass;
522 fprintf(stream: out, format: " return %s::qt_metacast(_clname);\n", superClass.constData());
523 } else {
524 fprintf(stream: out, format: " return nullptr;\n");
525 }
526 fprintf(stream: out, format: "}\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(def: &cdef->signalList.at(i: signalindex), index: 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(stream: out, format: "namespace CheckNotifySignalValidity_%s {\n", qualifiedClassNameIdentifier.constData());
552 for (const QByteArray &nonClassSignal : std::as_const(t&: cdef->nonClassSignalList)) {
553 const auto propertyIt = std::find_if(first: cdef->propertyList.constBegin(),
554 last: cdef->propertyList.constEnd(),
555 pred: [&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(stream: out, format: "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(stream: out, format: "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(stream: out, format: "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(stream: out, format: "}\n");
575 }
576}
577
578
579void Generator::registerClassInfoStrings()
580{
581 for (const ClassInfoDef &c : std::as_const(t&: cdef->classInfoList)) {
582 strreg(s: c.name);
583 strreg(s: c.value);
584 }
585}
586
587void Generator::addClassInfos()
588{
589 for (const ClassInfoDef &c : std::as_const(t&: cdef->classInfoList))
590 fprintf(stream: out, format: " { %4d, %4d },\n", stridx(s: c.name), stridx(s: c.value));
591}
592
593void Generator::registerFunctionStrings(const QList<FunctionDef> &list)
594{
595 for (const FunctionDef &f : list) {
596 strreg(s: f.name);
597 if (!isBuiltinType(type: f.normalizedType))
598 strreg(s: f.normalizedType);
599 strreg(s: f.tag);
600
601 for (const ArgumentDef &a : f.arguments) {
602 if (!isBuiltinType(type: a.normalizedType))
603 strreg(s: a.normalizedType);
604 strreg(s: a.name);
605 }
606 }
607}
608
609void Generator::registerByteArrayVector(const QList<QByteArray> &list)
610{
611 for (const QByteArray &ba : list)
612 strreg(s: 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(c: comma, stream: out);
621 printStringWithIndentation(out, s: 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(stream: out, format: " // %s '%s'\n", functype, f.name.constData());
631 fprintf(stream: out, format: " QtMocHelpers::%s%sData<",
632 f.revision > 0 ? "Revisioned" : "", functype);
633
634 if (f.isConstructor)
635 fprintf(stream: out, format: "Constructor(");
636 else
637 fprintf(stream: out, format: "%s(", disambiguatedTypeName(name: f.type.name).constData()); // return type
638
639 const char *comma = "";
640 for (const auto &argument : f.arguments) {
641 fprintf(stream: out, format: "%s%s", comma, disambiguatedTypeName(name: argument.type.name).constData());
642 comma = ", ";
643 }
644
645 if (f.isConstructor)
646 fprintf(stream: out, format: ")>(%d, ", stridx(s: f.tag));
647 else
648 fprintf(stream: out, format: ")%s>(%d, %d, ", f.isConst ? " const" : "", stridx(s: f.name), stridx(s: f.tag));
649
650 // flags
651 // access right is always present
652 if (f.access == FunctionDef::Private)
653 fprintf(stream: out, format: "QMC::AccessPrivate");
654 else if (f.access == FunctionDef::Public)
655 fprintf(stream: out, format: "QMC::AccessPublic");
656 else if (f.access == FunctionDef::Protected)
657 fprintf(stream: out, format: "QMC::AccessProtected");
658 if (f.isCompat)
659 fprintf(stream: out, format: " | QMC::MethodCompatibility");
660 if (f.wasCloned)
661 fprintf(stream: out, format: " | QMC::MethodCloned");
662 if (f.isScriptable)
663 fprintf(stream: out, format: " | QMC::MethodScriptable");
664
665 // QtMocConstants::MethodRevisioned is implied by the call we're making
666 if (f.revision > 0)
667 fprintf(stream: out, format: ", %#x", f.revision);
668
669 // return type (if not a constructor)
670 if (!f.isConstructor) {
671 fprintf(stream: out, format: ", ");
672 generateTypeInfo(typeName: f.normalizedType);
673 }
674
675 if (f.arguments.isEmpty()) {
676 fprintf(stream: out, format: "),\n");
677 } else {
678 // array of parameter types (or type names) and names
679 fprintf(stream: out, format: ", {{");
680 for (qsizetype i = 0; i < f.arguments.size(); ++i) {
681 if ((i % 4) == 0)
682 fprintf(stream: out, format: "\n ");
683 const ArgumentDef &arg = f.arguments.at(i);
684 fprintf(stream: out, format: " { ");
685 generateTypeInfo(typeName: arg.normalizedType);
686 fprintf(stream: out, format: ", %d },", stridx(s: arg.name));
687 }
688
689 fprintf(stream: out, format: "\n }}),\n");
690 }
691 }
692}
693
694
695void Generator::generateTypeInfo(const QByteArray &typeName, bool allowEmptyName)
696{
697 Q_UNUSED(allowEmptyName);
698 if (isBuiltinType(type: typeName)) {
699 int type;
700 const char *valueString;
701 if (typeName == "qreal") {
702 type = QMetaType::UnknownType;
703 valueString = "QReal";
704 } else {
705 type = nameToBuiltinType(name: typeName);
706 valueString = metaTypeEnumValueString(type);
707 }
708 if (valueString) {
709 fprintf(stream: out, format: "QMetaType::%s", valueString);
710 } else {
711 Q_ASSERT(type != QMetaType::UnknownType);
712 fprintf(stream: out, format: "%4d", type);
713 }
714 } else {
715 Q_ASSERT(!typeName.isEmpty() || allowEmptyName);
716 fprintf(stream: out, format: "0x%.8x | %d", IsUnresolvedType, stridx(s: typeName));
717 }
718}
719
720void Generator::registerPropertyStrings()
721{
722 for (const PropertyDef &p : std::as_const(t&: cdef->propertyList)) {
723 strreg(s: p.name);
724 if (!isBuiltinType(type: p.type))
725 strreg(s: p.type);
726 }
727}
728
729void Generator::addProperties()
730{
731 for (const PropertyDef &p : std::as_const(t&: cdef->propertyList)) {
732 fprintf(stream: out, format: " // property '%s'\n"
733 " QtMocHelpers::PropertyData<%s%s>(%d, ",
734 p.name.constData(), cxxTypeTag(t: p.typeTag),
735 disambiguatedTypeName(name: p.type, tag: p.typeTag).constData(),
736 stridx(s: p.name));
737 generateTypeInfo(typeName: p.type);
738 fputc(c: ',', stream: out);
739
740 const char *separator = "";
741 auto addFlag = [this, &separator](const char *text) {
742 fprintf(stream: out, format: "%s QMC::%s", separator, text);
743 separator = " |";
744 };
745 bool readable = !p.read.isEmpty() || !p.member.isEmpty();
746 bool designable = p.designable != "false";
747 bool scriptable = p.scriptable != "false";
748 bool stored = p.stored != "false";
749 if (readable && designable && scriptable && stored) {
750 addFlag("DefaultPropertyFlags");
751 if ((!p.member.isEmpty() && !p.constant) || !p.write.isEmpty())
752 addFlag("Writable");
753 } else {
754 if (readable)
755 addFlag("Readable");
756 if ((!p.member.isEmpty() && !p.constant) || !p.write.isEmpty())
757 addFlag("Writable");
758 if (designable)
759 addFlag("Designable");
760 if (scriptable)
761 addFlag("Scriptable");
762 if (stored)
763 addFlag("Stored");
764 }
765 if (!p.reset.isEmpty())
766 addFlag("Resettable");
767 if (!isBuiltinType(type: p.type))
768 addFlag("EnumOrFlag");
769 if (p.stdCppSet())
770 addFlag("StdCppSet");
771 if (p.constant)
772 addFlag("Constant");
773 if (p.final)
774 addFlag("Final");
775 if (p.user != "false")
776 addFlag("User");
777 if (p.required)
778 addFlag("Required");
779 if (!p.bind.isEmpty())
780 addFlag("Bindable");
781
782 if (*separator == '\0')
783 addFlag("Invalid");
784
785 int notifyId = p.notifyId;
786 if (notifyId != -1 || p.revision > 0) {
787 fprintf(stream: out, format: ", ");
788 if (p.notifyId < -1) {
789 // signal is in parent class
790 const int indexInStrings = int(strings.indexOf(t: p.notify));
791 notifyId = indexInStrings;
792 fprintf(stream: out, format: "%#x | ", IsUnresolvedSignal);
793 }
794 fprintf(stream: out, format: "%d", notifyId);
795 if (p.revision > 0)
796 fprintf(stream: out, format: ", %#x", p.revision);
797 }
798
799 fprintf(stream: out, format: "),\n");
800 }
801}
802
803void Generator::registerEnumStrings()
804{
805 for (const EnumDef &e : std::as_const(t&: cdef->enumList)) {
806 strreg(s: e.name);
807 if (!e.enumName.isNull())
808 strreg(s: e.enumName);
809 for (const QByteArray &val : e.values)
810 strreg(s: val);
811 }
812}
813
814void Generator::addEnums()
815{
816 for (const EnumDef &e : std::as_const(t&: cdef->enumList)) {
817 const QByteArray &typeName = e.enumName.isNull() ? e.name : e.enumName;
818 fprintf(stream: out, format: " // %s '%s'\n"
819 " QtMocHelpers::EnumData<%s>(%d, %d,",
820 e.flags & EnumIsFlag ? "flag" : "enum", e.name.constData(),
821 disambiguatedTypeName(name: e.name).constData(), stridx(s: e.name), stridx(s: typeName));
822
823 if (e.flags) {
824 const char *separator = "";
825 auto addFlag = [this, &separator](const char *text) {
826 fprintf(stream: out, format: "%s QMC::%s", separator, text);
827 separator = " |";
828 };
829 if (e.flags & EnumIsFlag)
830 addFlag("EnumIsFlag");
831 if (e.flags & EnumIsScoped)
832 addFlag("EnumIsScoped");
833 } else {
834 fprintf(stream: out, format: " QMC::EnumFlags{}");
835 }
836
837 if (e.values.isEmpty()) {
838 fprintf(stream: out, format: "),\n");
839 continue;
840 }
841
842 // add the enumerations
843 fprintf(stream: out, format: ").add({\n");
844 QByteArray prefix = (e.enumName.isNull() ? e.name : e.enumName);
845 for (const QByteArray &val : e.values) {
846 fprintf(stream: out, format: " { %4d, %s::%s },\n", stridx(s: val),
847 prefix.constData(), val.constData());
848 }
849
850 fprintf(stream: out, format: " }),\n");
851 }
852}
853
854void Generator::generateMetacall()
855{
856 bool isQObject = (cdef->classname == "QObject");
857
858 fprintf(stream: out, format: "\nint %s::qt_metacall(QMetaObject::Call _c, int _id, void **_a)\n{\n",
859 cdef->qualified.constData());
860
861 if (!purestSuperClass.isEmpty() && !isQObject) {
862 QByteArray superClass = purestSuperClass;
863 fprintf(stream: out, format: " _id = %s::qt_metacall(_c, _id, _a);\n", superClass.constData());
864 }
865
866
867 QList<FunctionDef> methodList;
868 methodList += cdef->signalList;
869 methodList += cdef->slotList;
870 methodList += cdef->methodList;
871
872 // If there are no methods or properties, we will return _id anyway, so
873 // don't emit this comparison -- it is unnecessary, and it makes coverity
874 // unhappy.
875 if (methodList.size() || cdef->propertyList.size()) {
876 fprintf(stream: out, format: " if (_id < 0)\n return _id;\n");
877 }
878
879 if (methodList.size()) {
880 fprintf(stream: out, format: " if (_c == QMetaObject::InvokeMetaMethod) {\n");
881 fprintf(stream: out, format: " if (_id < %d)\n", int(methodList.size()));
882 fprintf(stream: out, format: " qt_static_metacall(this, _c, _id, _a);\n");
883 fprintf(stream: out, format: " _id -= %d;\n }\n", int(methodList.size()));
884
885 fprintf(stream: out, format: " if (_c == QMetaObject::RegisterMethodArgumentMetaType) {\n");
886 fprintf(stream: out, format: " if (_id < %d)\n", int(methodList.size()));
887
888 if (methodsWithAutomaticTypesHelper(methodList).isEmpty())
889 fprintf(stream: out, format: " *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType();\n");
890 else
891 fprintf(stream: out, format: " qt_static_metacall(this, _c, _id, _a);\n");
892 fprintf(stream: out, format: " _id -= %d;\n }\n", int(methodList.size()));
893
894 }
895
896 if (cdef->propertyList.size()) {
897 fprintf(stream: out,
898 format: " if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty\n"
899 " || _c == QMetaObject::ResetProperty || _c == QMetaObject::BindableProperty\n"
900 " || _c == QMetaObject::RegisterPropertyMetaType) {\n"
901 " qt_static_metacall(this, _c, _id, _a);\n"
902 " _id -= %d;\n }\n", int(cdef->propertyList.size()));
903 }
904 fprintf(stream: out,format: " return _id;\n}\n");
905}
906
907
908// ### Qt 7 (6.x?): remove
909QMultiMap<QByteArray, int> Generator::automaticPropertyMetaTypesHelper()
910{
911 QMultiMap<QByteArray, int> automaticPropertyMetaTypes;
912 for (int i = 0; i < int(cdef->propertyList.size()); ++i) {
913 const PropertyDef &p = cdef->propertyList.at(i);
914 const QByteArray &propertyType = p.type;
915 if (registerableMetaType(propertyType) && !isBuiltinType(type: propertyType))
916 automaticPropertyMetaTypes.insert(key: cxxTypeTag(t: p.typeTag) + propertyType, value: i);
917 }
918 return automaticPropertyMetaTypes;
919}
920
921QMap<int, QMultiMap<QByteArray, int>>
922Generator::methodsWithAutomaticTypesHelper(const QList<FunctionDef> &methodList)
923{
924 QMap<int, QMultiMap<QByteArray, int> > methodsWithAutomaticTypes;
925 for (int i = 0; i < methodList.size(); ++i) {
926 const FunctionDef &f = methodList.at(i);
927 for (int j = 0; j < f.arguments.size(); ++j) {
928 const QByteArray &argType = f.arguments.at(i: j).normalizedType;
929 if (registerableMetaType(propertyType: argType) && !isBuiltinType(type: argType))
930 methodsWithAutomaticTypes[i].insert(key: argType, value: j);
931 }
932 }
933 return methodsWithAutomaticTypes;
934}
935
936void Generator::generateStaticMetacall()
937{
938 fprintf(stream: out, format: "void %s::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)\n{\n",
939 cdef->qualified.constData());
940
941 enum UsedArgs {
942 UsedT = 1,
943 UsedC = 2,
944 UsedId = 4,
945 UsedA = 8,
946 };
947 uint usedArgs = 0;
948
949 if (cdef->hasQObject) {
950#ifndef QT_NO_DEBUG
951 fprintf(stream: out, format: " Q_ASSERT(_o == nullptr || staticMetaObject.cast(_o));\n");
952#endif
953 fprintf(stream: out, format: " auto *_t = static_cast<%s *>(_o);\n", cdef->classname.constData());
954 } else {
955 fprintf(stream: out, format: " auto *_t = reinterpret_cast<%s *>(_o);\n", cdef->classname.constData());
956 }
957
958 const auto generateCtorArguments = [&](int ctorindex) {
959 const FunctionDef &f = cdef->constructorList.at(i: ctorindex);
960 Q_ASSERT(!f.isPrivateSignal); // That would be a strange ctor indeed
961 int offset = 1;
962
963 const auto begin = f.arguments.cbegin();
964 const auto end = f.arguments.cend();
965 for (auto it = begin; it != end; ++it) {
966 const ArgumentDef &a = *it;
967 if (it != begin)
968 fprintf(stream: out, format: ",");
969 fprintf(stream: out, format: "(*reinterpret_cast<%s>(_a[%d]))",
970 disambiguatedTypeNameForCast(name: a.normalizedType).constData(), offset++);
971 }
972 };
973
974 if (!cdef->constructorList.isEmpty()) {
975 fprintf(stream: out, format: " if (_c == QMetaObject::CreateInstance) {\n");
976 fprintf(stream: out, format: " switch (_id) {\n");
977 const int ctorend = int(cdef->constructorList.size());
978 for (int ctorindex = 0; ctorindex < ctorend; ++ctorindex) {
979 fprintf(stream: out, format: " case %d: { %s *_r = new %s(", ctorindex,
980 cdef->classname.constData(), cdef->classname.constData());
981 generateCtorArguments(ctorindex);
982 fprintf(stream: out, format: ");\n");
983 fprintf(stream: out, format: " if (_a[0]) *reinterpret_cast<%s**>(_a[0]) = _r; } break;\n",
984 (cdef->hasQGadget || cdef->hasQNamespace) ? "void" : "QObject");
985 }
986 fprintf(stream: out, format: " default: break;\n");
987 fprintf(stream: out, format: " }\n");
988 fprintf(stream: out, format: " }\n");
989 fprintf(stream: out, format: " if (_c == QMetaObject::ConstructInPlace) {\n");
990 fprintf(stream: out, format: " switch (_id) {\n");
991 for (int ctorindex = 0; ctorindex < ctorend; ++ctorindex) {
992 fprintf(stream: out, format: " case %d: { new (_a[0]) %s(",
993 ctorindex, cdef->classname.constData());
994 generateCtorArguments(ctorindex);
995 fprintf(stream: out, format: "); } break;\n");
996 }
997 fprintf(stream: out, format: " default: break;\n");
998 fprintf(stream: out, format: " }\n");
999 fprintf(stream: out, format: " }\n");
1000 usedArgs |= UsedC | UsedId | UsedA;
1001 }
1002
1003 QList<FunctionDef> methodList;
1004 methodList += cdef->signalList;
1005 methodList += cdef->slotList;
1006 methodList += cdef->methodList;
1007
1008 if (!methodList.isEmpty()) {
1009 usedArgs |= UsedT | UsedC | UsedId;
1010 fprintf(stream: out, format: " if (_c == QMetaObject::InvokeMetaMethod) {\n");
1011 fprintf(stream: out, format: " switch (_id) {\n");
1012 for (int methodindex = 0; methodindex < methodList.size(); ++methodindex) {
1013 const FunctionDef &f = methodList.at(i: methodindex);
1014 Q_ASSERT(!f.normalizedType.isEmpty());
1015 fprintf(stream: out, format: " case %d: ", methodindex);
1016 if (f.normalizedType != "void")
1017 fprintf(stream: out, format: "{ %s _r = ", disambiguatedTypeName(name: noRef(type: f.normalizedType)).constData());
1018 fprintf(stream: out, format: "_t->");
1019 if (f.inPrivateClass.size())
1020 fprintf(stream: out, format: "%s->", f.inPrivateClass.constData());
1021 fprintf(stream: out, format: "%s(", f.name.constData());
1022 int offset = 1;
1023
1024 if (f.isRawSlot) {
1025 fprintf(stream: out, format: "QMethodRawArguments{ _a }");
1026 usedArgs |= UsedA;
1027 } else {
1028 const auto begin = f.arguments.cbegin();
1029 const auto end = f.arguments.cend();
1030 for (auto it = begin; it != end; ++it) {
1031 const ArgumentDef &a = *it;
1032 if (it != begin)
1033 fprintf(stream: out, format: ",");
1034 fprintf(stream: out, format: "(*reinterpret_cast<%s>(_a[%d]))", disambiguatedTypeNameForCast(name: a.normalizedType).constData(), offset++);
1035 usedArgs |= UsedA;
1036 }
1037 if (f.isPrivateSignal) {
1038 if (!f.arguments.isEmpty())
1039 fprintf(stream: out, format: ", ");
1040 fprintf(stream: out, format: "%s", "QPrivateSignal()");
1041 }
1042 }
1043 fprintf(stream: out, format: ");");
1044 if (f.normalizedType != "void") {
1045 fprintf(stream: out, format: "\n if (_a[0]) *reinterpret_cast<%s*>(_a[0]) = std::move(_r); } ",
1046 disambiguatedTypeName(name: noRef(type: f.normalizedType)).constData());
1047 usedArgs |= UsedA;
1048 }
1049 fprintf(stream: out, format: " break;\n");
1050 }
1051 fprintf(stream: out, format: " default: ;\n");
1052 fprintf(stream: out, format: " }\n");
1053 fprintf(stream: out, format: " }\n");
1054
1055 QMap<int, QMultiMap<QByteArray, int> > methodsWithAutomaticTypes = methodsWithAutomaticTypesHelper(methodList);
1056
1057 if (!methodsWithAutomaticTypes.isEmpty()) {
1058 fprintf(stream: out, format: " if (_c == QMetaObject::RegisterMethodArgumentMetaType) {\n");
1059 fprintf(stream: out, format: " switch (_id) {\n");
1060 fprintf(stream: out, format: " default: *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType(); break;\n");
1061 QMap<int, QMultiMap<QByteArray, int> >::const_iterator it = methodsWithAutomaticTypes.constBegin();
1062 const QMap<int, QMultiMap<QByteArray, int> >::const_iterator end = methodsWithAutomaticTypes.constEnd();
1063 for ( ; it != end; ++it) {
1064 fprintf(stream: out, format: " case %d:\n", it.key());
1065 fprintf(stream: out, format: " switch (*reinterpret_cast<int*>(_a[1])) {\n");
1066 fprintf(stream: out, format: " default: *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType(); break;\n");
1067 auto jt = it->begin();
1068 const auto jend = it->end();
1069 while (jt != jend) {
1070 fprintf(stream: out, format: " case %d:\n", jt.value());
1071 const QByteArray &lastKey = jt.key();
1072 ++jt;
1073 if (jt == jend || jt.key() != lastKey)
1074 fprintf(stream: out, format: " *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType::fromType< %s >(); break;\n", lastKey.constData());
1075 }
1076 fprintf(stream: out, format: " }\n");
1077 fprintf(stream: out, format: " break;\n");
1078 }
1079 fprintf(stream: out, format: " }\n");
1080 fprintf(stream: out, format: " }\n");
1081 usedArgs |= UsedC | UsedId | UsedA;
1082 }
1083
1084 }
1085 if (!cdef->signalList.isEmpty()) {
1086 usedArgs |= UsedC | UsedA;
1087 fprintf(stream: out, format: " if (_c == QMetaObject::IndexOfMethod) {\n");
1088 for (int methodindex = 0; methodindex < int(cdef->signalList.size()); ++methodindex) {
1089 const FunctionDef &f = cdef->signalList.at(i: methodindex);
1090 if (f.wasCloned || !f.inPrivateClass.isEmpty() || f.isStatic)
1091 continue;
1092 fprintf(stream: out, format: " if (QtMocHelpers::indexOfMethod<%s (%s::*)(",
1093 f.type.rawName.constData() , cdef->classname.constData());
1094
1095 const auto begin = f.arguments.cbegin();
1096 const auto end = f.arguments.cend();
1097 for (auto it = begin; it != end; ++it) {
1098 const ArgumentDef &a = *it;
1099 if (it != begin)
1100 fprintf(stream: out, format: ", ");
1101 fprintf(stream: out, format: "%s", QByteArray(a.type.name + ' ' + a.rightType).constData());
1102 }
1103 if (f.isPrivateSignal) {
1104 if (!f.arguments.isEmpty())
1105 fprintf(stream: out, format: ", ");
1106 fprintf(stream: out, format: "%s", "QPrivateSignal");
1107 }
1108 fprintf(stream: out, format: ")%s>(_a, &%s::%s, %d))\n",
1109 f.isConst ? " const" : "",
1110 cdef->classname.constData(), f.name.constData(), methodindex);
1111 fprintf(stream: out, format: " return;\n");
1112 }
1113 fprintf(stream: out, format: " }\n");
1114 }
1115
1116 const QMultiMap<QByteArray, int> automaticPropertyMetaTypes = automaticPropertyMetaTypesHelper();
1117
1118 if (!automaticPropertyMetaTypes.isEmpty()) {
1119 fprintf(stream: out, format: " if (_c == QMetaObject::RegisterPropertyMetaType) {\n");
1120 fprintf(stream: out, format: " switch (_id) {\n");
1121 fprintf(stream: out, format: " default: *reinterpret_cast<int*>(_a[0]) = -1; break;\n");
1122 auto it = automaticPropertyMetaTypes.begin();
1123 const auto end = automaticPropertyMetaTypes.end();
1124 while (it != end) {
1125 fprintf(stream: out, format: " case %d:\n", it.value());
1126 const QByteArray &lastKey = it.key();
1127 ++it;
1128 if (it == end || it.key() != lastKey)
1129 fprintf(stream: out, format: " *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< %s >(); break;\n", lastKey.constData());
1130 }
1131 fprintf(stream: out, format: " }\n");
1132 fprintf(stream: out, format: " }\n");
1133 usedArgs |= UsedC | UsedId | UsedA;
1134 }
1135
1136 if (!cdef->propertyList.empty()) {
1137 bool needGet = false;
1138 bool needTempVarForGet = false;
1139 bool needSet = false;
1140 bool needReset = false;
1141 bool hasBindableProperties = false;
1142 for (const PropertyDef &p : std::as_const(t&: cdef->propertyList)) {
1143 needGet |= !p.read.isEmpty() || !p.member.isEmpty();
1144 if (!p.read.isEmpty() || !p.member.isEmpty())
1145 needTempVarForGet |= (p.gspec != PropertyDef::PointerSpec
1146 && p.gspec != PropertyDef::ReferenceSpec);
1147
1148 needSet |= !p.write.isEmpty() || (!p.member.isEmpty() && !p.constant);
1149 needReset |= !p.reset.isEmpty();
1150 hasBindableProperties |= !p.bind.isEmpty();
1151 }
1152 if (needGet || needSet || hasBindableProperties || needReset)
1153 usedArgs |= UsedT | UsedC | UsedId;
1154 if (needGet || needSet || hasBindableProperties)
1155 usedArgs |= UsedA; // resetting doesn't need arguments
1156
1157 if (needGet) {
1158 fprintf(stream: out, format: " if (_c == QMetaObject::ReadProperty) {\n");
1159 if (needTempVarForGet)
1160 fprintf(stream: out, format: " void *_v = _a[0];\n");
1161 fprintf(stream: out, format: " switch (_id) {\n");
1162 for (int propindex = 0; propindex < int(cdef->propertyList.size()); ++propindex) {
1163 const PropertyDef &p = cdef->propertyList.at(i: propindex);
1164 if (p.read.isEmpty() && p.member.isEmpty())
1165 continue;
1166 QByteArray prefix = "_t->";
1167 if (p.inPrivateClass.size()) {
1168 prefix += p.inPrivateClass + "->";
1169 }
1170
1171 if (p.gspec == PropertyDef::PointerSpec)
1172 fprintf(stream: out, format: " case %d: _a[0] = const_cast<void*>(reinterpret_cast<const void*>(%s%s())); break;\n",
1173 propindex, prefix.constData(), p.read.constData());
1174 else if (p.gspec == PropertyDef::ReferenceSpec)
1175 fprintf(stream: out, format: " case %d: _a[0] = const_cast<void*>(reinterpret_cast<const void*>(&%s%s())); break;\n",
1176 propindex, prefix.constData(), p.read.constData());
1177#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0)
1178 else if (auto eflags = cdef->enumDeclarations.value(key: p.type); eflags & EnumIsFlag)
1179 fprintf(stream: out, format: " case %d: QtMocHelpers::assignFlags<%s>(_v, %s%s()); break;\n",
1180 propindex, disambiguatedTypeName(name: p.type, tag: p.typeTag).constData(), prefix.constData(), p.read.constData());
1181#endif
1182 else if (p.read == "default")
1183 fprintf(stream: out, format: " case %d: *reinterpret_cast<%s%s*>(_v) = %s%s().value(); break;\n",
1184 propindex, cxxTypeTag(t: p.typeTag), disambiguatedTypeName(name: p.type, tag: p.typeTag).constData(),
1185 prefix.constData(), p.bind.constData());
1186 else if (!p.read.isEmpty())
1187 fprintf(stream: out, format: " case %d: *reinterpret_cast<%s%s*>(_v) = %s%s(); break;\n",
1188 propindex, cxxTypeTag(t: p.typeTag), disambiguatedTypeName(name: p.type, tag: p.typeTag).constData(),
1189 prefix.constData(), p.read.constData());
1190 else
1191 fprintf(stream: out, format: " case %d: *reinterpret_cast<%s%s*>(_v) = %s%s; break;\n",
1192 propindex, cxxTypeTag(t: p.typeTag), disambiguatedTypeName(name: p.type, tag: p.typeTag).constData(),
1193 prefix.constData(), p.member.constData());
1194 }
1195 fprintf(stream: out, format: " default: break;\n");
1196 fprintf(stream: out, format: " }\n");
1197 fprintf(stream: out, format: " }\n");
1198 }
1199
1200 if (needSet) {
1201 fprintf(stream: out, format: " if (_c == QMetaObject::WriteProperty) {\n");
1202 fprintf(stream: out, format: " void *_v = _a[0];\n");
1203 fprintf(stream: out, format: " switch (_id) {\n");
1204 for (int propindex = 0; propindex < int(cdef->propertyList.size()); ++propindex) {
1205 const PropertyDef &p = cdef->propertyList.at(i: propindex);
1206 if (p.constant)
1207 continue;
1208 if (p.write.isEmpty() && p.member.isEmpty())
1209 continue;
1210 QByteArray prefix = "_t->";
1211 if (p.inPrivateClass.size()) {
1212 prefix += p.inPrivateClass + "->";
1213 }
1214 if (p.write == "default") {
1215 fprintf(stream: out, format: " case %d: {\n", propindex);
1216 fprintf(stream: out, format: " %s%s().setValue(*reinterpret_cast<%s%s*>(_v));\n",
1217 prefix.constData(), p.bind.constData(), cxxTypeTag(t: p.typeTag),
1218 disambiguatedTypeName(name: p.type, tag: p.typeTag).constData());
1219 fprintf(stream: out, format: " break;\n");
1220 fprintf(stream: out, format: " }\n");
1221 } else if (!p.write.isEmpty()) {
1222 fprintf(stream: out, format: " case %d: %s%s(*reinterpret_cast<%s%s*>(_v)); break;\n",
1223 propindex, prefix.constData(), p.write.constData(),
1224 cxxTypeTag(t: p.typeTag), disambiguatedTypeName(name: p.type, tag: p.typeTag).constData());
1225 } else {
1226 fprintf(stream: out, format: " case %d:", propindex);
1227 if (p.notify.isEmpty()) {
1228 fprintf(stream: out, format: " QtMocHelpers::setProperty(%s%s, *reinterpret_cast<%s%s*>(_v)); break;\n",
1229 prefix.constData(), p.member.constData(), cxxTypeTag(t: p.typeTag),
1230 disambiguatedTypeName(name: p.type, tag: p.typeTag).constData());
1231 } else {
1232 fprintf(stream: out, format: "\n if (QtMocHelpers::setProperty(%s%s, *reinterpret_cast<%s%s*>(_v)))\n",
1233 prefix.constData(), p.member.constData(), cxxTypeTag(t: p.typeTag),
1234 disambiguatedTypeName(name: p.type, tag: p.typeTag).constData());
1235 fprintf(stream: out, format: " Q_EMIT _t->%s(", p.notify.constData());
1236 if (p.notifyId > -1) {
1237 const FunctionDef &f = cdef->signalList.at(i: p.notifyId);
1238 if (f.arguments.size() == 1 && f.arguments.at(i: 0).normalizedType == p.type)
1239 fprintf(stream: out, format: "%s%s", prefix.constData(), p.member.constData());
1240 }
1241 fprintf(stream: out, format: ");\n");
1242 fprintf(stream: out, format: " break;\n");
1243 }
1244 }
1245 }
1246 fprintf(stream: out, format: " default: break;\n");
1247 fprintf(stream: out, format: " }\n");
1248 fprintf(stream: out, format: " }\n");
1249 }
1250
1251 if (needReset) {
1252 fprintf(stream: out, format: " if (_c == QMetaObject::ResetProperty) {\n");
1253 fprintf(stream: out, format: " switch (_id) {\n");
1254 for (int propindex = 0; propindex < int(cdef->propertyList.size()); ++propindex) {
1255 const PropertyDef &p = cdef->propertyList.at(i: propindex);
1256 if (p.reset.isEmpty())
1257 continue;
1258 QByteArray prefix = "_t->";
1259 if (p.inPrivateClass.size()) {
1260 prefix += p.inPrivateClass + "->";
1261 }
1262 fprintf(stream: out, format: " case %d: %s%s(); break;\n",
1263 propindex, prefix.constData(), p.reset.constData());
1264 }
1265 fprintf(stream: out, format: " default: break;\n");
1266 fprintf(stream: out, format: " }\n");
1267 fprintf(stream: out, format: " }\n");
1268 }
1269
1270 if (hasBindableProperties) {
1271 fprintf(stream: out, format: " if (_c == QMetaObject::BindableProperty) {\n");
1272 fprintf(stream: out, format: " switch (_id) {\n");
1273 for (int propindex = 0; propindex < int(cdef->propertyList.size()); ++propindex) {
1274 const PropertyDef &p = cdef->propertyList.at(i: propindex);
1275 if (p.bind.isEmpty())
1276 continue;
1277 QByteArray prefix = "_t->";
1278 if (p.inPrivateClass.size()) {
1279 prefix += p.inPrivateClass + "->";
1280 }
1281 fprintf(stream: out,
1282 format: " case %d: *static_cast<QUntypedBindable *>(_a[0]) = %s%s(); "
1283 "break;\n",
1284 propindex, prefix.constData(), p.bind.constData());
1285 }
1286 fprintf(stream: out, format: " default: break;\n");
1287 fprintf(stream: out, format: " }\n");
1288 fprintf(stream: out, format: " }\n");
1289 }
1290 }
1291
1292 auto printUnused = [&](UsedArgs entry, const char *name) {
1293 if ((usedArgs & entry) == 0)
1294 fprintf(stream: out, format: " (void)%s;\n", name);
1295 };
1296 printUnused(UsedT, "_t");
1297 printUnused(UsedC, "_c");
1298 printUnused(UsedId, "_id");
1299 printUnused(UsedA, "_a");
1300
1301 fprintf(stream: out, format: "}\n");
1302}
1303
1304void Generator::generateSignal(const FunctionDef *def, int index)
1305{
1306 if (def->wasCloned || def->isAbstract)
1307 return;
1308 fprintf(stream: out, format: "\n// SIGNAL %d\n%s %s::%s(",
1309 index, def->type.name.constData(), cdef->qualified.constData(), def->name.constData());
1310
1311 QByteArray thisPtr = "this";
1312 const char *constQualifier = "";
1313
1314 if (def->isConst) {
1315 thisPtr = "const_cast< " + cdef->qualified + " *>(this)";
1316 constQualifier = "const";
1317 }
1318
1319 Q_ASSERT(!def->normalizedType.isEmpty());
1320 if (def->arguments.isEmpty() && def->normalizedType == "void" && !def->isPrivateSignal) {
1321 fprintf(stream: out, format: ")%s\n{\n"
1322 " QMetaObject::activate(%s, &staticMetaObject, %d, nullptr);\n"
1323 "}\n", constQualifier, thisPtr.constData(), index);
1324 return;
1325 }
1326
1327 int offset = 1;
1328 const auto begin = def->arguments.cbegin();
1329 const auto end = def->arguments.cend();
1330 for (auto it = begin; it != end; ++it) {
1331 const ArgumentDef &a = *it;
1332 if (it != begin)
1333 fputs(s: ", ", stream: out);
1334 if (a.type.name.size())
1335 fputs(s: a.type.name.constData(), stream: out);
1336 fprintf(stream: out, format: " _t%d", offset++);
1337 if (a.rightType.size())
1338 fputs(s: a.rightType.constData(), stream: out);
1339 }
1340 if (def->isPrivateSignal) {
1341 if (!def->arguments.isEmpty())
1342 fprintf(stream: out, format: ", ");
1343 fprintf(stream: out, format: "QPrivateSignal _t%d", offset++);
1344 }
1345
1346 fprintf(stream: out, format: ")%s\n{\n", constQualifier);
1347 if (def->type.name.size() && def->normalizedType != "void") {
1348 QByteArray returnType = noRef(type: def->normalizedType);
1349 fprintf(stream: out, format: " %s _t0{};\n", returnType.constData());
1350 }
1351
1352 fprintf(stream: out, format: " QMetaObject::activate<%s>(%s, &staticMetaObject, %d, ",
1353 def->normalizedType.constData(), thisPtr.constData(), index);
1354 if (def->normalizedType == "void") {
1355 fprintf(stream: out, format: "nullptr");
1356 } else {
1357 fprintf(stream: out, format: "std::addressof(_t0)");
1358 }
1359 int i;
1360 for (i = 1; i < offset; ++i)
1361 fprintf(stream: out, format: ", _t%d", i);
1362 fprintf(stream: out, format: ");\n");
1363
1364 if (def->normalizedType != "void")
1365 fprintf(stream: out, format: " return _t0;\n");
1366 fprintf(stream: out, format: "}\n");
1367}
1368
1369static CborError jsonValueToCbor(CborEncoder *parent, const QJsonValue &v);
1370static CborError jsonObjectToCbor(CborEncoder *parent, const QJsonObject &o)
1371{
1372 auto it = o.constBegin();
1373 auto end = o.constEnd();
1374 CborEncoder map;
1375 cbor_encoder_create_map(parentEncoder: parent, mapEncoder: &map, length: o.size());
1376
1377 for ( ; it != end; ++it) {
1378 QByteArray key = it.key().toUtf8();
1379 cbor_encode_text_string(encoder: &map, string: key.constData(), length: key.size());
1380 jsonValueToCbor(parent: &map, v: it.value());
1381 }
1382 return cbor_encoder_close_container(parentEncoder: parent, containerEncoder: &map);
1383}
1384
1385static CborError jsonArrayToCbor(CborEncoder *parent, const QJsonArray &a)
1386{
1387 CborEncoder array;
1388 cbor_encoder_create_array(parentEncoder: parent, arrayEncoder: &array, length: a.size());
1389 for (const QJsonValue v : a)
1390 jsonValueToCbor(parent: &array, v);
1391 return cbor_encoder_close_container(parentEncoder: parent, containerEncoder: &array);
1392}
1393
1394static CborError jsonValueToCbor(CborEncoder *parent, const QJsonValue &v)
1395{
1396 switch (v.type()) {
1397 case QJsonValue::Null:
1398 case QJsonValue::Undefined:
1399 return cbor_encode_null(encoder: parent);
1400 case QJsonValue::Bool:
1401 return cbor_encode_boolean(encoder: parent, value: v.toBool());
1402 case QJsonValue::Array:
1403 return jsonArrayToCbor(parent, a: v.toArray());
1404 case QJsonValue::Object:
1405 return jsonObjectToCbor(parent, o: v.toObject());
1406 case QJsonValue::String: {
1407 QByteArray s = v.toString().toUtf8();
1408 return cbor_encode_text_string(encoder: parent, string: s.constData(), length: s.size());
1409 }
1410 case QJsonValue::Double: {
1411 double d = v.toDouble();
1412 if (d == floor(x: d) && fabs(x: d) <= (Q_INT64_C(1) << std::numeric_limits<double>::digits))
1413 return cbor_encode_int(encoder: parent, value: qint64(d));
1414 return cbor_encode_double(encoder: parent, value: d);
1415 }
1416 }
1417 Q_UNREACHABLE_RETURN(CborUnknownError);
1418}
1419
1420void Generator::generatePluginMetaData()
1421{
1422 if (cdef->pluginData.iid.isEmpty())
1423 return;
1424
1425 auto outputCborData = [this]() {
1426 CborDevice dev(out);
1427 CborEncoder enc;
1428 cbor_encoder_init_writer(encoder: &enc, writer: CborDevice::callback, &dev);
1429
1430 CborEncoder map;
1431 cbor_encoder_create_map(parentEncoder: &enc, mapEncoder: &map, length: CborIndefiniteLength);
1432
1433 dev.nextItem(comment: "\"IID\"");
1434 cbor_encode_int(encoder: &map, value: int(QtPluginMetaDataKeys::IID));
1435 cbor_encode_text_string(encoder: &map, string: cdef->pluginData.iid.constData(), length: cdef->pluginData.iid.size());
1436
1437 dev.nextItem(comment: "\"className\"");
1438 cbor_encode_int(encoder: &map, value: int(QtPluginMetaDataKeys::ClassName));
1439 cbor_encode_text_string(encoder: &map, string: cdef->classname.constData(), length: cdef->classname.size());
1440
1441 QJsonObject o = cdef->pluginData.metaData.object();
1442 if (!o.isEmpty()) {
1443 dev.nextItem(comment: "\"MetaData\"");
1444 cbor_encode_int(encoder: &map, value: int(QtPluginMetaDataKeys::MetaData));
1445 jsonObjectToCbor(parent: &map, o);
1446 }
1447
1448 if (!cdef->pluginData.uri.isEmpty()) {
1449 dev.nextItem(comment: "\"URI\"");
1450 cbor_encode_int(encoder: &map, value: int(QtPluginMetaDataKeys::URI));
1451 cbor_encode_text_string(encoder: &map, string: cdef->pluginData.uri.constData(), length: cdef->pluginData.uri.size());
1452 }
1453
1454 // Add -M args from the command line:
1455 for (auto it = cdef->pluginData.metaArgs.cbegin(), end = cdef->pluginData.metaArgs.cend(); it != end; ++it) {
1456 const QJsonArray &a = it.value();
1457 QByteArray key = it.key().toUtf8();
1458 dev.nextItem(comment: QByteArray("command-line \"" + key + "\"").constData());
1459 cbor_encode_text_string(encoder: &map, string: key.constData(), length: key.size());
1460 jsonArrayToCbor(parent: &map, a);
1461 }
1462
1463 // Close the CBOR map manually
1464 dev.nextItem();
1465 cbor_encoder_close_container(parentEncoder: &enc, containerEncoder: &map);
1466 };
1467
1468 // 'Use' all namespaces.
1469 qsizetype pos = cdef->qualified.indexOf(bv: "::");
1470 for ( ; pos != -1 ; pos = cdef->qualified.indexOf(bv: "::", from: pos + 2) )
1471 fprintf(stream: out, format: "using namespace %s;\n", cdef->qualified.left(n: pos).constData());
1472
1473 fputs(s: "\n#ifdef QT_MOC_EXPORT_PLUGIN_V2", stream: out);
1474
1475 // Qt 6.3+ output
1476 fprintf(stream: out, format: "\nstatic constexpr unsigned char qt_pluginMetaDataV2_%s[] = {",
1477 cdef->classname.constData());
1478 outputCborData();
1479 fprintf(stream: out, format: "\n};\nQT_MOC_EXPORT_PLUGIN_V2(%s, %s, qt_pluginMetaDataV2_%s)\n",
1480 cdef->qualified.constData(), cdef->classname.constData(), cdef->classname.constData());
1481
1482 // compatibility with Qt 6.0-6.2
1483 fprintf(stream: out, format: "#else\nQT_PLUGIN_METADATA_SECTION\n"
1484 "Q_CONSTINIT static constexpr unsigned char qt_pluginMetaData_%s[] = {\n"
1485 " 'Q', 'T', 'M', 'E', 'T', 'A', 'D', 'A', 'T', 'A', ' ', '!',\n"
1486 " // metadata version, Qt version, architectural requirements\n"
1487 " 0, QT_VERSION_MAJOR, QT_VERSION_MINOR, qPluginArchRequirements(),",
1488 cdef->classname.constData());
1489 outputCborData();
1490 fprintf(stream: out, format: "\n};\nQT_MOC_EXPORT_PLUGIN(%s, %s)\n"
1491 "#endif // QT_MOC_EXPORT_PLUGIN_V2\n",
1492 cdef->qualified.constData(), cdef->classname.constData());
1493
1494 fputs(s: "\n", stream: out);
1495}
1496
1497QByteArray Generator::disambiguatedTypeName(const QByteArray &name)
1498{
1499 if (cdef->allEnumNames.contains(value: name))
1500 return "enum " + name;
1501 return name;
1502}
1503
1504// in contexts where we already print the type tag, we don't want to do the
1505// disambiguation
1506QByteArray Generator::disambiguatedTypeName(const QByteArray &name, TypeTags tag)
1507{
1508 if (tag == TypeTag::None)
1509 return disambiguatedTypeName(name);
1510 return name;
1511}
1512
1513QByteArray Generator::disambiguatedTypeNameForCast(const QByteArray &name)
1514{
1515 return QByteArray("std::add_pointer_t<"+ disambiguatedTypeName(name) +">");
1516}
1517
1518QT_WARNING_DISABLE_GCC("-Wunused-function")
1519QT_WARNING_DISABLE_CLANG("-Wunused-function")
1520QT_WARNING_DISABLE_CLANG("-Wundefined-internal")
1521QT_WARNING_DISABLE_MSVC(4334) // '<<': result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?)
1522
1523#define CBOR_NO_HALF_FLOAT_TYPE 1
1524#define CBOR_ENCODER_WRITER_CONTROL 1
1525#define CBOR_ENCODER_WRITE_FUNCTION CborDevice::callback
1526
1527QT_END_NAMESPACE
1528
1529#include "cborencoder.c"
1530

source code of qtbase/src/tools/moc/generator.cpp