13#include <QtCore/qcborarray.h>
14#include <QtCore/qcbormap.h>
15#include <QtCore/qdir.h>
16#include <QtCore/qfile.h>
17#include <QtCore/qjsondocument.h>
18#include <QtCore/qqueue.h>
22using namespace Qt::StringLiterals;
31std::vector<std::unique_ptr<MetaTypePrivate>> s_pool;
35 const QJsonDocument jsonValue = QJsonDocument::fromJson(json, error);
36 if (jsonValue.isArray())
37 return QCborValue::fromJsonValue(jsonValue.array());
38 if (jsonValue.isObject())
39 return QCborValue::fromJsonValue(jsonValue.object());
45 const QAnyStringView unqualified = classDef.className();
46 const QAnyStringView qualified = classDef.qualifiedClassName();
48 QList<QAnyStringView> namespaces;
49 if (qualified != unqualified) {
50 namespaces = split(qualified,
"::"_L1);
51 Q_ASSERT(namespaces.last() == unqualified);
52 namespaces.pop_back();
60 for (
const QString &source: files) {
61 if (m_seenMetaTypesFiles.hasSeen(QDir::cleanPath(source)))
64 QCborValue metaObjects;
67 if (!f.open(QIODevice::ReadOnly)) {
68 error(source) <<
"Cannot open file for reading";
71 QJsonParseError parseError = {0, QJsonParseError::NoError};
72 metaObjects = fromJson(f.readAll(), &parseError);
73 if (parseError.error != QJsonParseError::NoError) {
75 <<
"Failed to parse JSON:" << parseError.error
76 << parseError.errorString();
81 if (metaObjects.isArray()) {
82 const QCborArray metaObjectsArray = metaObjects.toArray();
83 for (
const QCborValue &metaObject : metaObjectsArray) {
84 if (!metaObject.isMap()) {
85 error(source) <<
"JSON is not an object";
89 processTypes(metaObject.toMap());
91 }
else if (metaObjects.isMap()) {
92 processTypes(metaObjects.toMap());
94 error(source) <<
"JSON is not an object or an array";
104 QFile typesFile(types);
105 if (!typesFile.open(QIODevice::ReadOnly)) {
106 error(types) <<
"Cannot open foreign types file";
110 QJsonParseError parseError = {0, QJsonParseError::NoError};
111 QCborValue foreignMetaObjects = fromJson(typesFile.readAll(), &parseError);
112 if (parseError.error != QJsonParseError::NoError) {
114 <<
"Failed to parse JSON:" << parseError.error
115 << parseError.errorString();
119 const QCborArray foreignObjectsArray = foreignMetaObjects.toArray();
120 for (
const QCborValue &metaObject : foreignObjectsArray) {
121 if (!metaObject.isMap()) {
122 error(types) <<
"JSON is not an object";
126 processForeignTypes(metaObject.toMap());
136 for (
const QString &types : foreignTypesFiles) {
137 if (m_seenMetaTypesFiles.hasSeen(QDir::cleanPath(types)))
140 if (!processForeignTypes(types))
146template<
typename String>
149 std::sort(list->begin(), list->end());
150 const auto newEnd = std::unique(list->begin(), list->end());
151 list->erase(
typename QList<String>::const_iterator(newEnd), list->constEnd());
161 sortTypes(m_foreignTypes);
162 sortStringList(&m_primitiveTypes);
163 sortStringList(&m_usingDeclarations);
165 sortStringList(&m_referencedTypes);
166 sortStringList(&m_includes);
171 QString registrationHelper;
172 for (
const auto &obj: m_types) {
173 const QString className = obj.className().toString();
174 const QString qualifiedClassName = obj.qualifiedClassName().toString();
175 const QString foreignClassName = className + u"Foreign";
176 QStringList qmlElements;
177 QString qmlUncreatable;
179 bool isSingleton =
false;
180 bool isExplicitlyUncreatable =
false;
181 bool isNamespace = obj.kind() == MetaType::Kind::Namespace;
182 for (
const ClassInfo &entry: obj.classInfos()) {
183 const auto name = entry.name;
184 const auto value = entry.value;
185 if (name == S_ELEMENT) {
186 if (value == S_AUTO) {
187 qmlElements.append(u"QML_NAMED_ELEMENT("_s + className + u")"_s);
188 }
else if (value == S_ANONYMOUS) {
189 qmlElements.append(u"QML_ANONYMOUS"_s);
191 qmlElements.append(u"QML_NAMED_ELEMENT("_s + value.toString() + u")");
193 }
else if (name == S_CREATABLE && value == S_FALSE) {
194 isExplicitlyUncreatable =
true;
195 }
else if (name == S_UNCREATABLE_REASON) {
196 qmlUncreatable = u"QML_UNCREATABLE(\""_s + value.toString() + u"\")";
197 }
else if (name == S_ATTACHED) {
198 qmlAttached = u"QML_ATTACHED("_s + value.toString() + u")";
199 }
else if (name == S_SINGLETON) {
203 if (qmlElements.isEmpty())
205 const QString spaces = u" "_s;
207 registrationHelper += u"\nnamespace "_s + foreignClassName + u"{\n Q_NAMESPACE\n"_s;
208 registrationHelper += spaces + u"QML_FOREIGN_NAMESPACE(" + qualifiedClassName + u")\n"_s;
210 registrationHelper += u"\nstruct "_s + foreignClassName + u"{\n Q_GADGET\n"_s;
211 registrationHelper += spaces + u"QML_FOREIGN(" + qualifiedClassName + u")\n"_s;
213 registrationHelper += spaces + qmlElements.join(u"\n"_s) + u"\n"_s;
215 registrationHelper += spaces + u"QML_SINGLETON\n"_s;
216 if (isExplicitlyUncreatable) {
217 if (qmlUncreatable.isEmpty())
218 registrationHelper += spaces + uR"(QML_UNCREATABLE(""))" + u"n";
220 registrationHelper += spaces + qmlUncreatable + u"\n";
222 if (!qmlAttached.isEmpty())
223 registrationHelper += spaces + qmlAttached + u"\n";
224 registrationHelper += u"}";
226 registrationHelper += u";";
227 registrationHelper += u"\n";
229 return registrationHelper;
233 const MetaType &classDef, PopulateMode populateMode)
239 QList<QAnyStringView> primitiveAliases;
242 RegistrationMode mode = NoRegistration;
243 bool isSelfExtendingValueType =
false;
244 bool hasJavaScriptExtension =
false;
245 bool isRootObject =
false;
246 bool isSequence =
false;
248 for (
const ClassInfo &classInfo : classDef.classInfos()) {
249 if (classInfo.name == S_FOREIGN)
250 usingDeclaration.alias = classInfo.value;
251 else if (classInfo.name == S_PRIMITIVE_ALIAS)
252 primitiveAliases.append(classInfo.value);
253 else if (classInfo.name == S_EXTENSION_IS_JAVA_SCRIPT)
254 hasJavaScriptExtension = (classInfo.value == S_TRUE);
255 else if (classInfo.name == S_EXTENDED && classDef.kind() == MetaType::Kind::Gadget)
256 isSelfExtendingValueType = classInfo.value == classDef.className();
257 else if (classInfo.name == S_ROOT)
258 isRootObject = (classInfo.value == S_TRUE);
259 else if (classInfo.name == S_SEQUENCE)
261 else if (classInfo.name == S_USING)
262 usingDeclaration.original = classInfo.value;
263 else if (populateMode == PopulateMode::Yes && classInfo.name == S_ELEMENT) {
264 switch (classDef.kind()) {
265 case MetaType::Kind::Object:
266 mode = ObjectRegistration;
268 case MetaType::Kind::Gadget:
269 mode = GadgetRegistration;
271 case MetaType::Kind::Namespace:
272 mode = NamespaceRegistration;
276 <<
"Not registering a classInfo which is neither an object,"
277 <<
"nor a gadget, nor a namespace:"
278 << classInfo.name.toString();
284 return PreProcessResult {
285 std::move(primitiveAliases),
287 (!isRootObject && (isSequence || isSelfExtendingValueType || hasJavaScriptExtension))
288 ? usingDeclaration.alias
297 return a.qualifiedClassName() < b.qualifiedClassName();
308 case TypeRelation::Property:
return "property"_L1;
309 case TypeRelation::Argument:
return "argument"_L1;
310 case TypeRelation::Return:
return "return"_L1;
311 case TypeRelation::Enum:
return "enum"_L1;
312 case TypeRelation::Attached:
return "attached"_L1;
313 case TypeRelation::SequenceValue:
return "sequence value"_L1;
314 case TypeRelation::Extension:
return "extension"_L1;
319 Q_UNREACHABLE_RETURN(QLatin1StringView());
324 QSet<QAnyStringView> processedRelatedNativeNames;
325 QSet<QAnyStringView> processedRelatedJavaScriptNames;
326 QSet<QAnyStringView> unresolvedForeignNames;
327 QQueue<MetaType> typeQueue;
328 typeQueue.append(m_types);
330 const auto addRelatedName
331 = [&](QAnyStringView relatedName,
const QList<QAnyStringView> &namespaces) {
332 if (
const FoundType related = QmlTypesClassDescription::findType(
333 m_types, m_foreignTypes, relatedName, namespaces)) {
336 processedRelatedJavaScriptNames.insert(related
.javaScript.qualifiedClassName());
339 processedRelatedNativeNames.insert(related
.native.qualifiedClassName());
347 const auto addRelatedType = [&](
const MetaType &type) {
348 const QAnyStringView qualifiedName = type.qualifiedClassName();
349 if (type.inputFile().isEmpty())
350 processedRelatedJavaScriptNames.insert(qualifiedName);
352 processedRelatedNativeNames.insert(qualifiedName);
356 for (
const MetaType &type : std::as_const(m_types)) {
357 addRelatedType(type);
358 for (
const ClassInfo &obj : type.classInfos()) {
359 if (obj.name == S_FOREIGN) {
360 const QAnyStringView foreign = obj.value;
361 if (!addRelatedName(foreign, namespaces(type)))
362 unresolvedForeignNames.insert(foreign);
370 for (
const MetaType &foreignType : std::as_const(m_foreignTypes)) {
371 bool seenQmlPrefix =
false;
372 for (
const ClassInfo &obj : foreignType.classInfos()) {
373 const QAnyStringView name = obj.name;
374 if (!seenQmlPrefix && startsWith(name,
"QML."_L1)) {
375 addRelatedType(foreignType);
376 seenQmlPrefix =
true;
378 if (name == S_FOREIGN
379 || name == S_EXTENDED
380 || name == S_ATTACHED
381 || name == S_SEQUENCE) {
382 ResolvedTypeAlias foreign(obj.value, m_usingDeclarations);
383 if (!addRelatedName(foreign.type, namespaces(foreignType)))
384 unresolvedForeignNames.insert(foreign.type);
389 const auto addReference
390 = [&](
const MetaType &type, QSet<QAnyStringView> *processedRelatedNames,
394 QAnyStringView qualifiedName = type.qualifiedClassName();
395 m_referencedTypes.append(qualifiedName);
396 const qsizetype size = processedRelatedNames->size();
397 processedRelatedNames->insert(qualifiedName);
399 if (processedRelatedNames->size() == size)
402 typeQueue.enqueue(type);
408 const auto insert = std::lower_bound(
409 m_types.constBegin(), m_types.constEnd(), type,
410 qualifiedClassNameLessThan);
411 m_types.insert(insert, type);
418 const auto remove = std::equal_range(
419 m_foreignTypes.constBegin(), m_foreignTypes.constEnd(), type,
420 qualifiedClassNameLessThan);
421 for (
auto it = remove.first; it != remove.second; ++it) {
423 m_foreignTypes.erase(it);
429 const auto addInterface
430 = [&](QAnyStringView typeName,
const QList<QAnyStringView> &namespaces) {
431 if (
const FoundType other = QmlTypesClassDescription::findType(
432 m_types, m_foreignTypes, typeName, namespaces)) {
440 unresolvedForeignNames.insert(typeName);
443 processedRelatedNativeNames.insert(typeName);
447 const auto doAddReferences = [&](QAnyStringView typeName,
448 const QList<QAnyStringView> &namespaces) {
449 if (
const FoundType other = QmlTypesClassDescription::findType(
450 m_types, m_foreignTypes, typeName, namespaces)) {
460 const auto addType = [&](
const MetaType &context, QAnyStringView typeName,
461 const QList<QAnyStringView> &namespaces,
TypeRelation relation) {
462 if (doAddReferences(typeName, namespaces))
466 const QLatin1StringView separator(
"::");
467 if (
const qsizetype index = lastIndexOf(typeName, separator); index > 0) {
468 if (
const FoundType other = QmlTypesClassDescription::findType(
469 m_types, m_foreignTypes, typeName.left(index), namespaces)) {
471 const QAnyStringView enumName = typeName.mid(index + separator.length());
473 for (
const Enum &enumerator : other.native.enums()) {
474 if (enumerator.name != enumName && enumerator.alias != enumName)
477 addReference(other.native, &processedRelatedNativeNames, other.nativeOrigin);
479 other.javaScript, &processedRelatedJavaScriptNames,
480 other.javaScriptOrigin);
487 for (
const Enum &enumerator : context.enums()) {
488 if (enumerator.name == typeName || enumerator.alias == typeName)
495 if (!unresolvedForeignNames.contains(typeName) && !isPrimitive(typeName)) {
496 warning(context) << typeName <<
"is used as" << typeRelationString(relation)
497 <<
"type but cannot be found.";
500 processedRelatedNativeNames.insert(typeName);
501 processedRelatedJavaScriptNames.insert(typeName);
507 const auto addSupers = [&](
const MetaType &context,
const QList<QAnyStringView> &namespaces) {
508 for (
const Interface &iface : context.ifaces())
509 addInterface(interfaceName(iface), namespaces);
512 bool warnAboutSupers = context.kind() != MetaType::Kind::Gadget;
514 QList<QAnyStringView> missingSupers;
516 for (
const BaseType &superObject : context.superClasses()) {
517 if (superObject.access != Access::Public)
520 QAnyStringView typeName = superObject.name;
521 if (doAddReferences(typeName, namespaces))
522 warnAboutSupers =
false;
524 missingSupers.append(typeName);
527 for (QAnyStringView typeName : std::as_const(missingSupers)) {
530 && !unresolvedForeignNames.contains(typeName)
531 && !isPrimitive(typeName)) {
532 warning(context) << typeName <<
"is used as base type but cannot be found.";
535 processedRelatedNativeNames.insert(typeName);
536 processedRelatedJavaScriptNames.insert(typeName);
540 const auto addEnums = [&](
const MetaType &context,
541 const QList<QAnyStringView> &namespaces) {
542 for (
const Enum &enumerator : context.enums()) {
543 ResolvedTypeAlias resolved(enumerator.type, m_usingDeclarations);
544 if (!resolved.type.isEmpty())
545 addType(context, resolved.type, namespaces, TypeRelation::Enum);
550 const QList<QAnyStringView> &namespaces) {
551 const QAnyStringView objNameValue = obj.name;
552 if (objNameValue == S_ATTACHED) {
555 }
else if (objNameValue == S_SEQUENCE) {
559 }
else if (objNameValue == S_EXTENDED) {
560 const QAnyStringView value = obj.value;
569 while (!typeQueue.isEmpty()) {
570 QAnyStringView unresolvedForeign;
572 const MetaType classDef = typeQueue.dequeue();
573 const QList<QAnyStringView> namespaces = MetaTypesJsonProcessor::namespaces(classDef);
575 for (
const ClassInfo &obj : classDef.classInfos()) {
576 if (addRelation(classDef, obj, namespaces))
578 if (obj.name != S_FOREIGN)
581 const QAnyStringView foreignClassName = obj.value;
585 if (
const FoundType found = QmlTypesClassDescription::findType(
586 m_foreignTypes, {}, foreignClassName, namespaces)) {
587 const MetaType other = found.select(classDef,
"Foreign");
588 const QList<QAnyStringView> otherNamespaces
589 = MetaTypesJsonProcessor::namespaces(other);
590 addSupers(other, otherNamespaces);
591 addEnums(other, otherNamespaces);
593 for (
const ClassInfo &obj : other.classInfos()) {
594 if (addRelation(classDef, obj, otherNamespaces))
599 m_foreignTypeMetaObjectHashes.insert(classDef.qualifiedClassName(),
600 found.native.metaObjectHash());
601 }
else if (!QmlTypesClassDescription::findType(
602 m_types, {}, foreignClassName, namespaces)) {
603 unresolvedForeign = foreignClassName;
607 if (!unresolvedForeign.isEmpty() && !isPrimitive(unresolvedForeign)) {
610 <<
"is declared as foreign type, but cannot be found.";
613 addSupers(classDef, namespaces);
614 addEnums(classDef, namespaces);
620 std::sort(types.begin(), types.end(), qualifiedClassNameLessThan);
625 if (!m_privateIncludes)
626 return include.toString();
628 if (endsWith(include,
"_p.h"_L1))
629 return QLatin1String(
"private/") + include.toString();
631 if (startsWith(include,
"qplatform"_L1) || startsWith(include,
"qwindowsystem"_L1))
632 return QLatin1String(
"qpa/") + include.toString();
634 return include.toString();
639 const QString include = resolvedInclude(types[S_INPUT_FILE].toStringView());
640 const QCborArray classes = types[S_CLASSES].toArray();
641 const QCborMap hashes = types[S_HASHES].toMap();
642 for (
const QCborValue &cls : classes) {
643 const MetaType classDef(cls.toMap(), include, hashes);
645 const PreProcessResult preprocessed = preProcess(classDef, PopulateMode::Yes);
646 switch (preprocessed.mode) {
647 case NamespaceRegistration:
648 case GadgetRegistration:
649 case ObjectRegistration: {
650 if (!endsWith(include, QLatin1String(
".h"))
651 && !endsWith(include, QLatin1String(
".hpp"))
652 && !endsWith(include, QLatin1String(
".hxx"))
653 && !endsWith(include, QLatin1String(
".hh"))
654 && !endsWith(include, QLatin1String(
".py"))
655 && contains(include, QLatin1Char(
'.'))) {
657 <<
"Class" << classDef.qualifiedClassName()
658 <<
"is declared in" << include <<
"which appears not to be a header."
659 <<
"The compilation of its registration to QML may fail.";
661 m_includes.append(include);
662 m_types.emplaceBack(classDef);
666 m_foreignTypes.emplaceBack(classDef);
670 if (!preprocessed.foreignPrimitive.isEmpty()) {
671 m_primitiveTypes.emplaceBack(preprocessed.foreignPrimitive);
672 m_primitiveTypes.append(preprocessed.primitiveAliases);
675 if (preprocessed.usingDeclaration.isValid())
676 m_usingDeclarations.append(preprocessed.usingDeclaration);
682 const QString include = resolvedInclude(types[S_INPUT_FILE].toStringView());
683 const QCborArray classes = types[S_CLASSES].toArray();
684 const QCborMap hashes = types[S_HASHES].toMap();
685 for (
const QCborValue &cls : classes) {
686 const MetaType classDef(cls.toMap(), include, hashes);
687 PreProcessResult preprocessed = preProcess(classDef, PopulateMode::No);
689 m_foreignTypes.emplaceBack(classDef);
690 if (!preprocessed.foreignPrimitive.isEmpty()) {
691 m_primitiveTypes.emplaceBack(preprocessed.foreignPrimitive);
692 m_primitiveTypes.append(preprocessed.primitiveAliases);
695 if (preprocessed.usingDeclaration.isValid())
696 m_usingDeclarations.append(preprocessed.usingDeclaration);
702 const auto it = cbor.find(S_REVISION);
703 return it == cbor.end()
705 : QTypeRevision::fromEncodedVersion(it->toInteger());
710 const QAnyStringView access = cbor[S_ACCESS].toStringView();
711 if (access == S_PUBLIC)
713 if (access == S_PROTECTED)
732 if (cbor.isArray()) {
733 QCborArray needlessWrapping = cbor.toArray();
734 className = needlessWrapping.size() > 0
735 ? needlessWrapping[0].toMap()[S_CLASS_NAME].toStringView()
738 className = cbor.toMap()[S_CLASS_NAME].toStringView();
752 ,
index(cbor[S_INDEX].toInteger(-1))
755 ,
isFinal(cbor[S_FINAL].toBool())
776 ,
isCloned(cbor[S_IS_CLONED].toBool())
778 ,
isConstructor(isConstructor || cbor[S_IS_CONSTRUCTOR].toBool())
779 ,
isConst(cbor[S_IS_CONST].toBool())
781 const QCborArray args = cbor[S_ARGUMENTS].toArray();
782 for (
const QCborValue &argument : args)
783 arguments.emplace_back(argument.toMap());
785 if (arguments.size() == 1) {
786 const QAnyStringView type = arguments[0].type;
787 if (type ==
"QQmlV4FunctionPtr"_L1 || type ==
"QQmlV4Function*"_L1) {
799 ,
isFlag(cbor[S_IS_FLAG].toBool())
800 ,
isClass(cbor[S_IS_CLASS].toBool())
802 const QCborArray vals = cbor[S_VALUES].toArray();
803 for (
const QCborValue &value : vals)
804 values.emplace_back(value.toStringView());
808 const QCborMap &hashes)
813 className = cbor[S_CLASS_NAME].toStringView();
815 const QCborValue &qualifiedClassNameCborValue = cbor[S_QUALIFIED_CLASS_NAME];
816 qualifiedClassName = qualifiedClassNameCborValue.toStringView();
818 const QCborArray cborSuperClasses = cbor[S_SUPER_CLASSES].toArray();
819 for (
const QCborValue &superClass : cborSuperClasses)
820 superClasses.emplace_back(superClass.toMap());
822 const QCborArray cborClassInfos = cbor[S_CLASS_INFOS].toArray();
823 for (
const QCborValue &classInfo : cborClassInfos)
824 classInfos.emplace_back(classInfo.toMap());
826 const QCborArray cborIfaces = cbor[S_INTERFACES].toArray();
827 for (
const QCborValue &iface : cborIfaces)
828 ifaces.emplace_back(iface);
830 const QCborArray cborProperties = cbor[S_PROPERTIES].toArray();
831 for (
const QCborValue &property : cborProperties)
832 properties.emplace_back(property.toMap());
834 for (
const QCborArray &cborMethods : { cbor[S_SLOTS].toArray(), cbor[S_METHODS].toArray() }) {
835 for (
const QCborValue &method : cborMethods)
836 methods.emplace_back(method.toMap(),
false);
839 const QCborArray cborSigs = cbor[S_SIGNALS].toArray();
840 for (
const QCborValue &sig : cborSigs)
841 sigs.emplace_back(sig.toMap(),
false);
843 const QCborArray cborConstructors = cbor[S_CONSTRUCTORS].toArray();
844 for (
const QCborValue &constructor : cborConstructors)
845 constructors.emplace_back(constructor.toMap(),
true);
847 const QCborArray cborEnums = cbor[S_ENUMS].toArray();
848 for (
const QCborValue &enumerator : cborEnums)
849 enums.emplace_back(enumerator.toMap());
851 if (cbor[S_GADGET].toBool())
853 else if (cbor[S_OBJECT].toBool())
855 else if (cbor[S_NAMESPACE].toBool())
856 kind = Kind::Namespace;
858 metaObjectHash = hashes.value(qualifiedClassNameCborValue).toStringView();
Combined button and popup list for selecting options.
QDebug warning(const MetaType &classDef)
Argument(const QCborMap &cbor)
BaseType(const QCborMap &cbor)
ClassInfo(const QCborMap &cbor)
Enum(const QCborMap &cbor)
Interface(const QCborValue &cbor)
bool isJavaScriptFunction
Method(const QCborMap &cbor, bool isConstructor)
static constexpr int InvalidIndex
Property(const QCborMap &cbor)