aboutsummaryrefslogtreecommitdiffstats
path: root/sources/shiboken2
diff options
context:
space:
mode:
authorFriedemann Kleint <Friedemann.Kleint@qt.io>2018-05-18 16:45:35 +0200
committerFriedemann Kleint <Friedemann.Kleint@qt.io>2018-05-18 16:45:35 +0200
commit3f8c8702ea295f39357e7c66f46e5138f56bcc9f (patch)
tree9ca65a7f94d544ba4b36f239c4a48852ad8a7b09 /sources/shiboken2
parent5fce76074c01e52a22151133a1e3a2cf71cfe535 (diff)
parentdf1a619d65d8e5db91f3c8db46b00872b461e334 (diff)
Merge remote-tracking branch 'origin/5.9' into 5.11
Diffstat (limited to 'sources/shiboken2')
-rw-r--r--sources/shiboken2/ApiExtractor/abstractmetabuilder.cpp40
-rw-r--r--sources/shiboken2/ApiExtractor/abstractmetalang.cpp25
-rw-r--r--sources/shiboken2/ApiExtractor/abstractmetalang.h6
-rw-r--r--sources/shiboken2/ApiExtractor/docparser.cpp7
-rw-r--r--sources/shiboken2/ApiExtractor/qtdocparser.cpp192
-rw-r--r--sources/shiboken2/ApiExtractor/qtdocparser.h9
-rw-r--r--sources/shiboken2/CMakeLists.txt4
-rw-r--r--sources/shiboken2/generator/qtdoc/qtdocgenerator.cpp77
-rw-r--r--sources/shiboken2/generator/shiboken2/shibokengenerator.cpp85
-rw-r--r--sources/shiboken2/generator/shiboken2/shibokengenerator.h3
-rw-r--r--sources/shiboken2/tests/libsample/objecttype.h4
-rw-r--r--sources/shiboken2/tests/samplebinding/enum_test.py8
12 files changed, 343 insertions, 117 deletions
diff --git a/sources/shiboken2/ApiExtractor/abstractmetabuilder.cpp b/sources/shiboken2/ApiExtractor/abstractmetabuilder.cpp
index 8e1732be9..23feeafad 100644
--- a/sources/shiboken2/ApiExtractor/abstractmetabuilder.cpp
+++ b/sources/shiboken2/ApiExtractor/abstractmetabuilder.cpp
@@ -1878,6 +1878,12 @@ static inline QString msgUnmatchedParameterType(const ArgumentModelItem &arg, in
return result;
}
+static inline QString msgUnmatchedReturnType(const FunctionModelItem &functionItem)
+{
+ return QLatin1String("unmatched return type '")
+ + functionItem->type().toString() + QLatin1Char('\'');
+}
+
static inline QString msgVoidParameterType(const ArgumentModelItem &arg, int n)
{
QString result;
@@ -1888,6 +1894,22 @@ static inline QString msgVoidParameterType(const ArgumentModelItem &arg, int n)
return result;
}
+static QString msgSkippingFunction(const FunctionModelItem &functionItem,
+ const QString &signature, const QString &why)
+{
+ QString result;
+ QTextStream str(&result);
+ str << "skipping ";
+ if (functionItem->isAbstract())
+ str << "abstract ";
+ str << "function '" << signature << "', " << why;
+ if (functionItem->isAbstract()) {
+ str << "\nThis will lead to compilation errors due to not "
+ "being able to instantiate the wrapper.";
+ }
+ return result;
+}
+
static inline AbstractMetaFunction::FunctionType functionTypeFromCodeModel(CodeModel::FunctionType ft)
{
AbstractMetaFunction::FunctionType result = AbstractMetaFunction::NormalFunction;
@@ -2048,13 +2070,11 @@ AbstractMetaFunction *AbstractMetaBuilderPrivate::traverseFunction(FunctionModel
bool ok;
AbstractMetaType *type = translateType(returnType, &ok);
-
if (!ok) {
Q_ASSERT(type == 0);
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("skipping function '%1', unmatched return type '%2'")
- .arg(originalQualifiedSignatureWithReturn,
- functionItem->type().toString());
+ const QString reason = msgUnmatchedReturnType(functionItem);
+ qCWarning(lcShiboken, "%s",
+ qPrintable(msgSkippingFunction(functionItem, originalQualifiedSignatureWithReturn, reason)));
m_rejectedFunctions.insert(originalQualifiedSignatureWithReturn, AbstractMetaBuilder::UnmatchedReturnType);
delete metaFunction;
return nullptr;
@@ -2104,9 +2124,8 @@ AbstractMetaFunction *AbstractMetaBuilderPrivate::traverseFunction(FunctionModel
}
Q_ASSERT(metaType == 0);
const QString reason = msgUnmatchedParameterType(arg, i);
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("skipping function '%1', %2")
- .arg(originalQualifiedSignatureWithReturn, reason);
+ qCWarning(lcShiboken, "%s",
+ qPrintable(msgSkippingFunction(functionItem, originalQualifiedSignatureWithReturn, reason)));
const QString rejectedFunctionSignature = originalQualifiedSignatureWithReturn
+ QLatin1String(": ") + reason;
m_rejectedFunctions.insert(rejectedFunctionSignature, AbstractMetaBuilder::UnmatchedArgumentType);
@@ -2116,9 +2135,8 @@ AbstractMetaFunction *AbstractMetaBuilderPrivate::traverseFunction(FunctionModel
if (metaType == Q_NULLPTR) {
const QString reason = msgVoidParameterType(arg, i);
- qCWarning(lcShiboken).noquote().nospace()
- << QString::fromLatin1("skipping function '%1': %2")
- .arg(originalQualifiedSignatureWithReturn, reason);
+ qCWarning(lcShiboken, "%s",
+ qPrintable(msgSkippingFunction(functionItem, originalQualifiedSignatureWithReturn, reason)));
const QString rejectedFunctionSignature = originalQualifiedSignatureWithReturn
+ QLatin1String(": ") + reason;
m_rejectedFunctions.insert(rejectedFunctionSignature, AbstractMetaBuilder::UnmatchedArgumentType);
diff --git a/sources/shiboken2/ApiExtractor/abstractmetalang.cpp b/sources/shiboken2/ApiExtractor/abstractmetalang.cpp
index ba33f78d9..5be7050bf 100644
--- a/sources/shiboken2/ApiExtractor/abstractmetalang.cpp
+++ b/sources/shiboken2/ApiExtractor/abstractmetalang.cpp
@@ -189,6 +189,11 @@ AbstractMetaTypeCList AbstractMetaType::nestedArrayTypes() const
return result;
}
+bool AbstractMetaType::isConstRef() const
+{
+ return isConstant() && m_referenceType == LValueReference && indirections() == 0;
+}
+
QString AbstractMetaType::cppSignature() const
{
if (m_cachedCppSignature.isEmpty())
@@ -201,10 +206,8 @@ AbstractMetaType::TypeUsagePattern AbstractMetaType::determineUsagePattern() con
if (m_typeEntry->isTemplateArgument() || m_referenceType == RValueReference)
return InvalidPattern;
- if (m_typeEntry->isPrimitive() && (!actualIndirections()
- || (isConstant() && m_referenceType == LValueReference && !indirections()))) {
+ if (m_typeEntry->isPrimitive() && (actualIndirections() == 0 || isConstRef()))
return PrimitivePattern;
- }
if (m_typeEntry->isVoid())
return NativePointerPattern;
@@ -212,7 +215,7 @@ AbstractMetaType::TypeUsagePattern AbstractMetaType::determineUsagePattern() con
if (m_typeEntry->isVarargs())
return VarargsPattern;
- if (m_typeEntry->isEnum() && actualIndirections() == 0)
+ if (m_typeEntry->isEnum() && (actualIndirections() == 0 || isConstRef()))
return EnumPattern;
if (m_typeEntry->isObject()) {
@@ -228,8 +231,7 @@ AbstractMetaType::TypeUsagePattern AbstractMetaType::determineUsagePattern() con
if (m_typeEntry->isSmartPointer() && indirections() == 0)
return SmartPointerPattern;
- if (m_typeEntry->isFlags() && indirections() == 0
- && (isConstant() == (m_referenceType == LValueReference)))
+ if (m_typeEntry->isFlags() && (actualIndirections() == 0 || isConstRef()))
return FlagsPattern;
if (m_typeEntry->isArray())
@@ -1754,7 +1756,7 @@ void AbstractMetaClass::addDefaultConstructor()
f->setArguments(AbstractMetaArgumentList());
f->setDeclaringClass(this);
- f->setAttributes(AbstractMetaAttributes::Public | AbstractMetaAttributes::FinalInTargetLang);
+ f->setAttributes(Public | FinalInTargetLang | AddedMethod);
f->setImplementingClass(this);
f->setOriginalAttributes(f->attributes());
@@ -1782,7 +1784,7 @@ void AbstractMetaClass::addDefaultCopyConstructor(bool isPrivate)
arg->setName(name());
f->addArgument(arg);
- AbstractMetaAttributes::Attributes attr = AbstractMetaAttributes::FinalInTargetLang;
+ AbstractMetaAttributes::Attributes attr = FinalInTargetLang | AddedMethod;
if (isPrivate)
attr |= AbstractMetaAttributes::Private;
else
@@ -2154,8 +2156,11 @@ void AbstractMetaClass::fixFunctions()
funcsToAdd << sf;
}
- for (AbstractMetaFunction *f : qAsConst(funcsToAdd))
- funcs << f->copy();
+ for (AbstractMetaFunction *f : qAsConst(funcsToAdd)) {
+ AbstractMetaFunction *copy = f->copy();
+ (*copy) += AddedMethod;
+ funcs.append(copy);
+ }
if (superClass)
superClass = superClass->baseClass();
diff --git a/sources/shiboken2/ApiExtractor/abstractmetalang.h b/sources/shiboken2/ApiExtractor/abstractmetalang.h
index c31c5a386..d1a0fbf88 100644
--- a/sources/shiboken2/ApiExtractor/abstractmetalang.h
+++ b/sources/shiboken2/ApiExtractor/abstractmetalang.h
@@ -137,7 +137,9 @@ public:
FinalCppClass = 0x00100000,
VirtualCppMethod = 0x00200000,
OverriddenCppMethod = 0x00400000,
- FinalCppMethod = 0x00800000
+ FinalCppMethod = 0x00800000,
+ // Add by meta builder (implicit constructors, inherited methods, etc)
+ AddedMethod = 0x01000000
};
Q_DECLARE_FLAGS(Attributes, Attribute)
Q_FLAG(Attribute)
@@ -434,6 +436,8 @@ public:
m_constant = constant;
}
+ bool isConstRef() const;
+
ReferenceType referenceType() const { return m_referenceType; }
void setReferenceType(ReferenceType ref) { m_referenceType = ref; }
diff --git a/sources/shiboken2/ApiExtractor/docparser.cpp b/sources/shiboken2/ApiExtractor/docparser.cpp
index 0cbae33eb..9305332ba 100644
--- a/sources/shiboken2/ApiExtractor/docparser.cpp
+++ b/sources/shiboken2/ApiExtractor/docparser.cpp
@@ -82,6 +82,7 @@ bool DocParser::skipForQuery(const AbstractMetaFunction *func)
{
// Skip private functions and copies created by AbstractMetaClass::fixFunctions()
if (!func || func->isPrivate()
+ || (func->attributes() & AbstractMetaAttributes::AddedMethod) != 0
|| func->isModifiedRemoved()
|| func->declaringClass() != func->ownerClass()
|| func->isCastOperator()) {
@@ -124,9 +125,9 @@ QString DocParser::msgCannotFindDocumentation(const QString &fileName,
const AbstractMetaFunction *function,
const QString &query)
{
- return msgCannotFindDocumentation(fileName, "function",
- metaClass->name() + QLatin1String("::") + function->name() + QLatin1String("()"),
- query);
+ const QString name = metaClass->name() + QLatin1String("::")
+ + function->minimalSignature();
+ return msgCannotFindDocumentation(fileName, "function", name, query);
}
QString DocParser::msgCannotFindDocumentation(const QString &fileName,
diff --git a/sources/shiboken2/ApiExtractor/qtdocparser.cpp b/sources/shiboken2/ApiExtractor/qtdocparser.cpp
index 8917f801e..b0058d6ea 100644
--- a/sources/shiboken2/ApiExtractor/qtdocparser.cpp
+++ b/sources/shiboken2/ApiExtractor/qtdocparser.cpp
@@ -35,6 +35,8 @@
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
+#include <QtCore/QXmlStreamAttributes>
+#include <QtCore/QXmlStreamReader>
#include <QUrl>
Documentation QtDocParser::retrieveModuleDocumentation()
@@ -48,9 +50,6 @@ static void formatFunctionArgTypeQuery(QTextStream &str, const AbstractMetaArgum
if (metaType->isConstant())
str << "const " ;
switch (metaType->typeUsagePattern()) {
- case AbstractMetaType::PrimitivePattern:
- str << metaType->name();
- break;
case AbstractMetaType::FlagsPattern: {
// Modify qualified name "QFlags<Qt::AlignmentFlag>" with name "Alignment"
// to "Qt::Alignment" as seen by qdoc.
@@ -92,6 +91,119 @@ static void formatFunctionArgTypeQuery(QTextStream &str, const AbstractMetaArgum
str << ' ' << QByteArray(metaType->indirections(), '*');
}
+enum FunctionMatchFlags
+{
+ MatchArgumentCount = 0x1,
+ MatchArgumentType = 0x2,
+ DescriptionOnly = 0x4
+};
+
+static QString functionXQuery(const QString &classQuery,
+ const AbstractMetaFunction *func,
+ unsigned matchFlags = MatchArgumentCount | MatchArgumentType
+ | DescriptionOnly)
+{
+ QString result;
+ QTextStream str(&result);
+ const AbstractMetaArgumentList &arguments = func->arguments();
+ str << classQuery << "/function[@name=\"" << func->originalName()
+ << "\" and @const=\"" << (func->isConstant() ? "true" : "false") << '"';
+ if (matchFlags & MatchArgumentCount)
+ str << " and count(parameter)=" << arguments.size();
+ str << ']';
+ if (!arguments.isEmpty() && (matchFlags & MatchArgumentType)) {
+ for (int i = 0, size = arguments.size(); i < size; ++i) {
+ str << "/parameter[" << (i + 1) << "][@type=\"";
+ // Fixme: Use arguments.at(i)->type()->originalTypeDescription()
+ // instead to get unresolved typedefs?
+ formatFunctionArgTypeQuery(str, arguments.at(i));
+ str << "\"]/..";
+ }
+ }
+ if (matchFlags & DescriptionOnly)
+ str << "/description";
+ return result;
+}
+
+static QStringList signaturesFromWebXml(QString w)
+{
+ QStringList result;
+ if (w.isEmpty())
+ return result;
+ w.prepend(QLatin1String("<root>")); // Fake root element
+ w.append(QLatin1String("</root>"));
+ QXmlStreamReader reader(w);
+ while (!reader.atEnd()) {
+ if (reader.readNext() == QXmlStreamReader::StartElement
+ && reader.name() == QLatin1String("function")) {
+ result.append(reader.attributes().value(QStringLiteral("signature")).toString());
+ }
+ }
+ return result;
+}
+
+static QString msgArgumentCountMatch(const AbstractMetaFunction *func,
+ const QStringList &matches)
+{
+ QString result;
+ QTextStream str(&result);
+ str << "\n Note: Querying for the argument count=="
+ << func->arguments().size() << " only yields " << matches.size()
+ << " matches";
+ if (!matches.isEmpty())
+ str << ": \"" << matches.join(QLatin1String("\", \"")) << '"';
+ return result;
+}
+
+QString QtDocParser::queryFunctionDocumentation(const QString &sourceFileName,
+ const AbstractMetaClass* metaClass,
+ const QString &classQuery,
+ const AbstractMetaFunction *func,
+ const DocModificationList &signedModifs,
+ QXmlQuery &xquery,
+ QString *errorMessage)
+{
+ DocModificationList funcModifs;
+ for (const DocModification &funcModif : signedModifs) {
+ if (funcModif.signature() == func->minimalSignature())
+ funcModifs.append(funcModif);
+ }
+
+ // Properties
+ if (func->isPropertyReader() || func->isPropertyWriter() || func->isPropertyResetter()) {
+ const QString propertyQuery = classQuery + QLatin1String("/property[@name=\"")
+ + func->propertySpec()->name() + QLatin1String("\"]/description");
+ const QString properyDocumentation = getDocumentation(xquery, propertyQuery, funcModifs);
+ if (properyDocumentation.isEmpty())
+ *errorMessage = msgCannotFindDocumentation(sourceFileName, metaClass, func, propertyQuery);
+ return properyDocumentation;
+ }
+
+ // Query with full match of argument types
+ const QString fullQuery = functionXQuery(classQuery, func);
+ const QString result = getDocumentation(xquery, fullQuery, funcModifs);
+ if (!result.isEmpty())
+ return result;
+ *errorMessage = msgCannotFindDocumentation(sourceFileName, metaClass, func, fullQuery);
+ if (func->arguments().isEmpty()) // No arguments, can't be helped
+ return result;
+ // Test whether some mismatch in argument types occurred by checking for
+ // the argument count only. Include the outer <function> element.
+ QString countOnlyQuery = functionXQuery(classQuery, func, MatchArgumentCount);
+ QStringList signatures =
+ signaturesFromWebXml(getDocumentation(xquery, countOnlyQuery, funcModifs));
+ if (signatures.size() == 1) {
+ // One match was found. Repeat the query restricted to the <description>
+ // element and use the result with a warning.
+ countOnlyQuery = functionXQuery(classQuery, func, MatchArgumentCount | DescriptionOnly);
+ errorMessage->append(QLatin1String("\n Falling back to \"") + signatures.constFirst()
+ + QLatin1String("\" obtained by matching the argument count only."));
+ return getDocumentation(xquery, countOnlyQuery, funcModifs);
+ }
+ *errorMessage += msgArgumentCountMatch(func, signatures);
+ return result;
+}
+
void QtDocParser::fillDocumentation(AbstractMetaClass* metaClass)
{
if (!metaClass)
@@ -144,40 +256,16 @@ void QtDocParser::fillDocumentation(AbstractMetaClass* metaClass)
qCWarning(lcShiboken(), "%s", qPrintable(msgCannotFindDocumentation(sourceFileName, "class", className, query)));
metaClass->setDocumentation(doc);
-
//Functions Documentation
+ QString errorMessage;
const AbstractMetaFunctionList &funcs = DocParser::documentableFunctions(metaClass);
for (AbstractMetaFunction *func : funcs) {
- query.clear();
- QTextStream str(&query);
- str << classQuery;
- // properties
- if (func->isPropertyReader() || func->isPropertyWriter() || func->isPropertyResetter()) {
- str << "/property[@name=\"" << func->propertySpec()->name() << "\"]";
- } else { // normal methods
- str << "/function[@name=\"" << func->originalName() << "\" and count(parameter)="
- << func->arguments().count() << " and @const=\""
- << (func->isConstant() ? "true" : "false") << "\"]";
-
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (int i = 0, size = arguments.size(); i < size; ++i) {
- str << "/parameter[" << (i + 1) << "][@type=\"";
- formatFunctionArgTypeQuery(str, arguments.at(i));
- str << "\"]/..";
- }
- }
- str << "/description";
- DocModificationList funcModifs;
- for (const DocModification &funcModif : qAsConst(signedModifs)) {
- if (funcModif.signature() == func->minimalSignature())
- funcModifs.append(funcModif);
- }
- doc.setValue(getDocumentation(xquery, query, funcModifs));
- if (doc.isEmpty()) {
- qCWarning(lcShiboken(), "%s",
- qPrintable(msgCannotFindDocumentation(sourceFileName, metaClass, func, query)));
- }
- func->setDocumentation(doc);
+ const QString documentation =
+ queryFunctionDocumentation(sourceFileName, metaClass, classQuery,
+ func, signedModifs, xquery, &errorMessage);
+ if (!errorMessage.isEmpty())
+ qCWarning(lcShiboken(), "%s", qPrintable(errorMessage));
+ func->setDocumentation(Documentation(documentation));
}
#if 0
// Fields
@@ -206,18 +294,28 @@ void QtDocParser::fillDocumentation(AbstractMetaClass* metaClass)
}
}
+static QString qmlReferenceLink(const QFileInfo &qmlModuleFi)
+{
+ QString result;
+ QTextStream(&result) << "<para>The module also provides <link"
+ << " type=\"page\""
+ << " page=\"http://doc.qt.io/qt-5/" << qmlModuleFi.baseName() << ".html\""
+ << ">QML types</link>.</para>";
+ return result;
+}
+
Documentation QtDocParser::retrieveModuleDocumentation(const QString& name)
{
// TODO: This method of acquiring the module name supposes that the target language uses
// dots as module separators in package names. Improve this.
QString moduleName = name;
moduleName.remove(0, name.lastIndexOf(QLatin1Char('.')) + 1);
- QString sourceFile = documentationDataDirectory() + QLatin1Char('/')
- + moduleName.toLower() + QLatin1String(".xml");
+ const QString prefix = documentationDataDirectory() + QLatin1Char('/')
+ + moduleName.toLower();
+ QString sourceFile = prefix + QLatin1String(".xml");
if (!QFile::exists(sourceFile))
- sourceFile = documentationDataDirectory() + QLatin1Char('/')
- + moduleName.toLower() + QLatin1String("-module.webxml");
+ sourceFile = prefix + QLatin1String("-module.webxml");
if (!QFile::exists(sourceFile)) {
qCWarning(lcShiboken).noquote().nospace()
<< "Can't find qdoc file for module " << name << ", tried: "
@@ -231,8 +329,22 @@ Documentation QtDocParser::retrieveModuleDocumentation(const QString& name)
// Module documentation
QString query = QLatin1String("/WebXML/document/module[@name=\"")
+ moduleName + QLatin1String("\"]/description");
- const Documentation doc = getDocumentation(xquery, query, DocModificationList());
- if (doc.isEmpty())
+ Documentation doc = getDocumentation(xquery, query, DocModificationList());
+ if (doc.isEmpty()) {
qCWarning(lcShiboken(), "%s", qPrintable(msgCannotFindDocumentation(sourceFile, "module", name, query)));
+ return doc;
+ }
+
+ // If a QML module info file exists, insert a link to the Qt docs.
+ const QFileInfo qmlModuleFi(prefix + QLatin1String("-qmlmodule.webxml"));
+ if (qmlModuleFi.isFile()) {
+ QString docString = doc.value();
+ const int pos = docString.lastIndexOf(QLatin1String("</description>"));
+ if (pos != -1) {
+ docString.insert(pos, qmlReferenceLink(qmlModuleFi));
+ doc.setValue(docString);
+ }
+ }
+
return doc;
}
diff --git a/sources/shiboken2/ApiExtractor/qtdocparser.h b/sources/shiboken2/ApiExtractor/qtdocparser.h
index 3ea0122b4..b5f0e51d8 100644
--- a/sources/shiboken2/ApiExtractor/qtdocparser.h
+++ b/sources/shiboken2/ApiExtractor/qtdocparser.h
@@ -38,6 +38,15 @@ public:
void fillDocumentation(AbstractMetaClass* metaClass) override;
Documentation retrieveModuleDocumentation() override;
Documentation retrieveModuleDocumentation(const QString& name) override;
+
+private:
+ QString queryFunctionDocumentation(const QString &sourceFileName,
+ const AbstractMetaClass* metaClass,
+ const QString &classQuery,
+ const AbstractMetaFunction *func,
+ const DocModificationList &signedModifs,
+ QXmlQuery &xquery,
+ QString *errorMessage);
};
#endif // QTDOCPARSER_H
diff --git a/sources/shiboken2/CMakeLists.txt b/sources/shiboken2/CMakeLists.txt
index 3efc6fefe..0a2920e4f 100644
--- a/sources/shiboken2/CMakeLists.txt
+++ b/sources/shiboken2/CMakeLists.txt
@@ -19,8 +19,8 @@ if (USE_PYTHON_VERSION)
find_package(PythonInterp ${USE_PYTHON_VERSION} REQUIRED)
find_package(PythonLibs ${USE_PYTHON_VERSION} REQUIRED)
else()
- find_package(PythonInterp 2.6)
- find_package(PythonLibs 2.6)
+ find_package(PythonInterp 2.7)
+ find_package(PythonLibs 2.7)
endif()
macro(get_python_arch)
diff --git a/sources/shiboken2/generator/qtdoc/qtdocgenerator.cpp b/sources/shiboken2/generator/qtdoc/qtdocgenerator.cpp
index 7206d7ca8..489d498f9 100644
--- a/sources/shiboken2/generator/qtdoc/qtdocgenerator.cpp
+++ b/sources/shiboken2/generator/qtdoc/qtdocgenerator.cpp
@@ -464,8 +464,10 @@ QString QtXmlToSphinx::transform(const QString& doc)
while (!reader.atEnd()) {
QXmlStreamReader::TokenType token = reader.readNext();
if (reader.hasError()) {
- const QString message = QLatin1String("XML Error: ") + reader.errorString()
- + QLatin1Char('\n') + doc;
+ QString message;
+ QTextStream(&message) << "XML Error "
+ << reader.errorString() << " at " << reader.lineNumber()
+ << ':' << reader.columnNumber() << '\n' << doc;
m_output << INDENT << message;
qCWarning(lcShiboken).noquote().nospace() << message;
break;
@@ -2194,44 +2196,61 @@ void QtDocGenerator::writeAdditionalDocumentation()
qPrintable(FileOut::msgCannotOpenForReading(additionalDocumentationFile)));
return;
}
- const QByteArray contents = additionalDocumentationFile.readAll();
- const QStringList lines = QFile::decodeName(contents).split(QLatin1Char('\n'));
- QFileInfoList additionalDocFiles;
- additionalDocFiles.reserve(lines.size());
- for (const QString &lineIn : lines) {
- const QString line = lineIn.trimmed();
- if (!line.isEmpty() && !line.startsWith(QLatin1Char('#'))) {
+
+ QDir outDir(outputDirectory());
+ const QString rstSuffix = fileNameSuffix();
+
+ QString errorMessage;
+ int successCount = 0;
+ int count = 0;
+
+ QString targetDir = outDir.absolutePath();
+
+ while (!additionalDocumentationFile.atEnd()) {
+ const QByteArray lineBA = additionalDocumentationFile.readLine().trimmed();
+ if (lineBA.isEmpty() || lineBA.startsWith('#'))
+ continue;
+ const QString line = QFile::decodeName(lineBA);
+ // Parse "[directory]" specification
+ if (line.size() > 2 && line.startsWith(QLatin1Char('[')) && line.endsWith(QLatin1Char(']'))) {
+ const QString dir = line.mid(1, line.size() - 2);
+ if (dir.isEmpty() || dir == QLatin1String(".")) {
+ targetDir = outDir.absolutePath();
+ } else {
+ if (!outDir.exists(dir) && !outDir.mkdir(dir)) {
+ qCWarning(lcShiboken, "Cannot create directory %s under %s",
+ qPrintable(dir),
+ qPrintable(QDir::toNativeSeparators(outputDirectory())));
+ break;
+ }
+ targetDir = outDir.absoluteFilePath(dir);
+ }
+ } else {
+ // Normal file entry
QFileInfo fi(m_docDataDir + QLatin1Char('/') + line);
if (fi.isFile()) {
- additionalDocFiles.append(fi);
+ const QString rstFileName = fi.baseName() + rstSuffix;
+ const QString rstFile = targetDir + QLatin1Char('/') + rstFileName;
+ if (QtXmlToSphinx::convertToRst(this, fi.absoluteFilePath(),
+ rstFile, QString(), &errorMessage)) {
+ ++successCount;
+ qCDebug(lcShiboken).nospace().noquote() << __FUNCTION__
+ << " converted " << fi.fileName()
+ << ' ' << rstFileName;
+ } else {
+ qCWarning(lcShiboken, "%s", qPrintable(errorMessage));
+ }
} else {
qCWarning(lcShiboken, "%s",
qPrintable(msgNonExistentAdditionalDocFile(m_docDataDir, line)));
}
+ ++count;
}
}
additionalDocumentationFile.close();
- const QString rstPrefix = outputDirectory() + QLatin1Char('/');
- const QString rstSuffix = fileNameSuffix();
-
- QString errorMessage;
- int successCount = 0;
- for (const QFileInfo &additionalDocFile : additionalDocFiles) {
- const QString rstFileName = additionalDocFile.baseName() + rstSuffix;
- const QString rstFile = rstPrefix + rstFileName;
- if (QtXmlToSphinx::convertToRst(this, additionalDocFile.absoluteFilePath(),
- rstFile, QString(), &errorMessage)) {
- ++successCount;
- qCDebug(lcShiboken).nospace().noquote() << __FUNCTION__
- << " converted " << additionalDocFile.fileName()
- << ' ' << rstFileName;
- } else {
- qCWarning(lcShiboken, "%s", qPrintable(errorMessage));
- }
- }
qCInfo(lcShiboken, "Created %d/%d additional documentation files.",
- successCount, additionalDocFiles.size());
+ successCount, count);
}
bool QtDocGenerator::doSetup(const QMap<QString, QString>& args)
diff --git a/sources/shiboken2/generator/shiboken2/shibokengenerator.cpp b/sources/shiboken2/generator/shiboken2/shibokengenerator.cpp
index b2734418c..6165ef009 100644
--- a/sources/shiboken2/generator/shiboken2/shibokengenerator.cpp
+++ b/sources/shiboken2/generator/shiboken2/shibokengenerator.cpp
@@ -1996,6 +1996,17 @@ static QString getConverterTypeSystemVariableArgument(const QString& code, int p
return arg;
}
typedef QPair<QString, QString> StringPair;
+
+static QString msgCannotFindType(const QString &type, const QString &variable,
+ const QString &why)
+{
+ QString result;
+ QTextStream(&result) << "Could not find type '"
+ << type << "' for use in '" << variable << "' conversion: " << why
+ << "\nMake sure to use the full C++ name, e.g. 'Namespace::Class'.";
+ return result;
+}
+
void ShibokenGenerator::replaceConverterTypeSystemVariable(TypeSystemConverterVariable converterVariable, QString& code)
{
QVector<StringPair> replacements;
@@ -2005,12 +2016,12 @@ void ShibokenGenerator::replaceConverterTypeSystemVariable(TypeSystemConverterVa
const QStringList list = match.capturedTexts();
QString conversionString = list.constFirst();
QString conversionTypeName = list.constLast();
- const AbstractMetaType* conversionType = buildAbstractMetaTypeFromString(conversionTypeName);
+ QString message;
+ const AbstractMetaType *conversionType = buildAbstractMetaTypeFromString(conversionTypeName, &message);
if (!conversionType) {
- qFatal(qPrintable(QString::fromLatin1("Could not find type '%1' for use in '%2' conversion. "
- "Make sure to use the full C++ name, e.g. 'Namespace::Class'.")
- .arg(conversionTypeName).arg(m_typeSystemConvName[converterVariable])), NULL);
-
+ qFatal("%s", qPrintable(msgCannotFindType(conversionTypeName,
+ m_typeSystemConvName[converterVariable],
+ message)));
}
QString conversion;
QTextStream c(&conversion);
@@ -2312,7 +2323,8 @@ bool ShibokenGenerator::isCopyable(const AbstractMetaClass *metaClass)
return false;
}
-AbstractMetaType* ShibokenGenerator::buildAbstractMetaTypeFromString(QString typeSignature)
+AbstractMetaType *ShibokenGenerator::buildAbstractMetaTypeFromString(QString typeSignature,
+ QString *errorMessage)
{
typeSignature = typeSignature.trimmed();
if (typeSignature.startsWith(QLatin1String("::")))
@@ -2348,9 +2360,10 @@ AbstractMetaType* ShibokenGenerator::buildAbstractMetaTypeFromString(QString typ
typeString.remove(0, 2);
QString adjustedTypeName = typeString;
- QStringList instantiatedTypes;
+ AbstractMetaTypeList instantiations;
int lpos = typeString.indexOf(QLatin1Char('<'));
if (lpos > -1) {
+ QStringList instantiatedTypes;
int rpos = typeString.lastIndexOf(QLatin1Char('>'));
if ((lpos != -1) && (rpos != -1)) {
QString type = typeString.mid(lpos + 1, rpos - lpos - 1);
@@ -2369,25 +2382,57 @@ AbstractMetaType* ShibokenGenerator::buildAbstractMetaTypeFromString(QString typ
instantiatedTypes << type.mid(start).trimmed();
adjustedTypeName.truncate(lpos);
}
+ for (const QString &instantiatedType : qAsConst(instantiatedTypes)) {
+ AbstractMetaType *tmplArgType = buildAbstractMetaTypeFromString(instantiatedType);
+ if (!tmplArgType) {
+ if (errorMessage) {
+ QTextStream(errorMessage) << "Cannot find template type \""
+ << instantiatedType << "\" for \"" << typeSignature << "\".";
+ }
+ return nullptr;
+ }
+ instantiations.append(tmplArgType);
+ }
}
- TypeEntry* typeEntry = TypeDatabase::instance()->findType(adjustedTypeName);
+ TypeEntry *typeEntry = nullptr;
+ AbstractMetaType::TypeUsagePattern pattern = AbstractMetaType::InvalidPattern;
- AbstractMetaType* metaType = 0;
- if (typeEntry) {
- metaType = new AbstractMetaType();
- metaType->setTypeEntry(typeEntry);
- metaType->setIndirections(indirections);
- metaType->setReferenceType(refType);
- metaType->setConstant(isConst);
- metaType->setTypeUsagePattern(AbstractMetaType::ContainerPattern);
- for (const QString &instantiation : qAsConst(instantiatedTypes)) {
- AbstractMetaType* tmplArgType = buildAbstractMetaTypeFromString(instantiation);
- metaType->addInstantiation(tmplArgType);
+ if (instantiations.size() == 1
+ && instantiations.at(0)->typeUsagePattern() == AbstractMetaType::EnumPattern
+ && adjustedTypeName == QLatin1String("QFlags")) {
+ pattern = AbstractMetaType::FlagsPattern;
+ typeEntry = TypeDatabase::instance()->findType(typeSignature);
+ } else {
+ typeEntry = TypeDatabase::instance()->findType(adjustedTypeName);
+ }
+
+ if (!typeEntry) {
+ if (errorMessage) {
+ QTextStream(errorMessage) << "Cannot find type \"" << adjustedTypeName
+ << "\" for \"" << typeSignature << "\".";
}
+ return nullptr;
+ }
+
+ AbstractMetaType *metaType = new AbstractMetaType();
+ metaType->setTypeEntry(typeEntry);
+ metaType->setIndirections(indirections);
+ metaType->setReferenceType(refType);
+ metaType->setConstant(isConst);
+ metaType->setTypeUsagePattern(AbstractMetaType::ContainerPattern);
+ switch (pattern) {
+ case AbstractMetaType::FlagsPattern:
+ metaType->setTypeUsagePattern(pattern);
+ break;
+ default:
+ metaType->setInstantiations(instantiations);
+ metaType->setTypeUsagePattern(AbstractMetaType::ContainerPattern);
metaType->decideUsagePattern();
- m_metaTypeFromStringCache.insert(typeSignature, metaType);
+ break;
}
+
+ m_metaTypeFromStringCache.insert(typeSignature, metaType);
return metaType;
}
diff --git a/sources/shiboken2/generator/shiboken2/shibokengenerator.h b/sources/shiboken2/generator/shiboken2/shibokengenerator.h
index d44f4aa66..3271d741d 100644
--- a/sources/shiboken2/generator/shiboken2/shibokengenerator.h
+++ b/sources/shiboken2/generator/shiboken2/shibokengenerator.h
@@ -467,7 +467,8 @@ public:
* \param typeSignature The string describing the type to be built.
* \return A new AbstractMetaType object that must be deleted by the caller, or a NULL pointer in case of failure.
*/
- AbstractMetaType* buildAbstractMetaTypeFromString(QString typeSignature);
+ AbstractMetaType *buildAbstractMetaTypeFromString(QString typeSignature,
+ QString *errorMessage = nullptr);
/// Creates an AbstractMetaType object from a TypeEntry.
AbstractMetaType* buildAbstractMetaTypeFromTypeEntry(const TypeEntry* typeEntry);
diff --git a/sources/shiboken2/tests/libsample/objecttype.h b/sources/shiboken2/tests/libsample/objecttype.h
index 9d659faa4..bcb4f3332 100644
--- a/sources/shiboken2/tests/libsample/objecttype.h
+++ b/sources/shiboken2/tests/libsample/objecttype.h
@@ -53,6 +53,10 @@ struct Event
Event(EventType eventType) : m_eventType(eventType) {}
EventType eventType() { return m_eventType; }
+
+ void setEventType(EventType et) { m_eventType = et; }
+ void setEventTypeByConstRef(const EventType &et) { m_eventType = et; }
+
private:
EventType m_eventType;
};
diff --git a/sources/shiboken2/tests/samplebinding/enum_test.py b/sources/shiboken2/tests/samplebinding/enum_test.py
index 0a5a84c4a..7e1cac8c0 100644
--- a/sources/shiboken2/tests/samplebinding/enum_test.py
+++ b/sources/shiboken2/tests/samplebinding/enum_test.py
@@ -115,6 +115,14 @@ class EnumTest(unittest.TestCase):
sum = Event.EventTypeClass.Value1 + Event.EventTypeClass.Value2
self.assertEqual(sum, 1)
+ def testSetEnum(self):
+ event = Event(Event.ANY_EVENT)
+ self.assertEqual(event.eventType(), Event.ANY_EVENT)
+ event.setEventType(Event.BASIC_EVENT)
+ self.assertEqual(event.eventType(), Event.BASIC_EVENT)
+ event.setEventTypeByConstRef(Event.SOME_EVENT)
+ self.assertEqual(event.eventType(), Event.SOME_EVENT)
+
def testEnumTpPrintImplementation(self):
'''Without SbkEnum.tp_print 'print' returns the enum represented as an int.'''
tmpfile = createTempFile()