From 8cc21eee84d96240510750d627e4bfccff5f40db Mon Sep 17 00:00:00 2001 From: Hugo Parente Lima Date: Thu, 30 Sep 2010 17:33:26 -0300 Subject: Fix bug#267 - "Provide human-readable object strings (__repr__)" Reviewer: Luciano Wolf Marcelo Lira --- generator/cppgenerator.cpp | 23 +++++++++++++++++++++++ generator/cppgenerator.h | 1 + 2 files changed, 24 insertions(+) (limited to 'generator') diff --git a/generator/cppgenerator.cpp b/generator/cppgenerator.cpp index da15c4d4c..15f30afad 100644 --- a/generator/cppgenerator.cpp +++ b/generator/cppgenerator.cpp @@ -2371,6 +2371,10 @@ void CppGenerator::writeClassDefinition(QTextStream& s, const AbstractMetaClass* if (m_tpFuncs.contains(func->name())) m_tpFuncs[func->name()] = cpythonFunctionName(func); } + if (m_tpFuncs["__repr__"] == "0" + && metaClass->hasToStringCapability()) { + m_tpFuncs["__repr__"] = writeReprFunction(s, metaClass); + } // class or some ancestor has multiple inheritance const AbstractMetaClass* miClass = getMultipleInheritingClass(metaClass); @@ -3880,4 +3884,23 @@ void CppGenerator::writeStdListWrapperMethods(QTextStream& s, const AbstractMeta s << endl << "}" << endl; } +QString CppGenerator::writeReprFunction(QTextStream& s, const AbstractMetaClass* metaClass) +{ + QString funcName = cpythonBaseName(metaClass) + "__repr__"; + s << "extern \"C\"" << endl; + s << '{' << endl; + s << "static PyObject* " << funcName << "(PyObject* pyObj)" << endl; + s << '{' << endl; + s << INDENT << "QBuffer buffer;" << endl; + s << INDENT << "buffer.open(QBuffer::ReadWrite);" << endl; + s << INDENT << "QDebug dbg(&buffer);" << endl; + s << INDENT << "dbg << "; + writeToCppConversion(s, metaClass, "pyObj"); + s << ';' << endl; + s << INDENT << "buffer.close();" << endl; + s << INDENT << "return PyString_FromFormat(\"<" << metaClass->package() << ".%s at %p>\", buffer.data().constData(), pyObj);" << endl; + s << '}' << endl; + s << "} // extern C" << endl << endl;; + return funcName; +} diff --git a/generator/cppgenerator.h b/generator/cppgenerator.h index b4d68dc45..3869b1bc1 100644 --- a/generator/cppgenerator.h +++ b/generator/cppgenerator.h @@ -190,6 +190,7 @@ private: // Write default implementations for sequence protocol void writeStdListWrapperMethods(QTextStream& s, const AbstractMetaClass* metaClass); + QString writeReprFunction(QTextStream& s, const AbstractMetaClass* metaClass); // Maps special function names to function parameters and return types // used by CPython API in the sequence protocol. -- cgit v1.2.3