73a060502872a3e89bb6911db3c84fd1f51cf21b
[profile/ivi/qtbase.git] / src / tools / moc / generator.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the tools applications of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "generator.h"
43 #include "outputrevision.h"
44 #include "utils.h"
45 #include <QtCore/qmetatype.h>
46 #include <QtCore/qjsondocument.h>
47 #include <QtCore/qjsonobject.h>
48 #include <QtCore/qjsonvalue.h>
49 #include <QtCore/qjsonarray.h>
50 #include <QtCore/qplugin.h>
51 #include <stdio.h>
52
53 #include <private/qmetaobject_p.h> //for the flags.
54
55 QT_BEGIN_NAMESPACE
56
57 uint nameToBuiltinType(const QByteArray &name)
58 {
59     if (name.isEmpty())
60         return 0;
61
62     uint tp = QMetaType::type(name.constData());
63     return tp < QMetaType::User ? tp : 0;
64 }
65
66 /*
67   Returns true if the type is a built-in type.
68 */
69 bool isBuiltinType(const QByteArray &type)
70  {
71     int id = QMetaType::type(type.constData());
72     if (!id && !type.isEmpty() && type != "void")
73         return false;
74     return (id < QMetaType::User);
75 }
76
77 static const char *metaTypeEnumValueString(int type)
78  {
79 #define RETURN_METATYPENAME_STRING(MetaTypeName, MetaTypeId, RealType) \
80     case QMetaType::MetaTypeName: return #MetaTypeName;
81
82     switch (type) {
83 QT_FOR_EACH_STATIC_TYPE(RETURN_METATYPENAME_STRING)
84     }
85 #undef RETURN_METATYPENAME_STRING
86     return 0;
87  }
88
89 Generator::Generator(ClassDef *classDef, const QList<QByteArray> &metaTypes, FILE *outfile)
90     : out(outfile), cdef(classDef), metaTypes(metaTypes)
91 {
92     if (cdef->superclassList.size())
93         purestSuperClass = cdef->superclassList.first().first;
94 }
95
96 static inline int lengthOfEscapeSequence(const QByteArray &s, int i)
97 {
98     if (s.at(i) != '\\' || i >= s.length() - 1)
99         return 1;
100     const int startPos = i;
101     ++i;
102     char ch = s.at(i);
103     if (ch == 'x') {
104         ++i;
105         while (i < s.length() && is_hex_char(s.at(i)))
106             ++i;
107     } else if (is_octal_char(ch)) {
108         while (i < startPos + 4
109                && i < s.length()
110                && is_octal_char(s.at(i))) {
111             ++i;
112         }
113     } else { // single character escape sequence
114         i = qMin(i + 1, s.length());
115     }
116     return i - startPos;
117 }
118
119 void Generator::strreg(const QByteArray &s)
120 {
121     if (!strings.contains(s))
122         strings.append(s);
123 }
124
125 int Generator::stridx(const QByteArray &s)
126 {
127     int i = strings.indexOf(s);
128     Q_ASSERT_X(i != -1, Q_FUNC_INFO, "We forgot to register some strings");
129     return i;
130 }
131
132 // Returns the sum of all parameters (including return type) for the given
133 // \a list of methods. This is needed for calculating the size of the methods'
134 // parameter type/name meta-data.
135 static int aggregateParameterCount(const QList<FunctionDef> &list)
136 {
137     int sum = 0;
138     for (int i = 0; i < list.count(); ++i)
139         sum += list.at(i).arguments.count() + 1; // +1 for return type
140     return sum;
141 }
142
143 void Generator::generateCode()
144 {
145     bool isQt = (cdef->classname == "Qt");
146     bool isQObject = (cdef->classname == "QObject");
147     bool isConstructible = !cdef->constructorList.isEmpty();
148
149     // filter out undeclared enumerators and sets
150     {
151         QList<EnumDef> enumList;
152         for (int i = 0; i < cdef->enumList.count(); ++i) {
153             EnumDef def = cdef->enumList.at(i);
154             if (cdef->enumDeclarations.contains(def.name)) {
155                 enumList += def;
156             }
157             QByteArray alias = cdef->flagAliases.value(def.name);
158             if (cdef->enumDeclarations.contains(alias)) {
159                 def.name = alias;
160                 enumList += def;
161             }
162         }
163         cdef->enumList = enumList;
164     }
165
166 //
167 // Register all strings used in data section
168 //
169     strreg(cdef->qualified);
170     registerClassInfoStrings();
171     registerFunctionStrings(cdef->signalList);
172     registerFunctionStrings(cdef->slotList);
173     registerFunctionStrings(cdef->methodList);
174     registerFunctionStrings(cdef->constructorList);
175     registerPropertyStrings();
176     registerEnumStrings();
177
178     QByteArray qualifiedClassNameIdentifier = cdef->qualified;
179     qualifiedClassNameIdentifier.replace(':', '_');
180
181 //
182 // Build stringdata struct
183 //
184     fprintf(out, "struct qt_meta_stringdata_%s_t {\n", qualifiedClassNameIdentifier.constData());
185     fprintf(out, "    QByteArrayData data[%d];\n", strings.size());
186     {
187         int len = 0;
188         for (int i = 0; i < strings.size(); ++i)
189             len += strings.at(i).length() + 1;
190         fprintf(out, "    char stringdata[%d];\n", len + 1);
191     }
192     fprintf(out, "};\n");
193
194     // Macro that expands into a QByteArrayData. The offset member is
195     // calculated from 1) the offset of the actual characters in the
196     // stringdata.stringdata member, and 2) the stringdata.data index of the
197     // QByteArrayData being defined. This calculation relies on the
198     // QByteArrayData::data() implementation returning simply "this + offset".
199     fprintf(out, "#define QT_MOC_LITERAL(idx, ofs, len) { \\\n"
200             "    Q_REFCOUNT_INITIALIZE_STATIC, len, 0, 0, \\\n"
201             "    offsetof(qt_meta_stringdata_%s_t, stringdata) + ofs \\\n"
202             "        - idx * sizeof(QByteArrayData) \\\n"
203             "    }\n",
204             qualifiedClassNameIdentifier.constData());
205
206     fprintf(out, "static const qt_meta_stringdata_%s_t qt_meta_stringdata_%s = {\n",
207             qualifiedClassNameIdentifier.constData(), qualifiedClassNameIdentifier.constData());
208     fprintf(out, "    {\n");
209     {
210         int idx = 0;
211         for (int i = 0; i < strings.size(); ++i) {
212             if (i)
213                 fprintf(out, ",\n");
214             const QByteArray &str = strings.at(i);
215             fprintf(out, "QT_MOC_LITERAL(%d, %d, %d)", i, idx, str.length());
216             idx += str.length() + 1;
217             for (int j = 0; j < str.length(); ++j) {
218                 if (str.at(j) == '\\') {
219                     int cnt = lengthOfEscapeSequence(str, j) - 1;
220                     idx -= cnt;
221                     j += cnt;
222                 }
223             }
224         }
225         fprintf(out, "\n    },\n");
226     }
227
228 //
229 // Build stringdata array
230 //
231     fprintf(out, "    \"");
232     int col = 0;
233     int len = 0;
234     for (int i = 0; i < strings.size(); ++i) {
235         QByteArray s = strings.at(i);
236         len = s.length();
237         if (col && col + len >= 72) {
238             fprintf(out, "\"\n    \"");
239             col = 0;
240         } else if (len && s.at(0) >= '0' && s.at(0) <= '9') {
241             fprintf(out, "\"\"");
242             len += 2;
243         }
244         int idx = 0;
245         while (idx < s.length()) {
246             if (idx > 0) {
247                 col = 0;
248                 fprintf(out, "\"\n    \"");
249             }
250             int spanLen = qMin(70, s.length() - idx);
251             // don't cut escape sequences at the end of a line
252             int backSlashPos = s.lastIndexOf('\\', idx + spanLen - 1);
253             if (backSlashPos >= idx) {
254                 int escapeLen = lengthOfEscapeSequence(s, backSlashPos);
255                 spanLen = qBound(spanLen, backSlashPos + escapeLen - idx, s.length() - idx);
256             }
257             fwrite(s.constData() + idx, 1, spanLen, out);
258             idx += spanLen;
259             col += spanLen;
260         }
261
262         fputs("\\0", out);
263         col += len + 2;
264     }
265
266 // Terminate stringdata struct
267     fprintf(out, "\"\n};\n");
268     fprintf(out, "#undef QT_MOC_LITERAL\n\n");
269
270 //
271 // build the data array
272 //
273
274     int index = MetaObjectPrivateFieldCount;
275     fprintf(out, "static const uint qt_meta_data_%s[] = {\n", qualifiedClassNameIdentifier.constData());
276     fprintf(out, "\n // content:\n");
277     fprintf(out, "    %4d,       // revision\n", int(QMetaObjectPrivate::OutputRevision));
278     fprintf(out, "    %4d,       // classname\n", stridx(cdef->qualified));
279     fprintf(out, "    %4d, %4d, // classinfo\n", cdef->classInfoList.count(), cdef->classInfoList.count() ? index : 0);
280     index += cdef->classInfoList.count() * 2;
281
282     int methodCount = cdef->signalList.count() + cdef->slotList.count() + cdef->methodList.count();
283     fprintf(out, "    %4d, %4d, // methods\n", methodCount, methodCount ? index : 0);
284     index += methodCount * 5;
285     if (cdef->revisionedMethods)
286         index += methodCount;
287     int paramsIndex = index;
288     int totalParameterCount = aggregateParameterCount(cdef->signalList)
289             + aggregateParameterCount(cdef->slotList)
290             + aggregateParameterCount(cdef->methodList)
291             + aggregateParameterCount(cdef->constructorList);
292     index += totalParameterCount * 2 // types and parameter names
293             - methodCount // return "parameters" don't have names
294             - cdef->constructorList.count(); // "this" parameters don't have names
295
296     fprintf(out, "    %4d, %4d, // properties\n", cdef->propertyList.count(), cdef->propertyList.count() ? index : 0);
297     index += cdef->propertyList.count() * 3;
298     if(cdef->notifyableProperties)
299         index += cdef->propertyList.count();
300     if (cdef->revisionedProperties)
301         index += cdef->propertyList.count();
302     fprintf(out, "    %4d, %4d, // enums/sets\n", cdef->enumList.count(), cdef->enumList.count() ? index : 0);
303
304     int enumsIndex = index;
305     for (int i = 0; i < cdef->enumList.count(); ++i)
306         index += 4 + (cdef->enumList.at(i).values.count() * 2);
307     fprintf(out, "    %4d, %4d, // constructors\n", isConstructible ? cdef->constructorList.count() : 0,
308             isConstructible ? index : 0);
309
310     fprintf(out, "    %4d,       // flags\n", 0);
311     fprintf(out, "    %4d,       // signalCount\n", cdef->signalList.count());
312
313
314 //
315 // Build classinfo array
316 //
317     generateClassInfos();
318
319 //
320 // Build signals array first, otherwise the signal indices would be wrong
321 //
322     generateFunctions(cdef->signalList, "signal", MethodSignal, paramsIndex);
323
324 //
325 // Build slots array
326 //
327     generateFunctions(cdef->slotList, "slot", MethodSlot, paramsIndex);
328
329 //
330 // Build method array
331 //
332     generateFunctions(cdef->methodList, "method", MethodMethod, paramsIndex);
333
334 //
335 // Build method version arrays
336 //
337     if (cdef->revisionedMethods) {
338         generateFunctionRevisions(cdef->signalList, "signal");
339         generateFunctionRevisions(cdef->slotList, "slot");
340         generateFunctionRevisions(cdef->methodList, "method");
341     }
342
343 //
344 // Build method parameters array
345 //
346     generateFunctionParameters(cdef->signalList, "signal");
347     generateFunctionParameters(cdef->slotList, "slot");
348     generateFunctionParameters(cdef->methodList, "method");
349     if (isConstructible)
350         generateFunctionParameters(cdef->constructorList, "constructor");
351
352 //
353 // Build property array
354 //
355     generateProperties();
356
357 //
358 // Build enums array
359 //
360     generateEnums(enumsIndex);
361
362 //
363 // Build constructors array
364 //
365     if (isConstructible)
366         generateFunctions(cdef->constructorList, "constructor", MethodConstructor, paramsIndex);
367
368 //
369 // Terminate data array
370 //
371     fprintf(out, "\n       0        // eod\n};\n\n");
372
373 //
374 // Generate internal qt_static_metacall() function
375 //
376     if (cdef->hasQObject && !isQt)
377         generateStaticMetacall();
378
379 //
380 // Build extra array
381 //
382     QList<QByteArray> extraList;
383     for (int i = 0; i < cdef->propertyList.count(); ++i) {
384         const PropertyDef &p = cdef->propertyList.at(i);
385         if (!isBuiltinType(p.type) && !metaTypes.contains(p.type) && !p.type.contains('*') &&
386                 !p.type.contains('<') && !p.type.contains('>')) {
387             int s = p.type.lastIndexOf("::");
388             if (s > 0) {
389                 QByteArray scope = p.type.left(s);
390                 if (scope != "Qt" && scope != cdef->classname && !extraList.contains(scope))
391                     extraList += scope;
392             }
393         }
394     }
395
396     // QTBUG-20639 - Accept non-local enums for QML signal/slot parameters.
397     // Look for any scoped enum declarations, and add those to the list
398     // of extra/related metaobjects for this object.
399     QList<QByteArray> enumKeys = cdef->enumDeclarations.keys();
400     for (int i = 0; i < enumKeys.count(); ++i) {
401         const QByteArray &enumKey = enumKeys[i];
402         int s = enumKey.lastIndexOf("::");
403         if (s > 0) {
404             QByteArray scope = enumKey.left(s);
405             if (scope != "Qt" && scope != cdef->classname && !extraList.contains(scope))
406                 extraList += scope;
407         }
408     }
409
410     if (!extraList.isEmpty()) {
411         fprintf(out, "static const QMetaObject *qt_meta_extradata_%s[] = {\n    ", qualifiedClassNameIdentifier.constData());
412         for (int i = 0; i < extraList.count(); ++i) {
413             fprintf(out, "    &%s::staticMetaObject,\n", extraList.at(i).constData());
414         }
415         fprintf(out, "    0\n};\n\n");
416     }
417
418     bool hasExtraData = (cdef->hasQObject && !isQt) || !extraList.isEmpty();
419     if (hasExtraData) {
420         fprintf(out, "const QMetaObjectExtraData %s::staticMetaObjectExtraData = {\n    ",
421                 cdef->qualified.constData());
422         if (extraList.isEmpty())
423             fprintf(out, "0, ");
424         else
425             fprintf(out, "qt_meta_extradata_%s, ", qualifiedClassNameIdentifier.constData());
426
427         if (cdef->hasQObject && !isQt)
428             fprintf(out, " qt_static_metacall");
429         else
430             fprintf(out, " 0");
431         fprintf(out, " \n};\n\n");
432     }
433
434 //
435 // Finally create and initialize the static meta object
436 //
437     if (isQt)
438         fprintf(out, "const QMetaObject QObject::staticQtMetaObject = {\n");
439     else
440         fprintf(out, "const QMetaObject %s::staticMetaObject = {\n", cdef->qualified.constData());
441
442     if (isQObject)
443         fprintf(out, "    { 0, ");
444     else if (cdef->superclassList.size())
445         fprintf(out, "    { &%s::staticMetaObject, ", purestSuperClass.constData());
446     else
447         fprintf(out, "    { 0, ");
448     fprintf(out, "qt_meta_stringdata_%s.data,\n"
449             "      qt_meta_data_%s, ", qualifiedClassNameIdentifier.constData(),
450             qualifiedClassNameIdentifier.constData());
451     if (!hasExtraData)
452         fprintf(out, "0 }\n");
453     else
454         fprintf(out, "&staticMetaObjectExtraData }\n");
455     fprintf(out, "};\n");
456
457     if(isQt)
458         return;
459
460
461     if (!cdef->hasQObject)
462         return;
463
464     fprintf(out, "\nconst QMetaObject *%s::metaObject() const\n{\n    return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;\n}\n",
465             cdef->qualified.constData());
466
467 //
468 // Generate smart cast function
469 //
470     fprintf(out, "\nvoid *%s::qt_metacast(const char *_clname)\n{\n", cdef->qualified.constData());
471     fprintf(out, "    if (!_clname) return 0;\n");
472     fprintf(out, "    if (!strcmp(_clname, qt_meta_stringdata_%s.stringdata))\n"
473                   "        return static_cast<void*>(const_cast< %s*>(this));\n",
474             qualifiedClassNameIdentifier.constData(), cdef->classname.constData());
475     for (int i = 1; i < cdef->superclassList.size(); ++i) { // for all superclasses but the first one
476         if (cdef->superclassList.at(i).second == FunctionDef::Private)
477             continue;
478         const char *cname = cdef->superclassList.at(i).first.constData();
479         fprintf(out, "    if (!strcmp(_clname, \"%s\"))\n        return static_cast< %s*>(const_cast< %s*>(this));\n",
480                 cname, cname, cdef->classname.constData());
481     }
482     for (int i = 0; i < cdef->interfaceList.size(); ++i) {
483         const QList<ClassDef::Interface> &iface = cdef->interfaceList.at(i);
484         for (int j = 0; j < iface.size(); ++j) {
485             fprintf(out, "    if (!strcmp(_clname, %s))\n        return ", iface.at(j).interfaceId.constData());
486             for (int k = j; k >= 0; --k)
487                 fprintf(out, "static_cast< %s*>(", iface.at(k).className.constData());
488             fprintf(out, "const_cast< %s*>(this)%s;\n",
489                     cdef->classname.constData(), QByteArray(j+1, ')').constData());
490         }
491     }
492     if (!purestSuperClass.isEmpty() && !isQObject) {
493         QByteArray superClass = purestSuperClass;
494         // workaround for VC6
495         if (superClass.contains("::")) {
496             fprintf(out, "    typedef %s QMocSuperClass;\n", superClass.constData());
497             superClass = "QMocSuperClass";
498         }
499         fprintf(out, "    return %s::qt_metacast(_clname);\n", superClass.constData());
500     } else {
501         fprintf(out, "    return 0;\n");
502     }
503     fprintf(out, "}\n");
504
505 //
506 // Generate internal qt_metacall()  function
507 //
508     generateMetacall();
509
510 //
511 // Generate internal signal functions
512 //
513     for (int signalindex = 0; signalindex < cdef->signalList.size(); ++signalindex)
514         generateSignal(&cdef->signalList[signalindex], signalindex);
515
516 //
517 // Generate plugin meta data
518 //
519     generatePluginMetaData();
520 }
521
522
523 void Generator::registerClassInfoStrings()
524 {
525     for (int i = 0; i < cdef->classInfoList.size(); ++i) {
526         const ClassInfoDef &c = cdef->classInfoList.at(i);
527         strreg(c.name);
528         strreg(c.value);
529     }
530 }
531
532 void Generator::generateClassInfos()
533 {
534     if (cdef->classInfoList.isEmpty())
535         return;
536
537     fprintf(out, "\n // classinfo: key, value\n");
538
539     for (int i = 0; i < cdef->classInfoList.size(); ++i) {
540         const ClassInfoDef &c = cdef->classInfoList.at(i);
541         fprintf(out, "    %4d, %4d,\n", stridx(c.name), stridx(c.value));
542     }
543 }
544
545 void Generator::registerFunctionStrings(const QList<FunctionDef>& list)
546 {
547     for (int i = 0; i < list.count(); ++i) {
548         const FunctionDef &f = list.at(i);
549
550         strreg(f.name);
551         if (!isBuiltinType(f.normalizedType))
552             strreg(f.normalizedType);
553         strreg(f.tag);
554
555         for (int j = 0; j < f.arguments.count(); ++j) {
556             const ArgumentDef &a = f.arguments.at(j);
557             if (!isBuiltinType(a.normalizedType))
558                 strreg(a.normalizedType);
559             strreg(a.name);
560         }
561     }
562 }
563
564 void Generator::generateFunctions(const QList<FunctionDef>& list, const char *functype, int type, int &paramsIndex)
565 {
566     if (list.isEmpty())
567         return;
568     fprintf(out, "\n // %ss: name, argc, parameters, tag, flags\n", functype);
569
570     for (int i = 0; i < list.count(); ++i) {
571         const FunctionDef &f = list.at(i);
572
573         unsigned char flags = type;
574         if (f.access == FunctionDef::Private)
575             flags |= AccessPrivate;
576         else if (f.access == FunctionDef::Public)
577             flags |= AccessPublic;
578         else if (f.access == FunctionDef::Protected)
579             flags |= AccessProtected;
580         if (f.access == FunctionDef::Private)
581             flags |= AccessPrivate;
582         else if (f.access == FunctionDef::Public)
583             flags |= AccessPublic;
584         else if (f.access == FunctionDef::Protected)
585             flags |= AccessProtected;
586         if (f.isCompat)
587             flags |= MethodCompatibility;
588         if (f.wasCloned)
589             flags |= MethodCloned;
590         if (f.isScriptable)
591             flags |= MethodScriptable;
592         if (f.revision > 0)
593             flags |= MethodRevisioned;
594
595         int argc = f.arguments.count();
596         fprintf(out, "    %4d, %4d, %4d, %4d, 0x%02x,\n",
597             stridx(f.name), argc, paramsIndex, stridx(f.tag), flags);
598
599         paramsIndex += 1 + argc * 2;
600     }
601 }
602
603 void Generator::generateFunctionRevisions(const QList<FunctionDef>& list, const char *functype)
604 {
605     if (list.count())
606         fprintf(out, "\n // %ss: revision\n", functype);
607     for (int i = 0; i < list.count(); ++i) {
608         const FunctionDef &f = list.at(i);
609         fprintf(out, "    %4d,\n", f.revision);
610     }
611 }
612
613 void Generator::generateFunctionParameters(const QList<FunctionDef>& list, const char *functype)
614 {
615     if (list.isEmpty())
616         return;
617     fprintf(out, "\n // %ss: parameters\n", functype);
618     for (int i = 0; i < list.count(); ++i) {
619         const FunctionDef &f = list.at(i);
620         fprintf(out, "    ");
621
622         // Types
623         for (int j = -1; j < f.arguments.count(); ++j) {
624             if (j > -1)
625                 fputc(' ', out);
626             const QByteArray &typeName = (j < 0) ? f.normalizedType : f.arguments.at(j).normalizedType;
627             if (isBuiltinType(typeName)) {
628                 int type = nameToBuiltinType(typeName);
629                 const char *valueString = metaTypeEnumValueString(type);
630                 if (valueString)
631                     fprintf(out, "QMetaType::%s", valueString);
632                 else
633                     fprintf(out, "%4d", type);
634             } else {
635                 Q_ASSERT(!typeName.isEmpty());
636                 fprintf(out, "0x%.8x | %d", IsUnresolvedType, stridx(typeName));
637             }
638             fputc(',', out);
639         }
640
641         // Parameter names
642         for (int j = 0; j < f.arguments.count(); ++j) {
643             const ArgumentDef &arg = f.arguments.at(j);
644             fprintf(out, " %4d,", stridx(arg.name));
645         }
646
647         fprintf(out, "\n");
648     }
649 }
650
651 void Generator::registerPropertyStrings()
652 {
653     for (int i = 0; i < cdef->propertyList.count(); ++i) {
654         const PropertyDef &p = cdef->propertyList.at(i);
655         strreg(p.name);
656         if (!isBuiltinType(p.type))
657             strreg(p.type);
658     }
659 }
660
661 void Generator::generateProperties()
662 {
663     //
664     // Create meta data
665     //
666
667     if (cdef->propertyList.count())
668         fprintf(out, "\n // properties: name, type, flags\n");
669     for (int i = 0; i < cdef->propertyList.count(); ++i) {
670         const PropertyDef &p = cdef->propertyList.at(i);
671         uint flags = Invalid;
672         if (!isBuiltinType(p.type))
673             flags |= EnumOrFlag;
674         if (!p.read.isEmpty())
675             flags |= Readable;
676         if (!p.write.isEmpty()) {
677             flags |= Writable;
678             if (p.stdCppSet())
679                 flags |= StdCppSet;
680         }
681         if (!p.reset.isEmpty())
682             flags |= Resettable;
683
684 //         if (p.override)
685 //             flags |= Override;
686
687         if (p.designable.isEmpty())
688             flags |= ResolveDesignable;
689         else if (p.designable != "false")
690             flags |= Designable;
691
692         if (p.scriptable.isEmpty())
693             flags |= ResolveScriptable;
694         else if (p.scriptable != "false")
695             flags |= Scriptable;
696
697         if (p.stored.isEmpty())
698             flags |= ResolveStored;
699         else if (p.stored != "false")
700             flags |= Stored;
701
702         if (p.editable.isEmpty())
703             flags |= ResolveEditable;
704         else if (p.editable != "false")
705             flags |= Editable;
706
707         if (p.user.isEmpty())
708             flags |= ResolveUser;
709         else if (p.user != "false")
710             flags |= User;
711
712         if (p.notifyId != -1)
713             flags |= Notify;
714
715         if (p.revision > 0)
716             flags |= Revisioned;
717
718         if (p.constant)
719             flags |= Constant;
720         if (p.final)
721             flags |= Final;
722
723         fprintf(out, "    %4d, ", stridx(p.name));
724
725         if (isBuiltinType(p.type)) {
726             int type = nameToBuiltinType(p.type);
727             const char *valueString = metaTypeEnumValueString(type);
728             if (valueString)
729                 fprintf(out, "QMetaType::%s", valueString);
730             else
731                 fprintf(out, "%4d", type);
732         } else {
733             fprintf(out, "0x%.8x | %d", IsUnresolvedType, stridx(p.type));
734         }
735
736         fprintf(out, ", 0x%.8x,\n", flags);
737     }
738
739     if(cdef->notifyableProperties) {
740         fprintf(out, "\n // properties: notify_signal_id\n");
741         for (int i = 0; i < cdef->propertyList.count(); ++i) {
742             const PropertyDef &p = cdef->propertyList.at(i);
743             if(p.notifyId == -1)
744                 fprintf(out, "    %4d,\n",
745                         0);
746             else
747                 fprintf(out, "    %4d,\n",
748                         p.notifyId);
749         }
750     }
751     if (cdef->revisionedProperties) {
752         fprintf(out, "\n // properties: revision\n");
753         for (int i = 0; i < cdef->propertyList.count(); ++i) {
754             const PropertyDef &p = cdef->propertyList.at(i);
755             fprintf(out, "    %4d,\n", p.revision);
756         }
757     }
758 }
759
760 void Generator::registerEnumStrings()
761 {
762     for (int i = 0; i < cdef->enumList.count(); ++i) {
763         const EnumDef &e = cdef->enumList.at(i);
764         strreg(e.name);
765         for (int j = 0; j < e.values.count(); ++j)
766             strreg(e.values.at(j));
767     }
768 }
769
770 void Generator::generateEnums(int index)
771 {
772     if (cdef->enumDeclarations.isEmpty())
773         return;
774
775     fprintf(out, "\n // enums: name, flags, count, data\n");
776     index += 4 * cdef->enumList.count();
777     int i;
778     for (i = 0; i < cdef->enumList.count(); ++i) {
779         const EnumDef &e = cdef->enumList.at(i);
780         fprintf(out, "    %4d, 0x%.1x, %4d, %4d,\n",
781                  stridx(e.name),
782                  cdef->enumDeclarations.value(e.name) ? 1 : 0,
783                  e.values.count(),
784                  index);
785         index += e.values.count() * 2;
786     }
787
788     fprintf(out, "\n // enum data: key, value\n");
789     for (i = 0; i < cdef->enumList.count(); ++i) {
790         const EnumDef &e = cdef->enumList.at(i);
791         for (int j = 0; j < e.values.count(); ++j) {
792             const QByteArray &val = e.values.at(j);
793             QByteArray code = cdef->qualified.constData();
794             if (e.isEnumClass)
795                 code += "::" + e.name;
796             code += "::" + val;
797             fprintf(out, "    %4d, uint(%s),\n",
798                     stridx(val), code.constData());
799         }
800     }
801 }
802
803 void Generator::generateMetacall()
804 {
805     bool isQObject = (cdef->classname == "QObject");
806
807     fprintf(out, "\nint %s::qt_metacall(QMetaObject::Call _c, int _id, void **_a)\n{\n",
808              cdef->qualified.constData());
809
810     if (!purestSuperClass.isEmpty() && !isQObject) {
811         QByteArray superClass = purestSuperClass;
812         // workaround for VC6
813         if (superClass.contains("::")) {
814             fprintf(out, "    typedef %s QMocSuperClass;\n", superClass.constData());
815             superClass = "QMocSuperClass";
816         }
817         fprintf(out, "    _id = %s::qt_metacall(_c, _id, _a);\n", superClass.constData());
818     }
819
820     fprintf(out, "    if (_id < 0)\n        return _id;\n");
821     fprintf(out, "    ");
822
823     bool needElse = false;
824     QList<FunctionDef> methodList;
825     methodList += cdef->signalList;
826     methodList += cdef->slotList;
827     methodList += cdef->methodList;
828
829     if (methodList.size()) {
830         needElse = true;
831         fprintf(out, "if (_c == QMetaObject::InvokeMetaMethod) {\n");
832         fprintf(out, "        if (_id < %d)\n", methodList.size());
833         fprintf(out, "            qt_static_metacall(this, _c, _id, _a);\n");
834         fprintf(out, "        _id -= %d;\n    }", methodList.size());
835     }
836
837     if (cdef->propertyList.size()) {
838         bool needGet = false;
839         bool needTempVarForGet = false;
840         bool needSet = false;
841         bool needReset = false;
842         bool needDesignable = false;
843         bool needScriptable = false;
844         bool needStored = false;
845         bool needEditable = false;
846         bool needUser = false;
847         for (int i = 0; i < cdef->propertyList.size(); ++i) {
848             const PropertyDef &p = cdef->propertyList.at(i);
849             needGet |= !p.read.isEmpty();
850             if (!p.read.isEmpty())
851                 needTempVarForGet |= (p.gspec != PropertyDef::PointerSpec
852                                       && p.gspec != PropertyDef::ReferenceSpec);
853
854             needSet |= !p.write.isEmpty();
855             needReset |= !p.reset.isEmpty();
856             needDesignable |= p.designable.endsWith(')');
857             needScriptable |= p.scriptable.endsWith(')');
858             needStored |= p.stored.endsWith(')');
859             needEditable |= p.editable.endsWith(')');
860             needUser |= p.user.endsWith(')');
861         }
862         fprintf(out, "\n#ifndef QT_NO_PROPERTIES\n     ");
863
864         if (needElse)
865             fprintf(out, " else ");
866         fprintf(out, "if (_c == QMetaObject::ReadProperty) {\n");
867         if (needGet) {
868             if (needTempVarForGet)
869                 fprintf(out, "        void *_v = _a[0];\n");
870             fprintf(out, "        switch (_id) {\n");
871             for (int propindex = 0; propindex < cdef->propertyList.size(); ++propindex) {
872                 const PropertyDef &p = cdef->propertyList.at(propindex);
873                 if (p.read.isEmpty())
874                     continue;
875                 QByteArray prefix;
876                 if (p.inPrivateClass.size()) {
877                     prefix = p.inPrivateClass;
878                     prefix.append("->");
879                 }
880                 if (p.gspec == PropertyDef::PointerSpec)
881                     fprintf(out, "        case %d: _a[0] = const_cast<void*>(reinterpret_cast<const void*>(%s%s())); break;\n",
882                             propindex, prefix.constData(), p.read.constData());
883                 else if (p.gspec == PropertyDef::ReferenceSpec)
884                     fprintf(out, "        case %d: _a[0] = const_cast<void*>(reinterpret_cast<const void*>(&%s%s())); break;\n",
885                             propindex, prefix.constData(), p.read.constData());
886                 else if (cdef->enumDeclarations.value(p.type, false))
887                     fprintf(out, "        case %d: *reinterpret_cast<int*>(_v) = QFlag(%s%s()); break;\n",
888                             propindex, prefix.constData(), p.read.constData());
889                 else
890                     fprintf(out, "        case %d: *reinterpret_cast< %s*>(_v) = %s%s(); break;\n",
891                             propindex, p.type.constData(), prefix.constData(), p.read.constData());
892             }
893             fprintf(out, "        }\n");
894         }
895
896         fprintf(out,
897                 "        _id -= %d;\n"
898                 "    }", cdef->propertyList.count());
899
900         fprintf(out, " else ");
901         fprintf(out, "if (_c == QMetaObject::WriteProperty) {\n");
902
903         if (needSet) {
904             fprintf(out, "        void *_v = _a[0];\n");
905             fprintf(out, "        switch (_id) {\n");
906             for (int propindex = 0; propindex < cdef->propertyList.size(); ++propindex) {
907                 const PropertyDef &p = cdef->propertyList.at(propindex);
908                 if (p.write.isEmpty())
909                     continue;
910                 QByteArray prefix;
911                 if (p.inPrivateClass.size()) {
912                     prefix = p.inPrivateClass;
913                     prefix.append("->");
914                 }
915                 if (cdef->enumDeclarations.value(p.type, false)) {
916                     fprintf(out, "        case %d: %s%s(QFlag(*reinterpret_cast<int*>(_v))); break;\n",
917                             propindex, prefix.constData(), p.write.constData());
918                 } else {
919                     fprintf(out, "        case %d: %s%s(*reinterpret_cast< %s*>(_v)); break;\n",
920                             propindex, prefix.constData(), p.write.constData(), p.type.constData());
921                 }
922             }
923             fprintf(out, "        }\n");
924         }
925
926         fprintf(out,
927                 "        _id -= %d;\n"
928                 "    }", cdef->propertyList.count());
929
930         fprintf(out, " else ");
931         fprintf(out, "if (_c == QMetaObject::ResetProperty) {\n");
932         if (needReset) {
933             fprintf(out, "        switch (_id) {\n");
934             for (int propindex = 0; propindex < cdef->propertyList.size(); ++propindex) {
935                 const PropertyDef &p = cdef->propertyList.at(propindex);
936                 if (!p.reset.endsWith(')'))
937                     continue;
938                 QByteArray prefix;
939                 if (p.inPrivateClass.size()) {
940                     prefix = p.inPrivateClass;
941                     prefix.append("->");
942                 }
943                 fprintf(out, "        case %d: %s%s; break;\n",
944                         propindex, prefix.constData(), p.reset.constData());
945             }
946             fprintf(out, "        }\n");
947         }
948         fprintf(out,
949                 "        _id -= %d;\n"
950                 "    }", cdef->propertyList.count());
951
952         fprintf(out, " else ");
953         fprintf(out, "if (_c == QMetaObject::QueryPropertyDesignable) {\n");
954         if (needDesignable) {
955             fprintf(out, "        bool *_b = reinterpret_cast<bool*>(_a[0]);\n");
956             fprintf(out, "        switch (_id) {\n");
957             for (int propindex = 0; propindex < cdef->propertyList.size(); ++propindex) {
958                 const PropertyDef &p = cdef->propertyList.at(propindex);
959                 if (!p.designable.endsWith(')'))
960                     continue;
961                 fprintf(out, "        case %d: *_b = %s; break;\n",
962                          propindex, p.designable.constData());
963             }
964             fprintf(out, "        }\n");
965         }
966         fprintf(out,
967                 "        _id -= %d;\n"
968                 "    }", cdef->propertyList.count());
969
970         fprintf(out, " else ");
971         fprintf(out, "if (_c == QMetaObject::QueryPropertyScriptable) {\n");
972         if (needScriptable) {
973             fprintf(out, "        bool *_b = reinterpret_cast<bool*>(_a[0]);\n");
974             fprintf(out, "        switch (_id) {\n");
975             for (int propindex = 0; propindex < cdef->propertyList.size(); ++propindex) {
976                 const PropertyDef &p = cdef->propertyList.at(propindex);
977                 if (!p.scriptable.endsWith(')'))
978                     continue;
979                 fprintf(out, "        case %d: *_b = %s; break;\n",
980                          propindex, p.scriptable.constData());
981             }
982             fprintf(out, "        }\n");
983         }
984         fprintf(out,
985                 "        _id -= %d;\n"
986                 "    }", cdef->propertyList.count());
987
988         fprintf(out, " else ");
989         fprintf(out, "if (_c == QMetaObject::QueryPropertyStored) {\n");
990         if (needStored) {
991             fprintf(out, "        bool *_b = reinterpret_cast<bool*>(_a[0]);\n");
992             fprintf(out, "        switch (_id) {\n");
993             for (int propindex = 0; propindex < cdef->propertyList.size(); ++propindex) {
994                 const PropertyDef &p = cdef->propertyList.at(propindex);
995                 if (!p.stored.endsWith(')'))
996                     continue;
997                 fprintf(out, "        case %d: *_b = %s; break;\n",
998                          propindex, p.stored.constData());
999             }
1000             fprintf(out, "        }\n");
1001         }
1002         fprintf(out,
1003                 "        _id -= %d;\n"
1004                 "    }", cdef->propertyList.count());
1005
1006         fprintf(out, " else ");
1007         fprintf(out, "if (_c == QMetaObject::QueryPropertyEditable) {\n");
1008         if (needEditable) {
1009             fprintf(out, "        bool *_b = reinterpret_cast<bool*>(_a[0]);\n");
1010             fprintf(out, "        switch (_id) {\n");
1011             for (int propindex = 0; propindex < cdef->propertyList.size(); ++propindex) {
1012                 const PropertyDef &p = cdef->propertyList.at(propindex);
1013                 if (!p.editable.endsWith(')'))
1014                     continue;
1015                 fprintf(out, "        case %d: *_b = %s; break;\n",
1016                          propindex, p.editable.constData());
1017             }
1018             fprintf(out, "        }\n");
1019         }
1020         fprintf(out,
1021                 "        _id -= %d;\n"
1022                 "    }", cdef->propertyList.count());
1023
1024
1025         fprintf(out, " else ");
1026         fprintf(out, "if (_c == QMetaObject::QueryPropertyUser) {\n");
1027         if (needUser) {
1028             fprintf(out, "        bool *_b = reinterpret_cast<bool*>(_a[0]);\n");
1029             fprintf(out, "        switch (_id) {\n");
1030             for (int propindex = 0; propindex < cdef->propertyList.size(); ++propindex) {
1031                 const PropertyDef &p = cdef->propertyList.at(propindex);
1032                 if (!p.user.endsWith(')'))
1033                     continue;
1034                 fprintf(out, "        case %d: *_b = %s; break;\n",
1035                          propindex, p.user.constData());
1036             }
1037             fprintf(out, "        }\n");
1038         }
1039         fprintf(out,
1040                 "        _id -= %d;\n"
1041                 "    }", cdef->propertyList.count());
1042
1043
1044         fprintf(out, "\n#endif // QT_NO_PROPERTIES");
1045     }
1046     if (methodList.size() || cdef->signalList.size() || cdef->propertyList.size())
1047         fprintf(out, "\n    ");
1048     fprintf(out,"return _id;\n}\n");
1049 }
1050
1051 void Generator::generateStaticMetacall()
1052 {
1053     fprintf(out, "void %s::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)\n{\n",
1054             cdef->qualified.constData());
1055
1056     bool needElse = false;
1057     bool isUsed_a = false;
1058
1059     if (!cdef->constructorList.isEmpty()) {
1060         fprintf(out, "    if (_c == QMetaObject::CreateInstance) {\n");
1061         fprintf(out, "        switch (_id) {\n");
1062         for (int ctorindex = 0; ctorindex < cdef->constructorList.count(); ++ctorindex) {
1063             fprintf(out, "        case %d: { %s *_r = new %s(", ctorindex,
1064                     cdef->classname.constData(), cdef->classname.constData());
1065             const FunctionDef &f = cdef->constructorList.at(ctorindex);
1066             int offset = 1;
1067             for (int j = 0; j < f.arguments.count(); ++j) {
1068                 const ArgumentDef &a = f.arguments.at(j);
1069                 if (j)
1070                     fprintf(out, ",");
1071                 fprintf(out, "(*reinterpret_cast< %s>(_a[%d]))", a.typeNameForCast.constData(), offset++);
1072             }
1073             fprintf(out, ");\n");
1074             fprintf(out, "            if (_a[0]) *reinterpret_cast<QObject**>(_a[0]) = _r; } break;\n");
1075         }
1076         fprintf(out, "        }\n");
1077         fprintf(out, "    }");
1078         needElse = true;
1079         isUsed_a = true;
1080     }
1081
1082     QList<FunctionDef> methodList;
1083     methodList += cdef->signalList;
1084     methodList += cdef->slotList;
1085     methodList += cdef->methodList;
1086
1087     if (!methodList.isEmpty()) {
1088         if (needElse)
1089             fprintf(out, " else ");
1090         else
1091             fprintf(out, "    ");
1092         fprintf(out, "if (_c == QMetaObject::InvokeMetaMethod) {\n");
1093 #ifndef QT_NO_DEBUG
1094         fprintf(out, "        Q_ASSERT(staticMetaObject.cast(_o));\n");
1095 #endif
1096         fprintf(out, "        %s *_t = static_cast<%s *>(_o);\n", cdef->classname.constData(), cdef->classname.constData());
1097         fprintf(out, "        switch (_id) {\n");
1098         for (int methodindex = 0; methodindex < methodList.size(); ++methodindex) {
1099             const FunctionDef &f = methodList.at(methodindex);
1100             fprintf(out, "        case %d: ", methodindex);
1101             if (f.normalizedType.size())
1102                 fprintf(out, "{ %s _r = ", noRef(f.normalizedType).constData());
1103             fprintf(out, "_t->");
1104             if (f.inPrivateClass.size())
1105                 fprintf(out, "%s->", f.inPrivateClass.constData());
1106             fprintf(out, "%s(", f.name.constData());
1107             int offset = 1;
1108             for (int j = 0; j < f.arguments.count(); ++j) {
1109                 const ArgumentDef &a = f.arguments.at(j);
1110                 if (j)
1111                     fprintf(out, ",");
1112                 fprintf(out, "(*reinterpret_cast< %s>(_a[%d]))",a.typeNameForCast.constData(), offset++);
1113                 isUsed_a = true;
1114             }
1115             fprintf(out, ");");
1116             if (f.normalizedType.size()) {
1117                 fprintf(out, "\n            if (_a[0]) *reinterpret_cast< %s*>(_a[0]) = _r; } ",
1118                         noRef(f.normalizedType).constData());
1119                 isUsed_a = true;
1120             }
1121             fprintf(out, " break;\n");
1122         }
1123         fprintf(out, "        default: ;\n");
1124         fprintf(out, "        }\n");
1125         fprintf(out, "    }");
1126         needElse = true;
1127     }
1128     if (!cdef->signalList.isEmpty()) {
1129         Q_ASSERT(needElse); // if there is signal, there was method.
1130         fprintf(out, " else if (_c == QMetaObject::IndexOfMethod) {\n");
1131         fprintf(out, "        int *result = reinterpret_cast<int *>(_a[0]);\n");
1132         fprintf(out, "        void **func = reinterpret_cast<void **>(_a[1]);\n");
1133         bool anythingUsed = false;
1134         for (int methodindex = 0; methodindex < cdef->signalList.size(); ++methodindex) {
1135             const FunctionDef &f = cdef->signalList.at(methodindex);
1136             if (f.wasCloned || !f.inPrivateClass.isEmpty() || f.isStatic)
1137                 continue;
1138             anythingUsed = true;
1139             fprintf(out, "        {\n");
1140             fprintf(out, "            typedef %s (%s::*_t)(",f.type.rawName.constData() , cdef->classname.constData());
1141             for (int j = 0; j < f.arguments.count(); ++j) {
1142                 const ArgumentDef &a = f.arguments.at(j);
1143                 if (j)
1144                     fprintf(out, ", ");
1145                 fprintf(out, "%s", QByteArray(a.type.name + ' ' + a.rightType).constData());
1146             }
1147             if (f.isConst)
1148                 fprintf(out, ") const;\n");
1149             else
1150                 fprintf(out, ");\n");
1151             fprintf(out, "            if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&%s::%s)) {\n",
1152                     cdef->classname.constData(), f.name.constData());
1153             fprintf(out, "                *result = %d;\n", methodindex);
1154             fprintf(out, "            }\n        }\n");
1155         }
1156         if (!anythingUsed)
1157             fprintf(out, "        Q_UNUSED(result);\n        Q_UNUSED(func);\n");
1158         fprintf(out, "    }");
1159         needElse = true;
1160     }
1161
1162     if (needElse)
1163         fprintf(out, "\n");
1164
1165     if (methodList.isEmpty()) {
1166         fprintf(out, "    Q_UNUSED(_o);\n");
1167         if (cdef->constructorList.isEmpty()) {
1168             fprintf(out, "    Q_UNUSED(_id);\n");
1169             fprintf(out, "    Q_UNUSED(_c);\n");
1170         }
1171     }
1172     if (!isUsed_a)
1173         fprintf(out, "    Q_UNUSED(_a);\n");
1174
1175     fprintf(out, "}\n\n");
1176 }
1177
1178 void Generator::generateSignal(FunctionDef *def,int index)
1179 {
1180     if (def->wasCloned || def->isAbstract)
1181         return;
1182     fprintf(out, "\n// SIGNAL %d\n%s %s::%s(",
1183             index, def->type.name.constData(), cdef->qualified.constData(), def->name.constData());
1184
1185     QByteArray thisPtr = "this";
1186     const char *constQualifier = "";
1187
1188     if (def->isConst) {
1189         thisPtr = "const_cast< ";
1190         thisPtr += cdef->qualified;
1191         thisPtr += " *>(this)";
1192         constQualifier = "const";
1193     }
1194
1195     if (def->arguments.isEmpty() && def->normalizedType.isEmpty()) {
1196         fprintf(out, ")%s\n{\n"
1197                 "    QMetaObject::activate(%s, &staticMetaObject, %d, 0);\n"
1198                 "}\n", constQualifier, thisPtr.constData(), index);
1199         return;
1200     }
1201
1202     int offset = 1;
1203     for (int j = 0; j < def->arguments.count(); ++j) {
1204         const ArgumentDef &a = def->arguments.at(j);
1205         if (j)
1206             fprintf(out, ", ");
1207         fprintf(out, "%s _t%d%s", a.type.name.constData(), offset++, a.rightType.constData());
1208     }
1209     fprintf(out, ")%s\n{\n", constQualifier);
1210     if (def->type.name.size() && def->normalizedType.size())
1211         fprintf(out, "    %s _t0 = %s();\n", noRef(def->normalizedType).constData(), noRef(def->normalizedType).constData());
1212
1213     fprintf(out, "    void *_a[] = { ");
1214     if (def->normalizedType.isEmpty()) {
1215         fprintf(out, "0");
1216     } else {
1217         if (def->returnTypeIsVolatile)
1218              fprintf(out, "const_cast<void*>(reinterpret_cast<const volatile void*>(&_t0))");
1219         else
1220              fprintf(out, "const_cast<void*>(reinterpret_cast<const void*>(&_t0))");
1221     }
1222     int i;
1223     for (i = 1; i < offset; ++i)
1224         if (def->arguments.at(i - 1).type.isVolatile)
1225             fprintf(out, ", const_cast<void*>(reinterpret_cast<const volatile void*>(&_t%d))", i);
1226         else
1227             fprintf(out, ", const_cast<void*>(reinterpret_cast<const void*>(&_t%d))", i);
1228     fprintf(out, " };\n");
1229     fprintf(out, "    QMetaObject::activate(%s, &staticMetaObject, %d, _a);\n", thisPtr.constData(), index);
1230     if (def->normalizedType.size())
1231         fprintf(out, "    return _t0;\n");
1232     fprintf(out, "}\n");
1233 }
1234
1235 static void writePluginMetaData(FILE *out, const QJsonObject &data)
1236 {
1237     const QJsonDocument doc(data);
1238
1239     fputs("\nQT_PLUGIN_METADATA_SECTION\n"
1240           "static const unsigned char qt_pluginMetaData[] = {\n"
1241           "    'Q', 'T', 'M', 'E', 'T', 'A', 'D', 'A', 'T', 'A', ' ', ' ',\n   ", out);
1242 #if 0
1243     fprintf(out, "\"%s\";\n", doc.toJson().constData());
1244 #else
1245     const QByteArray binary = doc.toBinaryData();
1246     const int last = binary.size() - 1;
1247     for (int i = 0; i < last; ++i) {
1248         fprintf(out, " 0x%02x,", (uchar)binary.at(i));
1249         if (!((i + 1) % 8))
1250             fputs("\n   ", out);
1251     }
1252     fprintf(out, " 0x%02x\n};\n", (uchar)binary.at(last));
1253 #endif
1254 }
1255
1256 void Generator::generatePluginMetaData()
1257 {
1258     if (cdef->pluginData.iid.isEmpty())
1259         return;
1260
1261     // Write plugin meta data #ifdefed QT_NO_DEBUG with debug=false,
1262     // true, respectively.
1263
1264     QJsonObject data;
1265     const QString debugKey = QStringLiteral("debug");
1266     data.insert(QStringLiteral("IID"), QLatin1String(cdef->pluginData.iid.constData()));
1267     data.insert(QStringLiteral("className"), QLatin1String(cdef->classname.constData()));
1268     data.insert(QStringLiteral("version"), (int)QT_VERSION);
1269     data.insert(debugKey, QJsonValue(false));
1270     data.insert(QStringLiteral("MetaData"), cdef->pluginData.metaData.object());
1271
1272     fputs("\nQT_PLUGIN_METADATA_SECTION const uint qt_section_alignment_dummy = 42;\n\n"
1273           "#ifdef QT_NO_DEBUG\n", out);
1274     writePluginMetaData(out, data);
1275
1276     fputs("\n#else // QT_NO_DEBUG\n", out);
1277
1278     data.remove(debugKey);
1279     data.insert(debugKey, QJsonValue(true));
1280     writePluginMetaData(out, data);
1281
1282     fputs("#endif // QT_NO_DEBUG\n\n", out);
1283
1284     // 'Use' all namespaces.
1285     int pos = cdef->qualified.indexOf("::");
1286     for ( ; pos != -1 ; pos = cdef->qualified.indexOf("::", pos + 2) )
1287         fprintf(out, "using namespace %s;\n", cdef->qualified.left(pos).constData());
1288     fprintf(out, "QT_MOC_EXPORT_PLUGIN(%s)\n\n", cdef->classname.constData());
1289 }
1290
1291 QT_END_NAMESPACE