-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.cpp
1663 lines (1464 loc) · 63.4 KB
/
generator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2020 The Qt Company Ltd.
// Copyright (C) 2019 Olivier Goffart <[email protected]>
// Copyright (C) 2018 Intel Corporation.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#include "generator.h"
#include "cbordevice.h"
#include "outputrevision.h"
#include "utils.h"
#include <metaobject/qmetatype.h>
#include <metaobject/qmetaobject.h>
#include <metaobject/qmetamethod.h> //enum PropertyFlags
#include <serialization/qjsondocument.h>
#include <serialization/qjsonobject.h>
#include <serialization/qjsonvalue.h>
#include <serialization/qjsonarray.h>
#include <plugin/qplugin.h>
#include <text/qstringview.h>
#include <math.h>
#include <stdio.h>
QT_BEGIN_NAMESPACE
uint nameToBuiltinType(const QByteArray &name)
{
if (name.isEmpty())
return 0;
uint tp = qMetaTypeTypeInternal(name.constData());
return tp < uint(QMetaType::User) ? tp : uint(QMetaType::UnknownType);
}
/*
Returns \c true if the type is a built-in type.
*/
bool isBuiltinType(const QByteArray &type)
{
int id = qMetaTypeTypeInternal(type.constData());
if (id == QMetaType::UnknownType)
return false;
return (id < QMetaType::User);
}
static const char *metaTypeEnumValueString(int type)
{
#define RETURN_METATYPENAME_STRING(MetaTypeName, MetaTypeId, RealType) \
case QMetaType::MetaTypeName: return #MetaTypeName;
switch (type) {
QT_FOR_EACH_STATIC_TYPE(RETURN_METATYPENAME_STRING)
}
#undef RETURN_METATYPENAME_STRING
return nullptr;
}
Generator::Generator(ClassDef *classDef, const QList<QByteArray> &metaTypes,
const QHash<QByteArray, QByteArray> &knownQObjectClasses,
const QHash<QByteArray, QByteArray> &knownGadgets, FILE *outfile,
bool requireCompleteTypes)
: out(outfile),
cdef(classDef),
metaTypes(metaTypes),
knownQObjectClasses(knownQObjectClasses),
knownGadgets(knownGadgets),
requireCompleteTypes(requireCompleteTypes)
{
if (cdef->superclassList.size())
purestSuperClass = cdef->superclassList.constFirst().first;
}
static inline int lengthOfEscapeSequence(const QByteArray &s, int i)
{
if (s.at(i) != '\\' || i >= s.size() - 1)
return 1;
const int startPos = i;
++i;
char ch = s.at(i);
if (ch == 'x') {
++i;
while (i < s.size() && is_hex_char(s.at(i)))
++i;
} else if (is_octal_char(ch)) {
while (i < startPos + 4
&& i < s.size()
&& is_octal_char(s.at(i))) {
++i;
}
} else { // single character escape sequence
i = qMin(i + 1, s.size());
}
return i - startPos;
}
static inline uint lengthOfEscapedString(const QByteArray &str)
{
int extra = 0;
for (int j = 0; j < str.size(); ++j) {
if (str.at(j) == '\\') {
int cnt = lengthOfEscapeSequence(str, j) - 1;
extra += cnt;
j += cnt;
}
}
return str.size() - extra;
}
// Prints \a s to \a out, breaking it into lines of at most ColumnWidth. The
// opening and closing quotes are NOT included (it's up to the caller).
static void printStringWithIndentation(FILE *out, const QByteArray &s)
{
static constexpr int ColumnWidth = 72;
int len = s.size();
int idx = 0;
do {
int spanLen = qMin(ColumnWidth - 2, len - idx);
// don't cut escape sequences at the end of a line
int backSlashPos = s.lastIndexOf('\\', idx + spanLen - 1);
if (backSlashPos >= idx) {
int escapeLen = lengthOfEscapeSequence(s, backSlashPos);
spanLen = qBound(spanLen, backSlashPos + escapeLen - idx, len - idx);
}
fprintf(out, "\n \"%.*s\"", spanLen, s.constData() + idx);
idx += spanLen;
} while (idx < len);
}
void Generator::strreg(const QByteArray &s)
{
if (!strings.contains(s))
strings.append(s);
}
int Generator::stridx(const QByteArray &s)
{
int i = strings.indexOf(s);
Q_ASSERT_X(i != -1, Q_FUNC_INFO, "We forgot to register some strings");
return i;
}
// Returns the sum of all parameters (including return type) for the given
// \a list of methods. This is needed for calculating the size of the methods'
// parameter type/name meta-data.
static int aggregateParameterCount(const QList<FunctionDef> &list)
{
int sum = 0;
for (int i = 0; i < list.size(); ++i)
sum += list.at(i).arguments.size() + 1; // +1 for return type
return sum;
}
bool Generator::registerableMetaType(const QByteArray &propertyType)
{
if (metaTypes.contains(propertyType))
return true;
if (propertyType.endsWith('*')) {
QByteArray objectPointerType = propertyType;
// The objects container stores class names, such as 'QState', 'QLabel' etc,
// not 'QState*', 'QLabel*'. The propertyType does contain the '*', so we need
// to chop it to find the class type in the known QObjects list.
objectPointerType.chop(1);
if (knownQObjectClasses.contains(objectPointerType))
return true;
}
static const QList<QByteArray> smartPointers = QList<QByteArray>()
#define STREAM_SMART_POINTER(SMART_POINTER) << #SMART_POINTER
QT_FOR_EACH_AUTOMATIC_TEMPLATE_SMART_POINTER(STREAM_SMART_POINTER)
#undef STREAM_SMART_POINTER
;
for (const QByteArray &smartPointer : smartPointers) {
QByteArray ba = smartPointer + "<";
if (propertyType.startsWith(ba) && !propertyType.endsWith("&"))
return knownQObjectClasses.contains(propertyType.mid(smartPointer.size() + 1, propertyType.size() - smartPointer.size() - 1 - 1));
}
static const QList<QByteArray> oneArgTemplates = QList<QByteArray>()
#define STREAM_1ARG_TEMPLATE(TEMPLATENAME) << #TEMPLATENAME
QT_FOR_EACH_AUTOMATIC_TEMPLATE_1ARG(STREAM_1ARG_TEMPLATE)
#undef STREAM_1ARG_TEMPLATE
;
for (const QByteArray &oneArgTemplateType : oneArgTemplates) {
QByteArray ba = oneArgTemplateType + "<";
if (propertyType.startsWith(ba) && propertyType.endsWith(">")) {
const int argumentSize = propertyType.size() - oneArgTemplateType.size() - 1
// The closing '>'
- 1
// templates inside templates have an extra whitespace char to strip.
- (propertyType.at(propertyType.size() - 2) == ' ' ? 1 : 0 );
const QByteArray templateArg = propertyType.mid(oneArgTemplateType.size() + 1, argumentSize);
return isBuiltinType(templateArg) || registerableMetaType(templateArg);
}
}
return false;
}
/* returns \c true if name and qualifiedName refers to the same name.
* If qualified name is "A::B::C", it returns \c true for "C", "B::C" or "A::B::C" */
static bool qualifiedNameEquals(const QByteArray &qualifiedName, const QByteArray &name)
{
if (qualifiedName == name)
return true;
int index = qualifiedName.indexOf("::");
if (index == -1)
return false;
return qualifiedNameEquals(qualifiedName.mid(index+2), name);
}
static QByteArray generateQualifiedClassNameIdentifier(const QByteArray &identifier)
{
QByteArray qualifiedClassNameIdentifier = identifier;
// Remove ':'s in the name, but be sure not to create any illegal
// identifiers in the process. (Don't replace with '_', because
// that will create problems with things like NS_::_class.)
qualifiedClassNameIdentifier.replace("::", "SCOPE");
// Also, avoid any leading/trailing underscores (we'll concatenate
// the generated name with other prefixes/suffixes, and these latter
// may already include an underscore, leading to two underscores)
qualifiedClassNameIdentifier = "CLASS" + qualifiedClassNameIdentifier + "ENDCLASS";
return qualifiedClassNameIdentifier;
}
void Generator::generateCode()
{
bool isQObject = (cdef->classname == "QObject");
bool isConstructible = !cdef->constructorList.isEmpty();
// filter out undeclared enumerators and sets
{
QList<EnumDef> enumList;
for (int i = 0; i < cdef->enumList.size(); ++i) {
EnumDef def = cdef->enumList.at(i);
if (cdef->enumDeclarations.contains(def.name)) {
enumList += def;
}
def.enumName = def.name;
QByteArray alias = cdef->flagAliases.value(def.name);
if (cdef->enumDeclarations.contains(alias)) {
def.name = alias;
enumList += def;
}
}
cdef->enumList = enumList;
}
//
// Register all strings used in data section
//
strreg(cdef->qualified);
registerClassInfoStrings();
registerFunctionStrings(cdef->signalList);
registerFunctionStrings(cdef->slotList);
registerFunctionStrings(cdef->methodList);
registerFunctionStrings(cdef->constructorList);
registerByteArrayVector(cdef->nonClassSignalList);
registerPropertyStrings();
registerEnumStrings();
const bool hasStaticMetaCall =
(cdef->hasQObject || !cdef->methodList.isEmpty()
|| !cdef->propertyList.isEmpty() || !cdef->constructorList.isEmpty());
const QByteArray qualifiedClassNameIdentifier = generateQualifiedClassNameIdentifier(cdef->qualified);
// ensure the qt_meta_stringdata_XXXX_t type is local
fprintf(out, "namespace {\n");
//
// Build the strings using QtMocHelpers::StringData
//
fprintf(out, "\n#ifdef QT_MOC_HAS_STRINGDATA\n"
"struct qt_meta_stringdata_%s_t {};\n"
"static constexpr auto qt_meta_stringdata_%s = QtMocHelpers::stringData(",
qualifiedClassNameIdentifier.constData(), qualifiedClassNameIdentifier.constData());
{
char comma = 0;
for (const QByteArray &str : strings) {
if (comma)
fputc(comma, out);
printStringWithIndentation(out, str);
comma = ',';
}
}
fprintf(out, "\n);\n"
"#else // !QT_MOC_HAS_STRING_DATA\n");
#if QT_VERSION >= QT_VERSION_CHECK(6, 9, 0)
fprintf(out, "#error \"qtmochelpers.h not found or too old.\"\n");
#else
//
// Build stringdata struct
//
fprintf(out, "struct qt_meta_stringdata_%s_t {\n", qualifiedClassNameIdentifier.constData());
fprintf(out, " uint offsetsAndSizes[%d];\n", int(strings.size() * 2));
for (int i = 0; i < strings.size(); ++i) {
int thisLength = lengthOfEscapedString(strings.at(i)) + 1;
fprintf(out, " char stringdata%d[%d];\n", i, thisLength);
}
fprintf(out, "};\n");
// Macro that simplifies the string data listing. The offset is calculated
// from the top of the stringdata object (i.e., past the uints).
fprintf(out, "#define QT_MOC_LITERAL(ofs, len) \\\n"
" uint(sizeof(qt_meta_stringdata_%s_t::offsetsAndSizes) + ofs), len \n",
qualifiedClassNameIdentifier.constData());
fprintf(out, "Q_CONSTINIT static const qt_meta_stringdata_%s_t qt_meta_stringdata_%s = {\n",
qualifiedClassNameIdentifier.constData(), qualifiedClassNameIdentifier.constData());
fprintf(out, " {");
{
int idx = 0;
for (int i = 0; i < strings.size(); ++i) {
const QByteArray &str = strings.at(i);
const QByteArray comment = str.size() > 32 ? str.left(29) + "..." : str;
const char *comma = (i != strings.size() - 1 ? "," : " ");
int len = lengthOfEscapedString(str);
fprintf(out, "\n QT_MOC_LITERAL(%d, %d)%s // \"%s\"", idx, len, comma,
comment.constData());
idx += len + 1;
}
fprintf(out, "\n }");
}
//
// Build stringdata arrays
//
for (const QByteArray &s : std::as_const(strings)) {
fputc(',', out);
printStringWithIndentation(out, s);
}
// Terminate stringdata struct
fprintf(out, "\n};\n");
fprintf(out, "#undef QT_MOC_LITERAL\n");
#endif // Qt 6.9
fprintf(out, "#endif // !QT_MOC_HAS_STRING_DATA\n");
fprintf(out, "} // unnamed namespace\n\n");
//
// build the data array
//
int index = 14 /* MetaObjectPrivateFieldCount */;
fprintf(out, "Q_CONSTINIT static const uint qt_meta_data_%s[] = {\n", qualifiedClassNameIdentifier.constData());
fprintf(out, "\n // content:\n");
fprintf(out, " %4d, // revision\n", 11 /* int(QMetaObjectPrivate::OutputRevision) */);
fprintf(out, " %4d, // classname\n", stridx(cdef->qualified));
fprintf(out, " %4d, %4d, // classinfo\n", int(cdef->classInfoList.size()), int(cdef->classInfoList.size() ? index : 0));
index += cdef->classInfoList.size() * 2;
int methodCount = cdef->signalList.size() + cdef->slotList.size() + cdef->methodList.size();
fprintf(out, " %4d, %4d, // methods\n", methodCount, methodCount ? index : 0);
index += methodCount * 6 /* QMetaMethod::Data::Size */ /* QMetaObjectPrivate::IntsPerMethod */;
if (cdef->revisionedMethods)
index += methodCount;
int paramsIndex = index;
int totalParameterCount = aggregateParameterCount(cdef->signalList)
+ aggregateParameterCount(cdef->slotList)
+ aggregateParameterCount(cdef->methodList)
+ aggregateParameterCount(cdef->constructorList);
index += totalParameterCount * 2 // types and parameter names
- methodCount // return "parameters" don't have names
- cdef->constructorList.size(); // "this" parameters don't have names
fprintf(out, " %4d, %4d, // properties\n", int(cdef->propertyList.size()), int(cdef->propertyList.size() ? index : 0));
index += cdef->propertyList.size() * 5 /* QMetaProperty::Data::Size */ /* QMetaObjectPrivate::IntsPerProperty */;
fprintf(out, " %4d, %4d, // enums/sets\n", int(cdef->enumList.size()), cdef->enumList.size() ? index : 0);
int enumsIndex = index;
for (int i = 0; i < cdef->enumList.size(); ++i)
index += 5 + (cdef->enumList.at(i).values.size() * 2);
fprintf(out, " %4d, %4d, // constructors\n", isConstructible ? int(cdef->constructorList.size()) : 0,
isConstructible ? index : 0);
int flags = 0;
if (cdef->hasQGadget || cdef->hasQNamespace) {
// Ideally, all the classes could have that flag. But this broke classes generated
// by qdbusxml2cpp which generate code that require that we call qt_metacall for properties
flags |= PropertyAccessInStaticMetaCall;
}
fprintf(out, " %4d, // flags\n", flags);
fprintf(out, " %4d, // signalCount\n", int(cdef->signalList.size()));
//
// Build classinfo array
//
generateClassInfos();
// all property metatypes, + 1 for the type of the current class itself
int initialMetaTypeOffset = cdef->propertyList.size() + 1;
//
// Build signals array first, otherwise the signal indices would be wrong
//
generateFunctions(cdef->signalList, "signal", MethodSignal, paramsIndex, initialMetaTypeOffset);
//
// Build slots array
//
generateFunctions(cdef->slotList, "slot", MethodSlot, paramsIndex, initialMetaTypeOffset);
//
// Build method array
//
generateFunctions(cdef->methodList, "method", MethodMethod, paramsIndex, initialMetaTypeOffset);
//
// Build method version arrays
//
if (cdef->revisionedMethods) {
generateFunctionRevisions(cdef->signalList, "signal");
generateFunctionRevisions(cdef->slotList, "slot");
generateFunctionRevisions(cdef->methodList, "method");
}
//
// Build method parameters array
//
generateFunctionParameters(cdef->signalList, "signal");
generateFunctionParameters(cdef->slotList, "slot");
generateFunctionParameters(cdef->methodList, "method");
if (isConstructible)
generateFunctionParameters(cdef->constructorList, "constructor");
//
// Build property array
//
generateProperties();
//
// Build enums array
//
generateEnums(enumsIndex);
//
// Build constructors array
//
if (isConstructible)
generateFunctions(cdef->constructorList, "constructor", MethodConstructor, paramsIndex, initialMetaTypeOffset);
//
// Terminate data array
//
fprintf(out, "\n 0 // eod\n};\n\n");
//
// Build extra array
//
QList<QByteArray> extraList;
QMultiHash<QByteArray, QByteArray> knownExtraMetaObject(knownGadgets);
knownExtraMetaObject.unite(knownQObjectClasses);
for (int i = 0; i < cdef->propertyList.size(); ++i) {
const PropertyDef &p = cdef->propertyList.at(i);
if (isBuiltinType(p.type))
continue;
if (p.type.contains('*') || p.type.contains('<') || p.type.contains('>'))
continue;
int s = p.type.lastIndexOf("::");
if (s <= 0)
continue;
QByteArray unqualifiedScope = p.type.left(s);
// The scope may be a namespace for example, so it's only safe to include scopes that are known QObjects (QTBUG-2151)
QMultiHash<QByteArray, QByteArray>::ConstIterator scopeIt;
QByteArray thisScope = cdef->qualified;
do {
int s = thisScope.lastIndexOf("::");
thisScope = thisScope.left(s);
QByteArray currentScope = thisScope.isEmpty() ? unqualifiedScope : thisScope + "::" + unqualifiedScope;
scopeIt = knownExtraMetaObject.constFind(currentScope);
} while (!thisScope.isEmpty() && scopeIt == knownExtraMetaObject.constEnd());
if (scopeIt == knownExtraMetaObject.constEnd())
continue;
const QByteArray &scope = *scopeIt;
if (scope == "Qt")
continue;
if (qualifiedNameEquals(cdef->qualified, scope))
continue;
if (!extraList.contains(scope))
extraList += scope;
}
// QTBUG-20639 - Accept non-local enums for QML signal/slot parameters.
// Look for any scoped enum declarations, and add those to the list
// of extra/related metaobjects for this object.
for (auto it = cdef->enumDeclarations.keyBegin(),
end = cdef->enumDeclarations.keyEnd(); it != end; ++it) {
const QByteArray &enumKey = *it;
int s = enumKey.lastIndexOf("::");
if (s > 0) {
QByteArray scope = enumKey.left(s);
if (scope != "Qt" && !qualifiedNameEquals(cdef->qualified, scope) && !extraList.contains(scope))
extraList += scope;
}
}
//
// Generate meta object link to parent meta objects
//
if (!extraList.isEmpty()) {
fprintf(out, "Q_CONSTINIT static const QMetaObject::SuperData qt_meta_extradata_%s[] = {\n",
qualifiedClassNameIdentifier.constData());
for (int i = 0; i < extraList.size(); ++i) {
fprintf(out, " QMetaObject::SuperData::link<%s::staticMetaObject>(),\n", extraList.at(i).constData());
}
fprintf(out, " nullptr\n};\n\n");
}
//
// Finally create and initialize the static meta object
//
fprintf(out, "Q_CONSTINIT const QMetaObject %s::staticMetaObject = { \n"
" .d {\n",
cdef->qualified.constData());
if (isQObject)
fprintf(out, " nullptr,\n");
else if (cdef->superclassList.size() && !cdef->hasQGadget && !cdef->hasQNamespace) // for qobject, we know the super class must have a static metaobject
fprintf(out, " QMetaObject::SuperData::link<%s::staticMetaObject>(),\n", purestSuperClass.constData());
else if (cdef->superclassList.size()) // for gadgets we need to query at compile time for it
fprintf(out, " QtPrivate::MetaObjectForType<%s>::value,\n", purestSuperClass.constData());
else
fprintf(out, " nullptr,\n");
fprintf(out, " qt_meta_stringdata_%s.offsetsAndSizes,\n"
" qt_meta_data_%s,\n", qualifiedClassNameIdentifier.constData(),
qualifiedClassNameIdentifier.constData());
if (hasStaticMetaCall)
fprintf(out, " qt_static_metacall,\n");
else
fprintf(out, " nullptr,\n");
if (extraList.isEmpty())
fprintf(out, " nullptr,\n");
else
fprintf(out, " qt_meta_extradata_%s,\n", qualifiedClassNameIdentifier.constData());
const char *comma = "";
const bool requireCompleteness = requireCompleteTypes || cdef->requireCompleteMethodTypes;
auto stringForType = [requireCompleteness](const QByteArray &type, bool forceComplete) -> QByteArray {
const char *forceCompleteType = forceComplete ? ", std::true_type>" : ", std::false_type>";
if (requireCompleteness)
return type;
return "QtPrivate::TypeAndForceComplete<" % type % forceCompleteType;
};
if (!requireCompleteness) {
fprintf(out, " qt_incomplete_metaTypeArray<qt_meta_stringdata_%s_t", qualifiedClassNameIdentifier.constData());
comma = ",";
} else {
fprintf(out, " qt_metaTypeArray<");
}
// metatypes for properties
for (int i = 0; i < cdef->propertyList.size(); ++i) {
const PropertyDef &p = cdef->propertyList.at(i);
fprintf(out, "%s\n // property '%s'\n %s",
comma, p.name.constData(), stringForType(p.type, true).constData());
comma = ",";
}
// type name for the Q_OJBECT/GADGET itself, void for namespaces
auto ownType = !cdef->hasQNamespace ? cdef->classname.data() : "void";
fprintf(out, "%s\n // Q_OBJECT / Q_GADGET\n %s",
comma, stringForType(ownType, true).constData());
comma = ",";
// metatypes for all exposed methods
// because we definitely printed something above, this section doesn't need comma control
for (const QList<FunctionDef> &methodContainer :
{ cdef->signalList, cdef->slotList, cdef->methodList }) {
for (int i = 0; i< methodContainer.size(); ++i) {
const FunctionDef& fdef = methodContainer.at(i);
fprintf(out, ",\n // method '%s'\n %s",
fdef.name.constData(), stringForType(fdef.type.name, false).constData());
for (const auto &argument: fdef.arguments)
fprintf(out, ",\n %s", stringForType(argument.type.name, false).constData());
}
}
// but constructors have no return types, so this needs comma control again
for (int i = 0; i< cdef->constructorList.size(); ++i) {
const FunctionDef& fdef = cdef->constructorList.at(i);
if (fdef.arguments.isEmpty())
continue;
fprintf(out, "%s\n // constructor '%s'", comma, fdef.name.constData());
comma = "";
for (const auto &argument: fdef.arguments) {
fprintf(out, "%s\n %s", comma,
stringForType(argument.type.name, false).constData());
comma = ",";
}
}
fprintf(out, "\n >,\n");
fprintf(out, " nullptr\n} };\n\n");
//
// Generate internal qt_static_metacall() function
//
if (hasStaticMetaCall)
generateStaticMetacall();
if (!cdef->hasQObject)
return;
fprintf(out, "\nconst QMetaObject *%s::metaObject() const\n{\n return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;\n}\n",
cdef->qualified.constData());
//
// Generate smart cast function
//
fprintf(out, "\nvoid *%s::qt_metacast(const char *_clname)\n{\n", cdef->qualified.constData());
fprintf(out, " if (!_clname) return nullptr;\n");
fprintf(out, " if (!strcmp(_clname, qt_meta_stringdata_%s.stringdata0))\n"
" return static_cast<void*>(this);\n",
qualifiedClassNameIdentifier.constData());
for (int i = 1; i < cdef->superclassList.size(); ++i) { // for all superclasses but the first one
if (cdef->superclassList.at(i).second == FunctionDef::Private)
continue;
const char *cname = cdef->superclassList.at(i).first.constData();
fprintf(out, " if (!strcmp(_clname, \"%s\"))\n return static_cast< %s*>(this);\n",
cname, cname);
}
for (int i = 0; i < cdef->interfaceList.size(); ++i) {
const QList<ClassDef::Interface> &iface = cdef->interfaceList.at(i);
for (int j = 0; j < iface.size(); ++j) {
fprintf(out, " if (!strcmp(_clname, %s))\n return ", iface.at(j).interfaceId.constData());
for (int k = j; k >= 0; --k)
fprintf(out, "static_cast< %s*>(", iface.at(k).className.constData());
fprintf(out, "this%s;\n", QByteArray(j + 1, ')').constData());
}
}
if (!purestSuperClass.isEmpty() && !isQObject) {
QByteArray superClass = purestSuperClass;
fprintf(out, " return %s::qt_metacast(_clname);\n", superClass.constData());
} else {
fprintf(out, " return nullptr;\n");
}
fprintf(out, "}\n");
//
// Generate internal qt_metacall() function
//
generateMetacall();
//
// Generate internal signal functions
//
for (int signalindex = 0; signalindex < cdef->signalList.size(); ++signalindex)
generateSignal(&cdef->signalList[signalindex], signalindex);
//
// Generate plugin meta data
//
generatePluginMetaData();
//
// Generate function to make sure the non-class signals exist in the parent classes
//
if (!cdef->nonClassSignalList.isEmpty()) {
fprintf(out, "// If you get a compile error in this function it can be because either\n");
fprintf(out, "// a) You are using a NOTIFY signal that does not exist. Fix it.\n");
fprintf(out, "// b) You are using a NOTIFY signal that does exist (in a parent class) but has a non-empty parameter list. This is a moc limitation.\n");
fprintf(out, "[[maybe_unused]] static void checkNotifySignalValidity_%s(%s *t) {\n", qualifiedClassNameIdentifier.constData(), cdef->qualified.constData());
for (const QByteArray &nonClassSignal : std::as_const(cdef->nonClassSignalList))
fprintf(out, " t->%s();\n", nonClassSignal.constData());
fprintf(out, "}\n");
}
}
void Generator::registerClassInfoStrings()
{
for (int i = 0; i < cdef->classInfoList.size(); ++i) {
const ClassInfoDef &c = cdef->classInfoList.at(i);
strreg(c.name);
strreg(c.value);
}
}
void Generator::generateClassInfos()
{
if (cdef->classInfoList.isEmpty())
return;
fprintf(out, "\n // classinfo: key, value\n");
for (int i = 0; i < cdef->classInfoList.size(); ++i) {
const ClassInfoDef &c = cdef->classInfoList.at(i);
fprintf(out, " %4d, %4d,\n", stridx(c.name), stridx(c.value));
}
}
void Generator::registerFunctionStrings(const QList<FunctionDef> &list)
{
for (int i = 0; i < list.size(); ++i) {
const FunctionDef &f = list.at(i);
strreg(f.name);
if (!isBuiltinType(f.normalizedType))
strreg(f.normalizedType);
strreg(f.tag);
int argsCount = f.arguments.size();
for (int j = 0; j < argsCount; ++j) {
const ArgumentDef &a = f.arguments.at(j);
if (!isBuiltinType(a.normalizedType))
strreg(a.normalizedType);
strreg(a.name);
}
}
}
void Generator::registerByteArrayVector(const QList<QByteArray> &list)
{
for (const QByteArray &ba : list)
strreg(ba);
}
void Generator::generateFunctions(const QList<FunctionDef> &list, const char *functype, int type,
int ¶msIndex, int &initialMetatypeOffset)
{
if (list.isEmpty())
return;
fprintf(out, "\n // %ss: name, argc, parameters, tag, flags, initial metatype offsets\n", functype);
for (int i = 0; i < list.size(); ++i) {
const FunctionDef &f = list.at(i);
QByteArray comment;
uint flags = type;
if (f.access == FunctionDef::Private) {
flags |= AccessPrivate;
comment.append("Private");
} else if (f.access == FunctionDef::Public) {
flags |= AccessPublic;
comment.append("Public");
} else if (f.access == FunctionDef::Protected) {
flags |= AccessProtected;
comment.append("Protected");
}
if (f.isCompat) {
flags |= MethodCompatibility;
comment.append(" | MethodCompatibility");
}
if (f.wasCloned) {
flags |= MethodCloned;
comment.append(" | MethodCloned");
}
if (f.isScriptable) {
flags |= MethodScriptable;
comment.append(" | isScriptable");
}
if (f.revision > 0) {
flags |= MethodRevisioned;
comment.append(" | MethodRevisioned");
}
if (f.isConst) {
flags |= MethodIsConst;
comment.append(" | MethodIsConst ");
}
int argc = f.arguments.size();
fprintf(out, " %4d, %4d, %4d, %4d, 0x%02x, %4d /* %s */,\n",
stridx(f.name), argc, paramsIndex, stridx(f.tag), flags, initialMetatypeOffset, comment.constData());
paramsIndex += 1 + argc * 2;
// constructors don't have a return type
initialMetatypeOffset += (f.isConstructor ? 0 : 1) + argc;
}
}
void Generator::generateFunctionRevisions(const QList<FunctionDef> &list, const char *functype)
{
if (list.size())
fprintf(out, "\n // %ss: revision\n", functype);
for (int i = 0; i < list.size(); ++i) {
const FunctionDef &f = list.at(i);
fprintf(out, " %4d,\n", f.revision);
}
}
void Generator::generateFunctionParameters(const QList<FunctionDef> &list, const char *functype)
{
if (list.isEmpty())
return;
fprintf(out, "\n // %ss: parameters\n", functype);
for (int i = 0; i < list.size(); ++i) {
const FunctionDef &f = list.at(i);
fprintf(out, " ");
// Types
int argsCount = f.arguments.size();
for (int j = -1; j < argsCount; ++j) {
if (j > -1)
fputc(' ', out);
const QByteArray &typeName = (j < 0) ? f.normalizedType : f.arguments.at(j).normalizedType;
generateTypeInfo(typeName, /*allowEmptyName=*/f.isConstructor);
fputc(',', out);
}
// Parameter names
for (int j = 0; j < argsCount; ++j) {
const ArgumentDef &arg = f.arguments.at(j);
fprintf(out, " %4d,", stridx(arg.name));
}
fprintf(out, "\n");
}
}
void Generator::generateTypeInfo(const QByteArray &typeName, bool allowEmptyName)
{
Q_UNUSED(allowEmptyName);
if (isBuiltinType(typeName)) {
int type;
const char *valueString;
if (typeName == "qreal") {
type = QMetaType::UnknownType;
valueString = "QReal";
} else {
type = nameToBuiltinType(typeName);
valueString = metaTypeEnumValueString(type);
}
if (valueString) {
fprintf(out, "QMetaType::%s", valueString);
} else {
Q_ASSERT(type != QMetaType::UnknownType);
fprintf(out, "%4d", type);
}
} else {
Q_ASSERT(!typeName.isEmpty() || allowEmptyName);
fprintf(out, "0x%.8x | %d", IsUnresolvedType, stridx(typeName));
}
}
void Generator::registerPropertyStrings()
{
for (int i = 0; i < cdef->propertyList.size(); ++i) {
const PropertyDef &p = cdef->propertyList.at(i);
strreg(p.name);
if (!isBuiltinType(p.type))
strreg(p.type);
}
}
void Generator::generateProperties()
{
//
// Create meta data
//
if (cdef->propertyList.size())
fprintf(out, "\n // properties: name, type, flags\n");
for (int i = 0; i < cdef->propertyList.size(); ++i) {
const PropertyDef &p = cdef->propertyList.at(i);
uint flags = Invalid;
if (!isBuiltinType(p.type))
flags |= EnumOrFlag;
if (!p.member.isEmpty() && !p.constant)
flags |= Writable;
if (!p.read.isEmpty() || !p.member.isEmpty())
flags |= Readable;
if (!p.write.isEmpty()) {
flags |= Writable;
if (p.stdCppSet())
flags |= StdCppSet;
}
if (!p.reset.isEmpty())
flags |= Resettable;
if (p.designable != "false")
flags |= Designable;
if (p.scriptable != "false")
flags |= Scriptable;
if (p.stored != "false")
flags |= Stored;
if (p.user != "false")
flags |= User;
if (p.constant)
flags |= Constant;
if (p.final)
flags |= Final;
if (p.required)
flags |= Required;
if (!p.bind.isEmpty())
flags |= Bindable;
fprintf(out, " %4d, ", stridx(p.name));
generateTypeInfo(p.type);
int notifyId = p.notifyId;
if (p.notifyId < -1) {
// signal is in parent class
const int indexInStrings = strings.indexOf(p.notify);
notifyId = indexInStrings | IsUnresolvedSignal;
}
fprintf(out, ", 0x%.8x, uint(%d), %d,\n", flags, notifyId, p.revision);
}
}
void Generator::registerEnumStrings()
{
for (int i = 0; i < cdef->enumList.size(); ++i) {
const EnumDef &e = cdef->enumList.at(i);
strreg(e.name);
if (!e.enumName.isNull())
strreg(e.enumName);
for (int j = 0; j < e.values.size(); ++j)
strreg(e.values.at(j));
}
}
void Generator::generateEnums(int index)
{
if (cdef->enumDeclarations.isEmpty())
return;
fprintf(out, "\n // enums: name, alias, flags, count, data\n");
index += 5 * cdef->enumList.size();
int i;
for (i = 0; i < cdef->enumList.size(); ++i) {
const EnumDef &e = cdef->enumList.at(i);
int flags = 0;
if (cdef->enumDeclarations.value(e.name))
flags |= EnumIsFlag;
if (e.isEnumClass)
flags |= EnumIsScoped;
fprintf(out, " %4d, %4d, 0x%.1x, %4d, %4d,\n",
stridx(e.name),
e.enumName.isNull() ? stridx(e.name) : stridx(e.enumName),
flags,
int(e.values.size()),
index);
index += e.values.size() * 2;
}
fprintf(out, "\n // enum data: key, value\n");
for (i = 0; i < cdef->enumList.size(); ++i) {
const EnumDef &e = cdef->enumList.at(i);
for (int j = 0; j < e.values.size(); ++j) {
const QByteArray &val = e.values.at(j);
QByteArray code = cdef->qualified.constData();
if (e.isEnumClass)
code += "::" + (e.enumName.isNull() ? e.name : e.enumName);
code += "::" + val;
fprintf(out, " %4d, uint(%s),\n",
stridx(val), code.constData());
}
}
}
void Generator::generateMetacall()
{
bool isQObject = (cdef->classname == "QObject");
fprintf(out, "\nint %s::qt_metacall(QMetaObject::Call _c, int _id, void **_a)\n{\n",
cdef->qualified.constData());
if (!purestSuperClass.isEmpty() && !isQObject) {
QByteArray superClass = purestSuperClass;
fprintf(out, " _id = %s::qt_metacall(_c, _id, _a);\n", superClass.constData());
}
bool needElse = false;
QList<FunctionDef> methodList;
methodList += cdef->signalList;
methodList += cdef->slotList;
methodList += cdef->methodList;
// If there are no methods or properties, we will return _id anyway, so
// don't emit this comparison -- it is unnecessary, and it makes coverity