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

source code of qtscxml/tools/qscxmlc/generator.cpp