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
298 return string.visit([seed](
auto view) {
299 if constexpr (std::is_same_v<
decltype(view), QStringView>)
300 return qHash(view, seed);
301 if constexpr (std::is_same_v<
decltype(view), QLatin1StringView>)
302 return qHash(view, seed);
303 if constexpr (std::is_same_v<
decltype(view), QUtf8StringView>)
304 return qHash(QByteArrayView(view.data(), view.length()), seed);
310 return a.qualifiedClassName() < b.qualifiedClassName();
321 case TypeRelation::Property:
return "property"_L1;
322 case TypeRelation::Argument:
return "argument"_L1;
323 case TypeRelation::Return:
return "return"_L1;
324 case TypeRelation::Enum:
return "enum"_L1;
325 case TypeRelation::Attached:
return "attached"_L1;
326 case TypeRelation::SequenceValue:
return "sequence value"_L1;
327 case TypeRelation::Extension:
return "extension"_L1;
332 Q_UNREACHABLE_RETURN(QLatin1StringView());
337 QSet<QAnyStringView> processedRelatedNativeNames;
338 QSet<QAnyStringView> processedRelatedJavaScriptNames;
339 QSet<QAnyStringView> unresolvedForeignNames;
340 QQueue<MetaType> typeQueue;
341 typeQueue.append(m_types);
343 const auto addRelatedName
344 = [&](QAnyStringView relatedName,
const QList<QAnyStringView> &namespaces) {
345 if (
const FoundType related = QmlTypesClassDescription::findType(
346 m_types, m_foreignTypes, relatedName, namespaces)) {
349 processedRelatedJavaScriptNames.insert(related
.javaScript.qualifiedClassName());
352 processedRelatedNativeNames.insert(related
.native.qualifiedClassName());
360 const auto addRelatedType = [&](
const MetaType &type) {
361 const QAnyStringView qualifiedName = type.qualifiedClassName();
362 if (type.inputFile().isEmpty())
363 processedRelatedJavaScriptNames.insert(qualifiedName);
365 processedRelatedNativeNames.insert(qualifiedName);
369 for (
const MetaType &type : std::as_const(m_types)) {
370 addRelatedType(type);
371 for (
const ClassInfo &obj : type.classInfos()) {
372 if (obj.name == S_FOREIGN) {
373 const QAnyStringView foreign = obj.value;
374 if (!addRelatedName(foreign, namespaces(type)))
375 unresolvedForeignNames.insert(foreign);
383 for (
const MetaType &foreignType : std::as_const(m_foreignTypes)) {
384 bool seenQmlPrefix =
false;
385 for (
const ClassInfo &obj : foreignType.classInfos()) {
386 const QAnyStringView name = obj.name;
387 if (!seenQmlPrefix && startsWith(name,
"QML."_L1)) {
388 addRelatedType(foreignType);
389 seenQmlPrefix =
true;
391 if (name == S_FOREIGN
392 || name == S_EXTENDED
393 || name == S_ATTACHED
394 || name == S_SEQUENCE) {
395 ResolvedTypeAlias foreign(obj.value, m_usingDeclarations);
396 if (!addRelatedName(foreign.type, namespaces(foreignType)))
397 unresolvedForeignNames.insert(foreign.type);
402 const auto addReference
403 = [&](
const MetaType &type, QSet<QAnyStringView> *processedRelatedNames,
407 QAnyStringView qualifiedName = type.qualifiedClassName();
408 m_referencedTypes.append(qualifiedName);
409 const qsizetype size = processedRelatedNames->size();
410 processedRelatedNames->insert(qualifiedName);
412 if (processedRelatedNames->size() == size)
415 typeQueue.enqueue(type);
421 const auto insert = std::lower_bound(
422 m_types.constBegin(), m_types.constEnd(), type,
423 qualifiedClassNameLessThan);
424 m_types.insert(insert, type);
431 const auto remove = std::equal_range(
432 m_foreignTypes.constBegin(), m_foreignTypes.constEnd(), type,
433 qualifiedClassNameLessThan);
434 for (
auto it = remove.first; it != remove.second; ++it) {
436 m_foreignTypes.erase(it);
442 const auto addInterface
443 = [&](QAnyStringView typeName,
const QList<QAnyStringView> &namespaces) {
444 if (
const FoundType other = QmlTypesClassDescription::findType(
445 m_types, m_foreignTypes, typeName, namespaces)) {
453 unresolvedForeignNames.insert(typeName);
456 processedRelatedNativeNames.insert(typeName);
460 const auto doAddReferences = [&](QAnyStringView typeName,
461 const QList<QAnyStringView> &namespaces) {
462 if (
const FoundType other = QmlTypesClassDescription::findType(
463 m_types, m_foreignTypes, typeName, namespaces)) {
473 const auto addType = [&](
const MetaType &context, QAnyStringView typeName,
474 const QList<QAnyStringView> &namespaces,
TypeRelation relation) {
475 if (doAddReferences(typeName, namespaces))
479 const QLatin1StringView separator(
"::");
480 if (
const qsizetype index = lastIndexOf(typeName, separator); index > 0) {
481 if (
const FoundType other = QmlTypesClassDescription::findType(
482 m_types, m_foreignTypes, typeName.left(index), namespaces)) {
484 const QAnyStringView enumName = typeName.mid(index + separator.length());
486 for (
const Enum &enumerator : other.native.enums()) {
487 if (enumerator.name != enumName && enumerator.alias != enumName)
490 addReference(other.native, &processedRelatedNativeNames, other.nativeOrigin);
492 other.javaScript, &processedRelatedJavaScriptNames,
493 other.javaScriptOrigin);
500 for (
const Enum &enumerator : context.enums()) {
501 if (enumerator.name == typeName || enumerator.alias == typeName)
508 if (!unresolvedForeignNames.contains(typeName) && !isPrimitive(typeName)) {
509 warning(context) << typeName <<
"is used as" << typeRelationString(relation)
510 <<
"type but cannot be found.";
513 processedRelatedNativeNames.insert(typeName);
514 processedRelatedJavaScriptNames.insert(typeName);
520 const auto addSupers = [&](
const MetaType &context,
const QList<QAnyStringView> &namespaces) {
521 for (
const Interface &iface : context.ifaces())
522 addInterface(interfaceName(iface), namespaces);
525 bool warnAboutSupers = context.kind() != MetaType::Kind::Gadget;
527 QList<QAnyStringView> missingSupers;
529 for (
const BaseType &superObject : context.superClasses()) {
530 if (superObject.access != Access::Public)
533 QAnyStringView typeName = superObject.name;
534 if (doAddReferences(typeName, namespaces))
535 warnAboutSupers =
false;
537 missingSupers.append(typeName);
540 for (QAnyStringView typeName : std::as_const(missingSupers)) {
543 && !unresolvedForeignNames.contains(typeName)
544 && !isPrimitive(typeName)) {
545 warning(context) << typeName <<
"is used as base type but cannot be found.";
548 processedRelatedNativeNames.insert(typeName);
549 processedRelatedJavaScriptNames.insert(typeName);
553 const auto addEnums = [&](
const MetaType &context,
554 const QList<QAnyStringView> &namespaces) {
555 for (
const Enum &enumerator : context.enums()) {
556 ResolvedTypeAlias resolved(enumerator.type, m_usingDeclarations);
557 if (!resolved.type.isEmpty())
558 addType(context, resolved.type, namespaces, TypeRelation::Enum);
563 const QList<QAnyStringView> &namespaces) {
564 const QAnyStringView objNameValue = obj.name;
565 if (objNameValue == S_ATTACHED) {
568 }
else if (objNameValue == S_SEQUENCE) {
572 }
else if (objNameValue == S_EXTENDED) {
573 const QAnyStringView value = obj.value;
582 while (!typeQueue.isEmpty()) {
583 QAnyStringView unresolvedForeign;
585 const MetaType classDef = typeQueue.dequeue();
586 const QList<QAnyStringView> namespaces = MetaTypesJsonProcessor::namespaces(classDef);
588 for (
const ClassInfo &obj : classDef.classInfos()) {
589 if (addRelation(classDef, obj, namespaces))
591 if (obj.name != S_FOREIGN)
594 const QAnyStringView foreignClassName = obj.value;
598 if (
const FoundType found = QmlTypesClassDescription::findType(
599 m_foreignTypes, {}, foreignClassName, namespaces)) {
600 const MetaType other = found.select(classDef,
"Foreign");
601 const QList<QAnyStringView> otherNamespaces
602 = MetaTypesJsonProcessor::namespaces(other);
603 addSupers(other, otherNamespaces);
604 addEnums(other, otherNamespaces);
606 for (
const ClassInfo &obj : other.classInfos()) {
607 if (addRelation(classDef, obj, otherNamespaces))
611 }
else if (!QmlTypesClassDescription::findType(
612 m_types, {}, foreignClassName, namespaces)) {
613 unresolvedForeign = foreignClassName;
617 if (!unresolvedForeign.isEmpty() && !isPrimitive(unresolvedForeign)) {
620 <<
"is declared as foreign type, but cannot be found.";
623 addSupers(classDef, namespaces);
624 addEnums(classDef, namespaces);
630 std::sort(types.begin(), types.end(), qualifiedClassNameLessThan);
635 if (!m_privateIncludes)
636 return include.toString();
638 if (endsWith(include,
"_p.h"_L1))
639 return QLatin1String(
"private/") + include.toString();
641 if (startsWith(include,
"qplatform"_L1) || startsWith(include,
"qwindowsystem"_L1))
642 return QLatin1String(
"qpa/") + include.toString();
644 return include.toString();
649 const QString include = resolvedInclude(types[S_INPUT_FILE].toStringView());
650 const QCborArray classes = types[S_CLASSES].toArray();
651 for (
const QCborValue &cls : classes) {
652 const MetaType classDef(cls.toMap(), include);
654 const PreProcessResult preprocessed = preProcess(classDef, PopulateMode::Yes);
655 switch (preprocessed.mode) {
656 case NamespaceRegistration:
657 case GadgetRegistration:
658 case ObjectRegistration: {
659 if (!endsWith(include, QLatin1String(
".h"))
660 && !endsWith(include, QLatin1String(
".hpp"))
661 && !endsWith(include, QLatin1String(
".hxx"))
662 && !endsWith(include, QLatin1String(
".hh"))
663 && !endsWith(include, QLatin1String(
".py"))
664 && contains(include, QLatin1Char(
'.'))) {
666 <<
"Class" << classDef.qualifiedClassName()
667 <<
"is declared in" << include <<
"which appears not to be a header."
668 <<
"The compilation of its registration to QML may fail.";
670 m_includes.append(include);
671 m_types.emplaceBack(classDef);
675 m_foreignTypes.emplaceBack(classDef);
679 if (!preprocessed.foreignPrimitive.isEmpty()) {
680 m_primitiveTypes.emplaceBack(preprocessed.foreignPrimitive);
681 m_primitiveTypes.append(preprocessed.primitiveAliases);
684 if (preprocessed.usingDeclaration.isValid())
685 m_usingDeclarations.append(preprocessed.usingDeclaration);
691 const QString include = resolvedInclude(types[S_INPUT_FILE].toStringView());
692 const QCborArray classes = types[S_CLASSES].toArray();
693 for (
const QCborValue &cls : classes) {
694 const MetaType classDef(cls.toMap(), include);
695 PreProcessResult preprocessed = preProcess(classDef, PopulateMode::No);
697 m_foreignTypes.emplaceBack(classDef);
698 if (!preprocessed.foreignPrimitive.isEmpty()) {
699 m_primitiveTypes.emplaceBack(preprocessed.foreignPrimitive);
700 m_primitiveTypes.append(preprocessed.primitiveAliases);
703 if (preprocessed.usingDeclaration.isValid())
704 m_usingDeclarations.append(preprocessed.usingDeclaration);
710 const auto it = cbor.find(S_REVISION);
711 return it == cbor.end()
713 : QTypeRevision::fromEncodedVersion(it->toInteger());
718 const QAnyStringView access = cbor[S_ACCESS].toStringView();
719 if (access == S_PUBLIC)
721 if (access == S_PROTECTED)
740 if (cbor.isArray()) {
741 QCborArray needlessWrapping = cbor.toArray();
742 className = needlessWrapping.size() > 0
743 ? needlessWrapping[0].toMap()[S_CLASS_NAME].toStringView()
746 className = cbor.toMap()[S_CLASS_NAME].toStringView();
760 ,
index(cbor[S_INDEX].toInteger(-1))
763 ,
isFinal(cbor[S_FINAL].toBool())
784 ,
isCloned(cbor[S_IS_CLONED].toBool())
786 ,
isConstructor(isConstructor || cbor[S_IS_CONSTRUCTOR].toBool())
787 ,
isConst(cbor[S_IS_CONST].toBool())
789 const QCborArray args = cbor[S_ARGUMENTS].toArray();
790 for (
const QCborValue &argument : args)
791 arguments.emplace_back(argument.toMap());
793 if (arguments.size() == 1) {
794 const QAnyStringView type = arguments[0].type;
795 if (type ==
"QQmlV4FunctionPtr"_L1 || type ==
"QQmlV4Function*"_L1) {
807 ,
isFlag(cbor[S_IS_FLAG].toBool())
808 ,
isClass(cbor[S_IS_CLASS].toBool())
810 const QCborArray vals = cbor[S_VALUES].toArray();
811 for (
const QCborValue &value : vals)
812 values.emplace_back(value.toStringView());
819 className = cbor[S_CLASS_NAME].toStringView();
821 qualifiedClassName = cbor[S_QUALIFIED_CLASS_NAME].toStringView();
823 const QCborArray cborSuperClasses = cbor[S_SUPER_CLASSES].toArray();
824 for (
const QCborValue &superClass : cborSuperClasses)
825 superClasses.emplace_back(superClass.toMap());
827 const QCborArray cborClassInfos = cbor[S_CLASS_INFOS].toArray();
828 for (
const QCborValue &classInfo : cborClassInfos)
829 classInfos.emplace_back(classInfo.toMap());
831 const QCborArray cborIfaces = cbor[S_INTERFACES].toArray();
832 for (
const QCborValue &iface : cborIfaces)
833 ifaces.emplace_back(iface);
835 const QCborArray cborProperties = cbor[S_PROPERTIES].toArray();
836 for (
const QCborValue &property : cborProperties)
837 properties.emplace_back(property.toMap());
839 for (
const QCborArray &cborMethods : { cbor[S_SLOTS].toArray(), cbor[S_METHODS].toArray() }) {
840 for (
const QCborValue &method : cborMethods)
841 methods.emplace_back(method.toMap(),
false);
844 const QCborArray cborSigs = cbor[S_SIGNALS].toArray();
845 for (
const QCborValue &sig : cborSigs)
846 sigs.emplace_back(sig.toMap(),
false);
848 const QCborArray cborConstructors = cbor[S_CONSTRUCTORS].toArray();
849 for (
const QCborValue &constructor : cborConstructors)
850 constructors.emplace_back(constructor.toMap(),
true);
852 const QCborArray cborEnums = cbor[S_ENUMS].toArray();
853 for (
const QCborValue &enumerator : cborEnums)
854 enums.emplace_back(enumerator.toMap());
856 if (cbor[S_GADGET].toBool())
858 else if (cbor[S_OBJECT].toBool())
860 else if (cbor[S_NAMESPACE].toBool())
861 kind = Kind::Namespace;
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)